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
80 //______________________________________________________________________________
81 GnuBook.prototype.init = function() {
83 var startIndex = undefined;
85 // Find start index and mode if set in location hash
86 var params = this.paramsFromFragment(window.location.hash);
88 if ('undefined' != typeof(params.index)) {
89 startIndex = params.index;
90 } else if ('undefined' != typeof(params.page)) {
91 startIndex = this.getPageIndex(params.page);
94 if ('undefined' == typeof(startIndex)) {
95 if ('undefined' != typeof(this.titleLeaf)) {
96 startIndex = this.leafNumToIndex(this.titleLeaf);
100 if ('undefined' == typeof(startIndex)) {
104 if ('undefined' != typeof(params.mode)) {
105 this.mode = params.mode;
108 // Set document title -- may have already been set in enclosing html for
109 // search engine visibility
110 document.title = this.shortTitle(50);
112 // Sanitize parameters
113 if ( !this.canSwitchToMode( this.mode ) ) {
114 this.mode = this.constMode1up;
117 $("#GnuBook").empty();
118 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
119 $("#GnuBook").append("<div id='GBcontainer'></div>");
120 $("#GBcontainer").append("<div id='GBpageview'></div>");
122 $("#GBcontainer").bind('scroll', this, function(e) {
126 this.setupKeyListeners();
127 this.startLocationPolling();
129 $(window).bind('resize', this, function(e) {
130 //console.log('resize!');
131 if (1 == e.data.mode) {
132 //console.log('centering 1page view');
133 e.data.centerPageView();
134 $('#GBpageview').empty()
135 e.data.displayedIndices = [];
136 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
139 //console.log('drawing 2 page view');
140 e.data.prepareTwoPageView();
144 $('.GBpagediv1up').bind('mousedown', this, function(e) {
145 //console.log('mousedown!');
148 if (1 == this.mode) {
149 this.resizePageView();
150 this.firstIndex = startIndex;
151 this.jumpToIndex(startIndex);
153 //this.resizePageView();
155 this.displayedIndices=[0];
156 this.firstIndex = startIndex;
157 this.displayedIndices = [this.firstIndex];
158 //console.log('titleLeaf: %d', this.titleLeaf);
159 //console.log('displayedIndices: %s', this.displayedIndices);
160 this.prepareTwoPageView();
161 //if (this.auto) this.nextPage();
164 // Enact other parts of initial params
165 this.updateFromParams(params);
168 GnuBook.prototype.setupKeyListeners = function() {
181 // We use document here instead of window to avoid a bug in jQuery on IE7
182 $(document).keydown(function(e) {
184 // Keyboard navigation
188 // In 1up mode page scrolling is handled by browser
189 if (2 == self.mode) {
195 if (2 == self.mode) {
206 if (self.keyboardNavigationIsDisabled(e)) {
209 if (2 == self.mode) {
214 if (self.keyboardNavigationIsDisabled(e)) {
217 if (2 == self.mode) {
226 //______________________________________________________________________________
227 GnuBook.prototype.drawLeafs = function() {
228 if (1 == this.mode) {
229 this.drawLeafsOnePage();
231 this.drawLeafsTwoPage();
235 // setDragHandler1up()
236 //______________________________________________________________________________
237 GnuBook.prototype.setDragHandler1up = function(div) {
238 div.dragging = false;
240 $(div).bind('mousedown', function(e) {
241 //console.log('mousedown at ' + e.pageY);
243 this.dragging = true;
244 this.prevMouseX = e.pageX;
245 this.prevMouseY = e.pageY;
247 var startX = e.pageX;
248 var startY = e.pageY;
249 var startTop = $('#GBcontainer').attr('scrollTop');
250 var startLeft = $('#GBcontainer').attr('scrollLeft');
255 $(div).bind('mousemove', function(ee) {
256 //console.log('mousemove ' + startY);
258 var offsetX = ee.pageX - this.prevMouseX;
259 var offsetY = ee.pageY - this.prevMouseY;
262 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
263 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
266 this.prevMouseX = ee.pageX;
267 this.prevMouseY = ee.pageY;
272 $(div).bind('mouseup', function(ee) {
273 //console.log('mouseup');
275 this.dragging = false;
279 $(div).bind('mouseleave', function(e) {
280 //console.log('mouseleave');
282 //$(this).unbind('mousemove mouseup');
283 this.dragging = false;
288 // drawLeafsOnePage()
289 //______________________________________________________________________________
290 GnuBook.prototype.drawLeafsOnePage = function() {
291 //alert('drawing leafs!');
295 var scrollTop = $('#GBcontainer').attr('scrollTop');
296 var scrollBottom = scrollTop + $('#GBcontainer').height();
297 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
299 var indicesToDisplay = [];
304 for (i=0; i<this.numLeafs; i++) {
305 var height = parseInt(this.getPageHeight(i)/this.reduce);
307 leafBottom += height;
308 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
309 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
310 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
311 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
312 if (topInView | bottomInView | middleInView) {
313 //console.log('displayed: ' + this.displayedIndices);
314 //console.log('to display: ' + i);
315 indicesToDisplay.push(i);
317 leafTop += height +10;
321 var firstIndexToDraw = indicesToDisplay[0];
322 this.firstIndex = firstIndexToDraw;
324 // Update hash, but only if we're currently displaying a leaf
325 // Hack that fixes #365790
326 if (this.displayedIndices.length > 0) {
327 this.updateLocationHash();
330 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
332 indicesToDisplay.unshift(firstIndexToDraw);
335 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
336 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
337 indicesToDisplay.push(lastIndexToDraw+1);
342 for (i=0; i<firstIndexToDraw; i++) {
343 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
346 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
347 var viewWidth = $('#GBcontainer').attr('scrollWidth');
350 for (i=0; i<indicesToDisplay.length; i++) {
351 var index = indicesToDisplay[i];
352 var height = parseInt(this.getPageHeight(index)/this.reduce);
354 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
355 var width = parseInt(this.getPageWidth(index)/this.reduce);
356 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
357 var div = document.createElement("div");
358 div.className = 'GBpagediv1up';
359 div.id = 'pagediv'+index;
360 div.style.position = "absolute";
361 $(div).css('top', leafTop + 'px');
362 var left = (viewWidth-width)>>1;
363 if (left<0) left = 0;
364 $(div).css('left', left+'px');
365 $(div).css('width', width+'px');
366 $(div).css('height', height+'px');
367 //$(div).text('loading...');
369 this.setDragHandler1up(div);
371 $('#GBpageview').append(div);
373 var img = document.createElement("img");
374 img.src = this.getPageURI(index);
375 $(img).css('width', width+'px');
376 $(img).css('height', height+'px');
380 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
383 leafTop += height +10;
387 for (i=0; i<this.displayedIndices.length; i++) {
388 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
389 var index = this.displayedIndices[i];
390 //console.log('Removing leaf ' + index);
391 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
392 $('#pagediv'+index).remove();
394 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
398 this.displayedIndices = indicesToDisplay.slice();
399 this.updateSearchHilites();
401 if (null != this.getPageNum(firstIndexToDraw)) {
402 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
404 $("#GBpagenum").val('');
407 //var centerY = this.centerY1up();
408 //var centerX = this.centerX1up();
409 //console.log('draw center ' + centerY + ',' + centerX);
410 //console.log('scroll left ' + $('#GBcontainer').attr('scrollLeft'));
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 index = this.twoPage.currentIndexL;
425 var height = this.getPageHeight(index);
426 var width = this.getPageWidth(index);
427 var handSide= this.getPageSide(index);
429 var leafEdgeWidthL = this.leafEdgeWidth(index);
430 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
431 var bookCoverDivWidth = this.twoPage.width*2+20 + this.twoPage.edgeWidth;
432 var bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
433 //console.log(leafEdgeWidthL);
435 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
436 var left = middle - this.twoPage.width;
437 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
439 var scaledW = parseInt(this.twoPage.height*width/height);
440 left = 10+leafEdgeWidthL;
441 //var right = left+scaledW;
442 var right = $(this.twoPageDiv).width()-11-$(this.leafEdgeL).width()-scaledW;
444 var gutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
446 this.prefetchImg(index);
447 $(this.prefetchedImgs[index]).css({
448 position: 'absolute',
449 /*right: gutter+'px',*/
450 left: gutter-scaledW+'px',
453 backgroundColor: 'rgb(234, 226, 205)',
454 height: this.twoPage.height +'px',
455 width: scaledW + 'px',
456 borderRight: '1px solid black',
458 }).appendTo('#GBtwopageview');
459 //$('#GBcontainer').append(this.prefetchedImgs[index]);
462 var index = this.twoPage.currentIndexR;
463 var height = this.getPageHeight(index);
464 var width = this.getPageWidth(index);
465 // var left = ($('#GBcontainer').width() >> 1);
468 var scaledW = this.twoPage.height*width/height;
469 this.prefetchImg(index);
470 $(this.prefetchedImgs[index]).css({
471 position: 'absolute',
475 backgroundColor: 'rgb(234, 226, 205)',
476 height: this.twoPage.height + 'px',
477 width: scaledW + 'px',
478 borderLeft: '1px solid black',
480 }).appendTo('#GBtwopageview');
481 //$('#GBcontainer').append(this.prefetchedImgs[index]);
484 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
485 this.setClickHandlers();
487 this.updatePageNumBox2UP();
490 // updatePageNumBox2UP
491 //______________________________________________________________________________
492 GnuBook.prototype.updatePageNumBox2UP = function() {
493 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
494 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
496 $("#GBpagenum").val('');
498 this.updateLocationHash();
502 //______________________________________________________________________________
503 GnuBook.prototype.loadLeafs = function() {
507 if (null == this.timer) {
508 this.timer=setTimeout(function(){self.drawLeafs()},250);
510 clearTimeout(this.timer);
511 this.timer=setTimeout(function(){self.drawLeafs()},250);
517 // Pass 1 to zoom in, anything else to zoom out
518 //______________________________________________________________________________
519 GnuBook.prototype.zoom = function(direction) {
521 case this.constMode1up:
522 return this.zoom1up(direction);
523 case this.constMode2up:
524 return this.zoom2up(direction);
529 //______________________________________________________________________________
530 GnuBook.prototype.zoom1up = function(dir) {
531 if (2 == this.mode) { //can only zoom in 1-page mode
536 // $$$ with flexible zoom we could "snap" to /2 page reductions
537 // for better scaling
539 if (this.reduce <= 0.5) return;
540 this.reduce*=0.5; //zoom in
542 if (this.reduce >= 8) return;
543 this.reduce*=2; //zoom out
546 this.resizePageView();
548 $('#GBpageview').empty()
549 this.displayedIndices = [];
552 $('#GBzoom').text(100/this.reduce);
556 //______________________________________________________________________________
557 GnuBook.prototype.resizePageView = function() {
560 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
561 var viewWidth = $('#GBcontainer').attr('clientWidth');
563 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
564 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
565 var oldPageViewHeight = $('#GBpageview').height();
566 var oldPageViewWidth = $('#GBpageview').width();
568 var oldCenterY = this.centerY1up();
569 var oldCenterX = this.centerX1up();
571 if (0 != oldPageViewHeight) {
572 var scrollRatio = oldCenterY / oldPageViewHeight;
577 for (i=0; i<this.numLeafs; i++) {
578 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
579 var width = parseInt(this.getPageWidth(i)/this.reduce);
580 if (width>viewWidth) viewWidth=width;
582 $('#GBpageview').height(viewHeight);
583 $('#GBpageview').width(viewWidth);
585 var newCenterY = scrollRatio*viewHeight;
586 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
587 $('#GBcontainer').attr('scrollTop', newTop);
589 // We use clientWidth here to avoid miscalculating due to scroll bar
590 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
591 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
592 newLeft = Math.max(newLeft, 0);
593 $('#GBcontainer').attr('scrollLeft', newLeft);
594 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
596 //this.centerPageView();
602 //______________________________________________________________________________
603 // Returns the current offset of the viewport center in scaled document coordinates.
604 GnuBook.prototype.centerX1up = function() {
606 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
607 centerX = $('#GBpageview').width();
609 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
611 centerX = Math.floor(centerX);
616 //______________________________________________________________________________
617 // Returns the current offset of the viewport center in scaled document coordinates.
618 GnuBook.prototype.centerY1up = function() {
619 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
620 return Math.floor(centerY);
624 //______________________________________________________________________________
625 GnuBook.prototype.centerPageView = function() {
627 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
628 var clientWidth = $('#GBcontainer').attr('clientWidth');
629 //console.log('sW='+scrollWidth+' cW='+clientWidth);
630 if (scrollWidth > clientWidth) {
631 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
636 // zoom2up(direction)
637 //______________________________________________________________________________
638 GnuBook.prototype.zoom2up = function(direction) {
639 // $$$ this is where we can e.g. snap to %2 sizes
641 if (1 == direction) {
642 if (this.reduce <= 0.5) return;
643 return this.zoom2upPercentage( 1 / (this.reduce*=0.5) ); //zoom in
645 if (this.reduce >= 8) return;
646 return this.zoom2upPercentage( 1 / (this.reduce*2) ); // zoom out
651 // zoom2upPercentage(percentage)
652 //______________________________________________________________________________
653 GnuBook.prototype.zoom2upPercentage = function(percentage) {
654 this.reduce = 1/percentage;
655 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 // We want to minimize the unused space in two-up mode (maximize the amount of page
810 // shown). We give width to the leaf edges and these widths change (though the sum
811 // of the two remains constant) as we flip through the book. With the book
812 // cover centered and fixed in the GBcontainer div the page images will meet
813 // at the "gutter" which is generally offset from the center.
814 var middle = ($('#GBcontainer').attr('clientWidth') >> 1); // Middle of the GBcontainer div
815 //var gutter = middle+parseInt((2*this.twoPage.currentIndexL - this.numLeafs)*this.twoPage.edgeWidth/this.numLeafs/2);
817 var gutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
819 var scaledWL = this.getPageWidth2UP(this.twoPage.currentIndexL);
820 var scaledWR = this.getPageWidth2UP(this.twoPage.currentIndexR);
821 var leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
822 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
824 //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
825 //var bookCoverDivWidth = this.twoPage.width*2+20 + this.twoPage.edgeWidth;
827 // The width of the book cover div. The combined width of both pages, twice the width
828 // of the book cover internal padding (2*10) and the page edges
829 var bookCoverDivWidth = scaledWL + scaledWR + 20 + this.twoPage.edgeWidth;
831 // The height of the book cover div
832 var bookCoverDivHeight = this.twoPage.height+20;
834 //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
835 var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-10;
836 var bookCoverDivTop = ($('#GBcontainer').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');
854 //$('#GBcontainer').append('<div id="book_div_1" style="border: 1px solid rgb(68, 25, 17); width: ' + bookCoverDivWidth + 'px; height: '+bookCoverDivHeight+'px; visibility: visible; position: absolute; background-color: rgb(136, 51, 34); left: ' + bookCoverDivLeft + 'px; top: '+bookCoverDivTop+'px; -moz-border-radius-topleft: 7px; -moz-border-radius-topright: 7px; -moz-border-radius-bottomright: 7px; -moz-border-radius-bottomleft: 7px;"/>');
857 var height = this.getPageHeight(this.twoPage.currentIndexR);
858 var width = this.getPageWidth(this.twoPage.currentIndexR);
859 var scaledW = this.twoPage.height*width/height;
861 this.leafEdgeR = document.createElement('div');
862 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
863 $(this.leafEdgeR).css({
864 borderStyle: 'solid solid solid none',
865 borderColor: 'rgb(51, 51, 34)',
866 borderWidth: '1px 1px 1px 0px',
867 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
868 width: leafEdgeWidthR + 'px',
869 height: this.twoPage.height-1 + 'px',
871 left: gutter+scaledW+'px',
872 top: bookCoverDivTop+10+'px',
874 }).appendTo('#GBtwopageview');
876 this.leafEdgeL = document.createElement('div');
877 this.leafEdgeL.className = 'leafEdgeL';
878 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
879 borderStyle: 'solid none solid solid',
880 borderColor: 'rgb(51, 51, 34)',
881 borderWidth: '1px 0px 1px 1px',
882 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
883 width: leafEdgeWidthL + 'px',
884 height: this.twoPage.height-1 + 'px',
885 left: bookCoverDivLeft+10+'px',
886 top: bookCoverDivTop+10+'px',
888 }).appendTo('#GBtwopageview');
892 bookCoverDivWidth = 30;
893 bookCoverDivHeight = this.twoPage.height+20;
894 bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
895 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
897 div = document.createElement('div');
898 $(div).attr('id', 'GBbookspine').css({
899 border: '1px solid rgb(68, 25, 17)',
900 width: bookCoverDivWidth+'px',
901 height: bookCoverDivHeight+'px',
902 position: 'absolute',
903 backgroundColor: 'rgb(68, 25, 17)',
904 left: bookCoverDivLeft+'px',
905 top: bookCoverDivTop+'px'
906 }).appendTo('#GBtwopageview');
907 //$('#GBcontainer').append('<div id="book_div_2" style="border: 1px solid rgb(68, 25, 17); width: '+bookCoverDivWidth+'px; height: '+bookCoverDivHeight+'px; visibility: visible; position: absolute; background-color: rgb(68, 25, 17); left: '+bookCoverDivLeft+'px; top: '+bookCoverDivTop+'px;"/>');
909 bookCoverDivWidth = this.twoPage.width*2;
910 bookCoverDivHeight = this.twoPage.height;
911 bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
912 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
915 this.prepareTwoPagePopUp();
917 this.displayedIndices = [];
919 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
920 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
922 this.drawLeafsTwoPage();
923 this.updateSearchHilites2UP();
926 $('#GBzoom').text((100*this.twoPage.height/this.getPageHeight(this.twoPage.currentIndexL)).toString().substr(0,4));
929 // prepareTwoPagePopUp()
931 // This function prepares the "View Page n" popup that shows while the mouse is
932 // over the left/right "stack of sheets" edges. It also binds the mouse
933 // events for these divs.
934 //______________________________________________________________________________
935 GnuBook.prototype.prepareTwoPagePopUp = function() {
937 this.twoPagePopUp = document.createElement('div');
938 $(this.twoPagePopUp).css({
939 border: '1px solid black',
941 position: 'absolute',
942 fontFamily: 'sans-serif',
945 backgroundColor: 'rgb(255, 255, 238)',
947 }).appendTo('#GBcontainer');
948 $(this.twoPagePopUp).hide();
950 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
951 $(e.data.twoPagePopUp).show();
954 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
955 $(e.data.twoPagePopUp).hide();
958 $(this.leafEdgeL).bind('click', this, function(e) {
960 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
961 e.data.jumpToIndex(jumpIndex);
964 $(this.leafEdgeR).bind('click', this, function(e) {
966 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
967 e.data.jumpToIndex(jumpIndex);
970 $(this.leafEdgeR).bind('mousemove', this, function(e) {
972 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
973 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
975 // $$$ TODO: Make sure popup is positioned so that it is in view
976 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
977 $(e.data.twoPagePopUp).css({
978 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
979 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
983 $(this.leafEdgeL).bind('mousemove', this, function(e) {
985 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
986 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
988 // $$$ TODO: Make sure popup is positioned so that it is in view
989 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
990 $(e.data.twoPagePopUp).css({
991 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
992 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
997 // calculateSpreadSize()
998 //______________________________________________________________________________
999 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1000 // this.twoPage.currentIndexR
1001 // This function sets this.twoPage.height, twoPage.width, and twoPage.ratio
1003 GnuBook.prototype.calculateSpreadSize = function() {
1004 console.log('calculateSpreadSize ' + this.twoPage.currentIndexL); // XXX
1006 var firstIndex = this.twoPage.currentIndexL;
1007 var secondIndex = this.twoPage.currentIndexR;
1008 //console.log('first page is ' + firstIndex);
1010 var canon5Dratio = 1.5;
1012 var firstIndexRatio = this.getPageHeight(firstIndex) / this.getPageWidth(firstIndex);
1013 var secondIndexRatio = this.getPageHeight(secondIndex) / this.getPageWidth(secondIndex);
1014 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1017 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1018 ratio = firstIndexRatio;
1019 //console.log('using firstIndexRatio ' + ratio);
1021 ratio = secondIndexRatio;
1022 //console.log('using secondIndexRatio ' + ratio);
1025 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1026 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1027 totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1029 var idealWidth = ($('#GBcontainer').attr('clientWidth') - 30 - totalLeafEdgeWidth)>>1;
1030 var idealHeight = $('#GBcontainer').height() - 30; // $$$ why - 30? book edge width?
1031 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
1033 if (idealHeight/ratio <= idealWidth) {
1035 idealWidth = parseInt(idealHeight/ratio);
1038 idealHeight = parseInt(idealWidth*ratio);
1041 this.twoPage.height = idealHeight;
1042 this.twoPage.width = idealWidth;
1043 this.twoPage.ratio = ratio;
1044 this.twoPage.edgeWidth = totalLeafEdgeWidth; // The combined width of both edges
1048 GnuBook.prototype.calculateSpreadSizeFromReduce = function() {
1051 this.twoPage.totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1 * this.reduce);
1053 // $$$ We clip to the smallest leaf since we can't currently display different sized pages
1054 // Affects https://bugs.edge.launchpad.net/gnubook/+bug/320712
1055 var smallestHeight = Math.min( this.getPageHeight(this.twoPage.currentIndexL), this.getPageHeight(this.twoPage.currentIndexR) );
1056 this.twoPage.height = smallestHeight * this.reduce - this.bookCoverPadding;
1062 //______________________________________________________________________________
1063 // Returns the currently active index.
1064 GnuBook.prototype.currentIndex = function() {
1065 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1066 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1067 return this.firstIndex;
1069 throw 'currentIndex called for unimplemented mode ' + this.mode;
1074 //______________________________________________________________________________
1075 // Flip the right page over onto the left
1076 GnuBook.prototype.right = function() {
1077 if ('rl' != this.pageProgression) {
1087 //______________________________________________________________________________
1088 // Flip to the rightmost page
1089 GnuBook.prototype.rightmost = function() {
1090 if ('rl' != this.pageProgression) {
1098 //______________________________________________________________________________
1099 // Flip the left page over onto the right.
1100 GnuBook.prototype.left = function() {
1101 if ('rl' != this.pageProgression) {
1111 //______________________________________________________________________________
1112 // Flip to the leftmost page
1113 GnuBook.prototype.leftmost = function() {
1114 if ('rl' != this.pageProgression) {
1122 //______________________________________________________________________________
1123 GnuBook.prototype.next = function() {
1124 if (2 == this.mode) {
1126 this.flipFwdToIndex(null);
1128 if (this.firstIndex < this.lastDisplayableIndex()) {
1129 this.jumpToIndex(this.firstIndex+1);
1135 //______________________________________________________________________________
1136 GnuBook.prototype.prev = function() {
1137 if (2 == this.mode) {
1139 this.flipBackToIndex(null);
1141 if (this.firstIndex >= 1) {
1142 this.jumpToIndex(this.firstIndex-1);
1147 GnuBook.prototype.first = function() {
1148 if (2 == this.mode) {
1149 this.jumpToIndex(2);
1152 this.jumpToIndex(0);
1156 GnuBook.prototype.last = function() {
1157 if (2 == this.mode) {
1158 this.jumpToIndex(this.lastDisplayableIndex());
1161 this.jumpToIndex(this.lastDisplayableIndex());
1165 // flipBackToIndex()
1166 //______________________________________________________________________________
1167 // to flip back one spread, pass index=null
1168 GnuBook.prototype.flipBackToIndex = function(index) {
1169 if (1 == this.mode) return;
1171 var leftIndex = this.twoPage.currentIndexL;
1173 // $$$ Need to change this to be able to see first spread.
1174 // See https://bugs.launchpad.net/gnubook/+bug/296788
1175 if (leftIndex <= 2) return;
1176 if (this.animating) return;
1178 if (null != this.leafEdgeTmp) {
1179 alert('error: leafEdgeTmp should be null!');
1183 if (null == index) {
1184 index = leftIndex-2;
1186 //if (index<0) return;
1188 var previousIndices = this.getSpreadIndices(index);
1190 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1194 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1196 this.animating = true;
1198 if ('rl' != this.pageProgression) {
1199 // Assume LTR and we are going backward
1200 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1201 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1204 // RTL and going backward
1205 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1206 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1210 // flipLeftToRight()
1211 //______________________________________________________________________________
1212 // Flips the page on the left towards the page on the right
1213 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1215 var leftLeaf = this.twoPage.currentIndexL;
1217 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1218 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1219 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1221 var currWidthL = this.getPageWidth2UP(leftLeaf);
1222 var newWidthL = this.getPageWidth2UP(newIndexL);
1223 var newWidthR = this.getPageWidth2UP(newIndexR);
1225 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1227 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1228 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1230 //animation strategy:
1231 // 0. remove search highlight, if any.
1232 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1233 // of the left leaf and where the user clicked in the leaf edge.
1234 // Note that if this function was triggered by left() and not a
1235 // mouse click, the width of leafEdgeTmp is very small (zero px).
1236 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1237 // leftLeaf to width=0.
1238 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1239 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1240 // its new full width.
1241 // 4. After step 3 is finished, do the following:
1242 // - remove leafEdgeTmp from the dom.
1243 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1244 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1245 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1246 // and width=newLeafEdgeWidthL.
1247 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1248 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1249 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1250 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1251 // - prefetch new adjacent leafs.
1252 // - set up click handlers for both new left and right leafs.
1253 // - redraw the search highlight.
1254 // - update the pagenum box and the url.
1257 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1259 this.leafEdgeTmp = document.createElement('div');
1260 $(this.leafEdgeTmp).css({
1261 borderStyle: 'solid none solid solid',
1262 borderColor: 'rgb(51, 51, 34)',
1263 borderWidth: '1px 0px 1px 1px',
1264 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1265 width: leafEdgeTmpW + 'px',
1266 height: this.twoPage.height-1 + 'px',
1267 left: leftEdgeTmpLeft + 'px',
1269 position: 'absolute',
1271 }).appendTo('#GBtwopageview');
1273 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1274 $(this.leafEdgeL).css({
1275 width: newLeafEdgeWidthL+'px',
1276 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1279 // Left gets the offset of the current left leaf from the document
1280 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1281 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1282 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1283 // We change the left leaf to right positioning
1284 $(this.prefetchedImgs[leftLeaf]).css({
1289 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1291 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1293 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1294 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1298 this.removeSearchHilites();
1300 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1301 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1303 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1304 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1306 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1307 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1308 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1310 $(self.leafEdgeR).css({
1311 // Moves the right leaf edge
1312 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1313 left: gutter+newWidthR+'px'
1316 $(self.leafEdgeL).css({
1317 // Moves and resizes the left leaf edge
1318 width: newLeafEdgeWidthL+'px',
1319 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1323 $(self.twoPageDiv).css({
1324 // Resizes the brown border div
1325 width: newWidthL+newWidthR+self.twoPage.edgeWidth+20+'px',
1326 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1329 $(self.leafEdgeTmp).remove();
1330 self.leafEdgeTmp = null;
1332 self.twoPage.currentIndexL = newIndexL;
1333 self.twoPage.currentIndexR = newIndexR;
1334 self.firstIndex = self.twoPage.currentIndexL;
1335 self.displayedIndices = [newIndexL, newIndexR];
1336 self.setClickHandlers();
1337 self.pruneUnusedImgs();
1339 self.animating = false;
1341 self.updateSearchHilites2UP();
1342 self.updatePageNumBox2UP();
1343 //$('#GBzoom').text((self.twoPage.height/self.getPageHeight(newIndexL)).toString().substr(0,4));
1345 if (self.animationFinishedCallback) {
1346 self.animationFinishedCallback();
1347 self.animationFinishedCallback = null;
1355 //______________________________________________________________________________
1356 // Whether we flip left or right is dependent on the page progression
1357 // to flip forward one spread, pass index=null
1358 GnuBook.prototype.flipFwdToIndex = function(index) {
1360 if (this.animating) return;
1362 if (null != this.leafEdgeTmp) {
1363 alert('error: leafEdgeTmp should be null!');
1367 if (null == index) {
1368 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1370 if (index > this.lastDisplayableIndex()) return;
1372 this.animating = true;
1374 var nextIndices = this.getSpreadIndices(index);
1376 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1378 if ('rl' != this.pageProgression) {
1379 // We did not specify RTL
1380 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1381 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1384 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1385 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1389 // flipRightToLeft(nextL, nextR, gutter)
1390 // $$$ better not to have to pass gutter in
1391 //______________________________________________________________________________
1392 // Flip from left to right and show the nextL and nextR indices on those sides
1393 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1394 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1395 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1396 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1397 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1399 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1401 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1403 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1405 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1406 var currGutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1409 console.log('R->L middle(' + middle +') currGutter(' + currGutter + ') gutter(' + gutter + ')');
1411 this.leafEdgeTmp = document.createElement('div');
1412 $(this.leafEdgeTmp).css({
1413 borderStyle: 'solid none solid solid',
1414 borderColor: 'rgb(51, 51, 34)',
1415 borderWidth: '1px 0px 1px 1px',
1416 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1417 width: leafEdgeTmpW + 'px',
1418 height: this.twoPage.height-1 + 'px',
1419 left: currGutter+scaledW+'px',
1421 position: 'absolute',
1423 }).appendTo('#GBtwopageview');
1425 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1426 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1428 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1429 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1430 var newWidthL = this.getPageWidth2UP(newIndexL);
1431 var newWidthR = this.getPageWidth2UP(newIndexR);
1433 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1435 var self = this; // closure-tastic!
1437 var speed = this.flipSpeed;
1439 this.removeSearchHilites();
1441 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1442 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1443 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1444 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1445 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1447 $(self.leafEdgeL).css({
1448 width: newLeafEdgeWidthL+'px',
1449 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1452 $(self.twoPageDiv).css({
1453 width: newWidthL+newWidthR+self.twoPage.edgeWidth+20+'px',
1454 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1457 $(self.leafEdgeTmp).remove();
1458 self.leafEdgeTmp = null;
1460 self.twoPage.currentIndexL = newIndexL;
1461 self.twoPage.currentIndexR = newIndexR;
1462 self.firstIndex = self.twoPage.currentIndexL;
1463 self.displayedIndices = [newIndexL, newIndexR];
1464 self.setClickHandlers();
1465 self.pruneUnusedImgs();
1467 self.animating = false;
1470 self.updateSearchHilites2UP();
1471 self.updatePageNumBox2UP();
1472 //$('#GBzoom').text((self.twoPage.height/self.getPageHeight(newIndexL)).toString().substr(0,4));
1474 if (self.animationFinishedCallback) {
1475 self.animationFinishedCallback();
1476 self.animationFinishedCallback = null;
1483 //______________________________________________________________________________
1484 GnuBook.prototype.setClickHandlers = function() {
1486 $(this.prefetchedImgs[this.twoPage.currentIndexL]).click(function() {
1491 $(this.prefetchedImgs[this.twoPage.currentIndexR]).click(function() {
1499 //______________________________________________________________________________
1500 GnuBook.prototype.prefetchImg = function(index) {
1501 if (undefined == this.prefetchedImgs[index]) {
1502 //console.log('prefetching ' + index);
1503 var img = document.createElement("img");
1504 img.src = this.getPageURI(index);
1505 this.prefetchedImgs[index] = img;
1510 // prepareFlipLeftToRight()
1512 //______________________________________________________________________________
1514 // Prepare to flip the left page towards the right. This corresponds to moving
1515 // backward when the page progression is left to right.
1516 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1518 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1520 this.prefetchImg(prevL);
1521 this.prefetchImg(prevR);
1523 var height = this.getPageHeight(prevL);
1524 var width = this.getPageWidth(prevL);
1525 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1526 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1527 var scaledW = this.twoPage.height*width/height;
1529 // The gutter is the dividing line between the left and right pages.
1530 // It is offset from the middle to create the illusion of thickness to the pages
1531 var gutter = middle + this.gutterOffsetForIndex(prevL);
1534 console.log(' gutter for ' + prevL + ' is ' + gutter);
1535 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1536 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1538 $(this.prefetchedImgs[prevL]).css({
1539 position: 'absolute',
1540 /*right: middle+'px',*/
1541 left: gutter-scaledW+'px',
1544 backgroundColor: 'rgb(234, 226, 205)',
1545 height: this.twoPage.height,
1546 width: scaledW+'px',
1547 borderRight: '1px solid black',
1551 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1553 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1555 $(this.prefetchedImgs[prevR]).css({
1556 position: 'absolute',
1560 backgroundColor: 'rgb(234, 226, 205)',
1561 height: this.twoPage.height,
1563 borderLeft: '1px solid black',
1567 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1574 // XXXmang we're adding an extra pixel in the middle
1575 // prepareFlipRightToLeft()
1576 //______________________________________________________________________________
1577 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1579 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1581 this.prefetchImg(nextL);
1582 this.prefetchImg(nextR);
1584 var height = this.getPageHeight(nextR);
1585 var width = this.getPageWidth(nextR);
1586 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1587 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1588 var scaledW = this.twoPage.height*width/height;
1590 var gutter = middle + this.gutterOffsetForIndex(nextL);
1592 console.log('right to left to %d gutter is %d', nextL, gutter); // XXX
1594 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1595 $(this.prefetchedImgs[nextR]).css({
1596 position: 'absolute',
1599 backgroundColor: 'rgb(234, 226, 205)',
1600 height: this.twoPage.height,
1601 width: scaledW+'px',
1602 borderLeft: '1px solid black',
1606 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1608 height = this.getPageHeight(nextL);
1609 width = this.getPageWidth(nextL);
1610 scaledW = this.twoPage.height*width/height;
1612 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1613 $(this.prefetchedImgs[nextL]).css({
1614 position: 'absolute',
1615 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1617 backgroundColor: 'rgb(234, 226, 205)',
1618 height: this.twoPage.height,
1620 borderRight: '1px solid black',
1624 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1630 // getNextLeafs() -- NOT RTL AWARE
1631 //______________________________________________________________________________
1632 // GnuBook.prototype.getNextLeafs = function(o) {
1633 // //TODO: we might have two left or two right leafs in a row (damaged book)
1634 // //For now, assume that leafs are contiguous.
1636 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1637 // o.L = this.twoPage.currentIndexL+2;
1638 // o.R = this.twoPage.currentIndexL+3;
1641 // getprevLeafs() -- NOT RTL AWARE
1642 //______________________________________________________________________________
1643 // GnuBook.prototype.getPrevLeafs = function(o) {
1644 // //TODO: we might have two left or two right leafs in a row (damaged book)
1645 // //For now, assume that leafs are contiguous.
1647 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1648 // o.L = this.twoPage.currentIndexL-2;
1649 // o.R = this.twoPage.currentIndexL-1;
1652 // pruneUnusedImgs()
1653 //______________________________________________________________________________
1654 GnuBook.prototype.pruneUnusedImgs = function() {
1655 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1656 for (var key in this.prefetchedImgs) {
1657 //console.log('key is ' + key);
1658 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1659 //console.log('removing key '+ key);
1660 $(this.prefetchedImgs[key]).remove();
1662 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1663 //console.log('deleting key '+ key);
1664 delete this.prefetchedImgs[key];
1670 //______________________________________________________________________________
1671 GnuBook.prototype.prefetch = function() {
1673 var lim = this.twoPage.currentIndexL-4;
1675 lim = Math.max(lim, 0);
1676 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1677 this.prefetchImg(i);
1680 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1681 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1682 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1683 this.prefetchImg(i);
1688 // getPageWidth2UP()
1689 //______________________________________________________________________________
1690 GnuBook.prototype.getPageWidth2UP = function(index) {
1691 var height = this.getPageHeight(index);
1692 var width = this.getPageWidth(index);
1693 return Math.floor(this.twoPage.height*width/height);
1697 //______________________________________________________________________________
1698 GnuBook.prototype.search = function(term) {
1699 $('#GnuBookSearchScript').remove();
1700 var script = document.createElement("script");
1701 script.setAttribute('id', 'GnuBookSearchScript');
1702 script.setAttribute("type", "text/javascript");
1703 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1704 document.getElementsByTagName('head')[0].appendChild(script);
1705 $('#GnuBookSearchResults').html('Searching...');
1708 // GBSearchCallback()
1709 //______________________________________________________________________________
1710 GnuBook.prototype.GBSearchCallback = function(txt) {
1712 if (jQuery.browser.msie) {
1713 var dom=new ActiveXObject("Microsoft.XMLDOM");
1717 var parser = new DOMParser();
1718 var dom = parser.parseFromString(txt, "text/xml");
1721 $('#GnuBookSearchResults').empty();
1722 $('#GnuBookSearchResults').append('<ul>');
1724 for (var key in this.searchResults) {
1725 if (null != this.searchResults[key].div) {
1726 $(this.searchResults[key].div).remove();
1728 delete this.searchResults[key];
1731 var pages = dom.getElementsByTagName('PAGE');
1733 if (0 == pages.length) {
1734 // $$$ it would be nice to echo the (sanitized) search result here
1735 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1737 for (var i = 0; i < pages.length; i++){
1738 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1741 var re = new RegExp (/_(\d{4})/);
1742 var reMatch = re.exec(pages[i].getAttribute('file'));
1743 var index = parseInt(reMatch[1], 10);
1744 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1746 var children = pages[i].childNodes;
1748 for (var j=0; j<children.length; j++) {
1749 //console.log(j + ' - ' + children[j].nodeName);
1750 //console.log(children[j].firstChild.nodeValue);
1751 if ('CONTEXT' == children[j].nodeName) {
1752 context += children[j].firstChild.nodeValue;
1753 } else if ('WORD' == children[j].nodeName) {
1754 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1756 var index = this.leafNumToIndex(index);
1757 if (null != index) {
1758 //coordinates are [left, bottom, right, top, [baseline]]
1759 //we'll skip baseline for now...
1760 var coords = children[j].getAttribute('coords').split(',',4);
1761 if (4 == coords.length) {
1762 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1767 var pageName = this.getPageName(index);
1768 //TODO: remove hardcoded instance name
1769 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1772 $('#GnuBookSearchResults').append('</ul>');
1774 this.updateSearchHilites();
1777 // updateSearchHilites()
1778 //______________________________________________________________________________
1779 GnuBook.prototype.updateSearchHilites = function() {
1780 if (2 == this.mode) {
1781 this.updateSearchHilites2UP();
1783 this.updateSearchHilites1UP();
1787 // showSearchHilites1UP()
1788 //______________________________________________________________________________
1789 GnuBook.prototype.updateSearchHilites1UP = function() {
1791 for (var key in this.searchResults) {
1793 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1794 var result = this.searchResults[key];
1795 if(null == result.div) {
1796 result.div = document.createElement('div');
1797 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1798 //console.log('appending ' + key);
1801 width: (result.r-result.l)/this.reduce + 'px',
1802 height: (result.b-result.t)/this.reduce + 'px',
1803 left: (result.l)/this.reduce + 'px',
1804 top: (result.t)/this.reduce +'px'
1808 //console.log(key + ' not displayed');
1809 this.searchResults[key].div=null;
1814 // showSearchHilites2UP()
1815 //______________________________________________________________________________
1816 GnuBook.prototype.updateSearchHilites2UP = function() {
1818 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1820 for (var key in this.searchResults) {
1821 key = parseInt(key, 10);
1822 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
1823 var result = this.searchResults[key];
1824 if(null == result.div) {
1825 result.div = document.createElement('div');
1826 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
1827 //console.log('appending ' + key);
1830 var height = this.getPageHeight(key);
1831 var width = this.getPageWidth(key)
1832 var reduce = this.twoPage.height/height;
1833 var scaledW = parseInt(width*reduce);
1835 var gutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1837 if ('L' == this.getPageSide(key)) {
1838 var pageL = gutter-scaledW;
1842 var pageT = ($('#GBtwopagview').height() - this.twoPage.height) >> 1;
1845 width: (result.r-result.l)*reduce + 'px',
1846 height: (result.b-result.t)*reduce + 'px',
1847 left: pageL+(result.l)*reduce + 'px',
1848 top: pageT+(result.t)*reduce +'px'
1852 //console.log(key + ' not displayed');
1853 if (null != this.searchResults[key].div) {
1854 //console.log('removing ' + key);
1855 $(this.searchResults[key].div).remove();
1857 this.searchResults[key].div=null;
1862 // removeSearchHilites()
1863 //______________________________________________________________________________
1864 GnuBook.prototype.removeSearchHilites = function() {
1865 for (var key in this.searchResults) {
1866 if (null != this.searchResults[key].div) {
1867 $(this.searchResults[key].div).remove();
1868 this.searchResults[key].div=null;
1874 //______________________________________________________________________________
1875 GnuBook.prototype.showEmbedCode = function() {
1876 if (null != this.embedPopup) { // check if already showing
1880 this.embedPopup = document.createElement("div");
1881 $(this.embedPopup).css({
1882 position: 'absolute',
1884 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
1887 border: "3px double #999999",
1889 backgroundColor: "#fff"
1890 }).appendTo('#GnuBook');
1892 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1893 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>';
1894 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
1895 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1897 this.embedPopup.innerHTML = htmlStr;
1898 $(this.embedPopup).find('input').bind('click', function() {
1904 //______________________________________________________________________________
1905 GnuBook.prototype.autoToggle = function() {
1907 var bComingFrom1up = false;
1908 if (2 != this.mode) {
1909 bComingFrom1up = true;
1914 if (null == this.autoTimer) {
1915 this.flipSpeed = 2000;
1917 // $$$ Draw events currently cause layout problems when they occur during animation.
1918 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1919 // we workaround for now by not triggering immediate animation in that case.
1920 // See https://bugs.launchpad.net/gnubook/+bug/328327
1921 if (('rl' == this.pageProgression) && bComingFrom1up) {
1922 // don't flip immediately -- wait until timer fires
1925 this.flipFwdToIndex();
1928 $('#GBtoolbar .play').hide();
1929 $('#GBtoolbar .pause').show();
1930 this.autoTimer=setInterval(function(){
1931 if (self.animating) {return;}
1933 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
1934 self.flipBackToIndex(1); // $$$ really what we want?
1936 self.flipFwdToIndex();
1945 //______________________________________________________________________________
1946 GnuBook.prototype.autoStop = function() {
1947 if (null != this.autoTimer) {
1948 clearInterval(this.autoTimer);
1949 this.flipSpeed = 'fast';
1950 $('#GBtoolbar .pause').hide();
1951 $('#GBtoolbar .play').show();
1952 this.autoTimer = null;
1956 // keyboardNavigationIsDisabled(event)
1957 // - returns true if keyboard navigation should be disabled for the event
1958 //______________________________________________________________________________
1959 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
1960 if (event.target.tagName == "INPUT") {
1966 // gutterOffsetForIndex
1967 //______________________________________________________________________________
1969 // Returns the gutter offset for the spread containing the given index.
1970 // This function supports RTL
1971 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
1973 // $$$ incorporate zooming
1975 // To find the offset of the gutter from the middle we calculate our percentage distance
1976 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
1977 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
1979 // But then again for RTL it's the opposite
1980 if ('rl' == this.pageProgression) {
1988 //______________________________________________________________________________
1989 // Returns the width of the leaf edge div for the page with index given
1990 GnuBook.prototype.leafEdgeWidth = function(pindex) {
1991 // $$$ could there be single pixel rounding errors for L vs R?
1992 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
1993 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
1995 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
1999 // jumpIndexForLeftEdgePageX
2000 //______________________________________________________________________________
2001 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2002 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2003 if ('rl' != this.pageProgression) {
2004 // LTR - flipping backward
2005 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2007 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2008 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2012 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2013 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2018 // jumpIndexForRightEdgePageX
2019 //______________________________________________________________________________
2020 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2021 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2022 if ('rl' != this.pageProgression) {
2024 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2025 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2028 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2029 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2034 GnuBook.prototype.initToolbar = function(mode, ui) {
2036 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2037 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2038 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2039 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2040 + " <span class='label'>Zoom: <span id='GBzoom'>"+100/this.reduce+"</span>%</span>"
2041 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2042 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2043 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2046 if (ui == "embed") {
2047 $("#GnuBook a.logo").attr("target","_blank");
2050 // $$$ turn this into a member variable
2051 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2053 // We build in mode 2
2054 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2055 + "<button class='GBicon rollover embed' />"
2056 + "<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>"
2057 + "<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>"
2058 + "<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>"
2059 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2061 this.bindToolbarNavHandlers(jToolbar);
2063 // Setup tooltips -- later we could load these from a file for i18n
2064 var titles = { '.logo': 'Go to Archive.org',
2065 '.zoom_in': 'Zoom in',
2066 '.zoom_out': 'Zoom out',
2067 '.one_page_mode': 'One-page view',
2068 '.two_page_mode': 'Two-page view',
2069 '.embed': 'Embed bookreader',
2070 '.book_left': 'Flip left',
2071 '.book_right': 'Flip right',
2072 '.book_up': 'Page up',
2073 '.book_down': 'Page down',
2076 '.book_top': 'First page',
2077 '.book_bottom': 'Last page'
2079 if ('rl' == this.pageProgression) {
2080 titles['.book_leftmost'] = 'Last page';
2081 titles['.book_rightmost'] = 'First page';
2083 titles['.book_leftmost'] = 'First page';
2084 titles['.book_rightmost'] = 'Last page';
2087 for (var icon in titles) {
2088 jToolbar.find(icon).attr('title', titles[icon]);
2091 // Hide mode buttons and autoplay if 2up is not available
2092 // $$$ if we end up with more than two modes we should show the applicable buttons
2093 if ( !this.canSwitchToMode(this.constMode2up) ) {
2094 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2097 // Switch to requested mode -- binds other click handlers
2098 this.switchToolbarMode(mode);
2103 // switchToolbarMode
2104 //______________________________________________________________________________
2105 // Update the toolbar for the given mode (changes navigation buttons)
2106 // $$$ we should soon split the toolbar out into its own module
2107 GnuBook.prototype.switchToolbarMode = function(mode) {
2110 $('#GBtoolbar .GBtoolbarmode2').hide();
2111 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2114 $('#GBtoolbar .GBtoolbarmode1').hide();
2115 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2119 // bindToolbarNavHandlers
2120 //______________________________________________________________________________
2121 // Binds the toolbar handlers
2122 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2124 jToolbar.find('.book_left').bind('click', function(e) {
2129 jToolbar.find('.book_right').bind('click', function(e) {
2134 jToolbar.find('.book_up').bind('click', function(e) {
2139 jToolbar.find('.book_down').bind('click', function(e) {
2144 jToolbar.find('.embed').bind('click', function(e) {
2149 jToolbar.find('.play').bind('click', function(e) {
2154 jToolbar.find('.pause').bind('click', function(e) {
2159 jToolbar.find('.book_top').bind('click', function(e) {
2164 jToolbar.find('.book_bottom').bind('click', function(e) {
2169 jToolbar.find('.book_leftmost').bind('click', function(e) {
2174 jToolbar.find('.book_rightmost').bind('click', function(e) {
2180 // firstDisplayableIndex
2181 //______________________________________________________________________________
2182 // Returns the index of the first visible page, dependent on the mode.
2183 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2184 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2185 GnuBook.prototype.firstDisplayableIndex = function() {
2186 if (this.mode == 0) {
2189 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2193 // lastDisplayableIndex
2194 //______________________________________________________________________________
2195 // Returns the index of the last visible page, dependent on the mode.
2196 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2197 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2198 GnuBook.prototype.lastDisplayableIndex = function() {
2199 if (this.mode == 2) {
2200 if (this.lastDisplayableIndex2up === null) {
2201 // Calculate and cache
2202 var candidate = this.numLeafs - 1;
2203 for ( ; candidate >= 0; candidate--) {
2204 var spreadIndices = this.getSpreadIndices(candidate);
2205 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2209 this.lastDisplayableIndex2up = candidate;
2211 return this.lastDisplayableIndex2up;
2213 return this.numLeafs - 1;
2217 // shortTitle(maximumCharacters)
2219 // Returns a shortened version of the title with the maximum number of characters
2220 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2221 if (this.bookTitle.length < maximumCharacters) {
2222 return this.bookTitle;
2225 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2232 // Parameter related functions
2234 // updateFromParams(params)
2236 // Update ourselves from the params object.
2238 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2239 GnuBook.prototype.updateFromParams = function(params) {
2240 if ('undefined' != typeof(params.mode)) {
2241 this.switchMode(params.mode);
2244 // $$$ process /search
2245 // $$$ process /zoom
2247 // We only respect page if index is not set
2248 if ('undefined' != typeof(params.index)) {
2249 if (params.index != this.currentIndex()) {
2250 this.jumpToIndex(params.index);
2252 } else if ('undefined' != typeof(params.page)) {
2253 // $$$ this assumes page numbers are unique
2254 if (params.page != this.getPageNum(this.currentIndex())) {
2255 this.jumpToPage(params.page);
2259 // $$$ process /region
2260 // $$$ process /highlight
2263 // paramsFromFragment(urlFragment)
2265 // Returns a object with configuration parametes from a URL fragment.
2267 // E.g paramsFromFragment(window.location.hash)
2268 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2269 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2273 // For convenience we allow an initial # character (as from window.location.hash)
2274 // but don't require it
2275 if (urlFragment.substr(0,1) == '#') {
2276 urlFragment = urlFragment.substr(1);
2279 // Simple #nn syntax
2280 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2281 if ( !isNaN(oldStyleLeafNum) ) {
2282 params.index = oldStyleLeafNum;
2284 // Done processing if using old-style syntax
2288 // Split into key-value pairs
2289 var urlArray = urlFragment.split('/');
2291 for (var i = 0; i < urlArray.length; i += 2) {
2292 urlHash[urlArray[i]] = urlArray[i+1];
2296 if ('1up' == urlHash['mode']) {
2297 params.mode = this.constMode1up;
2298 } else if ('2up' == urlHash['mode']) {
2299 params.mode = this.constMode2up;
2303 if ('undefined' != typeof(urlHash['page'])) {
2304 // page was set -- may not be int
2305 params.page = urlHash['page'];
2308 // $$$ process /region
2309 // $$$ process /search
2310 // $$$ process /highlight
2315 // paramsFromCurrent()
2317 // Create a params object from the current parameters.
2318 GnuBook.prototype.paramsFromCurrent = function() {
2322 var pageNum = this.getPageNum(this.currentIndex());
2323 if ((pageNum === 0) || pageNum) {
2324 params.page = pageNum;
2327 params.index = this.currentIndex();
2328 params.mode = this.mode;
2337 // fragmentFromParams(params)
2339 // Create a fragment string from the params object.
2340 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2341 GnuBook.prototype.fragmentFromParams = function(params) {
2342 var separator = '/';
2346 if ('undefined' != typeof(params.page)) {
2347 fragments.push('page', params.page);
2349 // Don't have page numbering -- use index instead
2350 fragments.push('page', 'n' + params.index);
2358 if ('undefined' != typeof(params.mode)) {
2359 if (params.mode == this.constMode1up) {
2360 fragments.push('mode', '1up');
2361 } else if (params.mode == this.constMode2up) {
2362 fragments.push('mode', '2up');
2364 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2368 return fragments.join(separator);
2371 // getPageIndex(pageNum)
2373 // Returns the *highest* index the given page number, or undefined
2374 GnuBook.prototype.getPageIndex = function(pageNum) {
2375 var pageIndices = this.getPageIndices(pageNum);
2377 if (pageIndices.length > 0) {
2378 return pageIndices[pageIndices.length - 1];
2384 // getPageIndices(pageNum)
2386 // Returns an array (possibly empty) of the indices with the given page number
2387 GnuBook.prototype.getPageIndices = function(pageNum) {
2390 // Check for special "nXX" page number
2391 if (pageNum.slice(0,1) == 'n') {
2393 var pageIntStr = pageNum.slice(1, pageNum.length);
2394 var pageIndex = parseInt(pageIntStr);
2395 indices.append(pageIndex);
2398 // Do nothing... will run through page names and see if one matches
2403 for (i=0; i<this.numLeafs; i++) {
2404 if (this.getPageNum(i) == pageNum) {
2412 // getPageName(index)
2414 // Returns the name of the page as it should be displayed in the user interface
2415 GnuBook.prototype.getPageName = function(index) {
2416 return 'Page ' + this.getPageNum(index);
2419 // updateLocationHash
2421 // Update the location hash from the current parameters. Call this instead of manually
2422 // using window.location.replace
2423 GnuBook.prototype.updateLocationHash = function() {
2424 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2425 window.location.replace(newHash);
2427 // This is the variable checked in the timer. Only user-generated changes
2428 // to the URL will trigger the event.
2429 this.oldLocationHash = newHash;
2432 // startLocationPolling
2434 // Starts polling of window.location to see hash fragment changes
2435 GnuBook.prototype.startLocationPolling = function() {
2436 var self = this; // remember who I am
2437 self.oldLocationHash = window.location.hash;
2439 if (this.locationPollId) {
2440 clearInterval(this.locationPollID);
2441 this.locationPollId = null;
2444 this.locationPollId = setInterval(function() {
2445 var newHash = window.location.hash;
2446 if (newHash != self.oldLocationHash) {
2447 if (newHash != self.oldUserHash) { // Only process new user hash once
2448 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2450 // Queue change if animating
2451 if (self.animating) {
2453 self.animationFinishedCallback = function() {
2454 self.updateFromParams(self.paramsFromFragment(newHash));
2456 } else { // update immediately
2457 self.updateFromParams(self.paramsFromFragment(newHash));
2459 self.oldUserHash = newHash;
2467 // Returns a URL for an embedded version of the current book
2468 GnuBook.prototype.getEmbedURL = function() {
2469 // We could generate a URL hash fragment here but for now we just leave at defaults
2470 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2475 // Returns the embed code HTML fragment suitable for copy and paste
2476 GnuBook.prototype.getEmbedCode = function() {
2477 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2482 // Returns true if we can switch to the requested mode
2483 GnuBook.prototype.canSwitchToMode = function(mode) {
2484 if (mode == this.constMode2up) {
2485 // check there are enough pages to display
2486 // $$$ this is a workaround for the mis-feature that we can't display
2487 // short books in 2up mode
2488 if (this.numLeafs < 6) {
2496 // Library functions
2498 clamp: function(value, min, max) {
2499 return Math.min(Math.max(value, min), max);