2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of GnuBook.
6 GnuBook is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Affero General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GnuBook is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Affero General Public License for more details.
16 You should have received a copy of the GNU Affero General Public License
17 along with GnuBook. If not, see <http://www.gnu.org/licenses/>.
19 The GnuBook source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init():
31 // You must also add a numLeafs property before calling init().
34 if (typeof(console) == 'undefined') {
35 console = { log: function(msg) { } };
41 this.mode = 1; //1 or 2
42 this.ui = 'full'; // UI mode
44 this.displayedIndices = [];
45 //this.indicesToDisplay = [];
47 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
50 this.animating = false;
52 this.autoTimer = null;
53 this.flipSpeed = 'fast';
55 this.twoPagePopUp = null;
56 this.leafEdgeTmp = null;
57 this.embedPopup = null;
59 this.searchResults = {};
61 this.firstIndex = null;
63 this.lastDisplayableIndex2up = null;
65 // We link to index.php to avoid redirect which breaks back button
66 this.logoURL = 'http://www.archive.org/index.php';
68 // Base URL for images
69 this.imagesBaseURL = '/bookreader/images/';
72 this.constMode1up = 1;
73 this.constMode2up = 2;
78 //______________________________________________________________________________
79 GnuBook.prototype.init = function() {
81 var startIndex = undefined;
83 // Find start index and mode if set in location hash
84 var params = this.paramsFromFragment(window.location.hash);
86 if ('undefined' != typeof(params.index)) {
87 startIndex = params.index;
88 } else if ('undefined' != typeof(params.page)) {
89 startIndex = this.getPageIndex(params.page);
92 if ('undefined' == typeof(startIndex)) {
93 if ('undefined' != typeof(this.titleLeaf)) {
94 startIndex = this.leafNumToIndex(this.titleLeaf);
98 if ('undefined' == typeof(startIndex)) {
102 if ('undefined' != typeof(params.mode)) {
103 this.mode = params.mode;
106 // Set document title -- may have already been set in enclosing html for
107 // search engine visibility
108 document.title = this.shortTitle(50);
110 // Sanitize parameters
111 if ( !this.canSwitchToMode( this.mode ) ) {
112 this.mode = this.constMode1up;
115 $("#GnuBook").empty();
116 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
117 $("#GnuBook").append("<div id='GBcontainer'></div>");
118 $("#GBcontainer").append("<div id='GBpageview'></div>");
120 $("#GBcontainer").bind('scroll', this, function(e) {
124 this.setupKeyListeners();
125 this.startLocationPolling();
127 $(window).bind('resize', this, function(e) {
128 //console.log('resize!');
129 if (1 == e.data.mode) {
130 //console.log('centering 1page view');
131 e.data.centerPageView();
132 $('#GBpageview').empty()
133 e.data.displayedIndices = [];
134 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
137 //console.log('drawing 2 page view');
138 e.data.prepareTwoPageView();
142 $('.GBpagediv1up').bind('mousedown', this, function(e) {
143 //console.log('mousedown!');
146 if (1 == this.mode) {
147 this.resizePageView();
148 this.firstIndex = startIndex;
149 this.jumpToIndex(startIndex);
151 //this.resizePageView();
153 this.displayedIndices=[0];
154 this.firstIndex = startIndex;
155 this.displayedIndices = [this.firstIndex];
156 //console.log('titleLeaf: %d', this.titleLeaf);
157 //console.log('displayedIndices: %s', this.displayedIndices);
158 this.prepareTwoPageView();
159 //if (this.auto) this.nextPage();
162 // Enact other parts of initial params
163 this.updateFromParams(params);
166 GnuBook.prototype.setupKeyListeners = function() {
179 // We use document here instead of window to avoid a bug in jQuery on IE7
180 $(document).keydown(function(e) {
182 // Keyboard navigation
186 // In 1up mode page scrolling is handled by browser
187 if (2 == self.mode) {
193 if (2 == self.mode) {
204 if (self.keyboardNavigationIsDisabled(e)) {
207 if (2 == self.mode) {
212 if (self.keyboardNavigationIsDisabled(e)) {
215 if (2 == self.mode) {
224 //______________________________________________________________________________
225 GnuBook.prototype.drawLeafs = function() {
226 if (1 == this.mode) {
227 this.drawLeafsOnePage();
229 this.drawLeafsTwoPage();
233 // setDragHandler1up()
234 //______________________________________________________________________________
235 GnuBook.prototype.setDragHandler1up = function(div) {
236 div.dragging = false;
238 $(div).bind('mousedown', function(e) {
239 //console.log('mousedown at ' + e.pageY);
241 this.dragging = true;
242 this.prevMouseX = e.pageX;
243 this.prevMouseY = e.pageY;
245 var startX = e.pageX;
246 var startY = e.pageY;
247 var startTop = $('#GBcontainer').attr('scrollTop');
248 var startLeft = $('#GBcontainer').attr('scrollLeft');
253 $(div).bind('mousemove', function(ee) {
254 //console.log('mousemove ' + startY);
256 var offsetX = ee.pageX - this.prevMouseX;
257 var offsetY = ee.pageY - this.prevMouseY;
260 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
261 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
264 this.prevMouseX = ee.pageX;
265 this.prevMouseY = ee.pageY;
270 $(div).bind('mouseup', function(ee) {
271 //console.log('mouseup');
273 this.dragging = false;
277 $(div).bind('mouseleave', function(e) {
278 //console.log('mouseleave');
280 //$(this).unbind('mousemove mouseup');
281 this.dragging = false;
286 // drawLeafsOnePage()
287 //______________________________________________________________________________
288 GnuBook.prototype.drawLeafsOnePage = function() {
289 //alert('drawing leafs!');
293 var scrollTop = $('#GBcontainer').attr('scrollTop');
294 var scrollBottom = scrollTop + $('#GBcontainer').height();
295 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
297 var indicesToDisplay = [];
302 for (i=0; i<this.numLeafs; i++) {
303 var height = parseInt(this.getPageHeight(i)/this.reduce);
305 leafBottom += height;
306 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
307 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
308 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
309 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
310 if (topInView | bottomInView | middleInView) {
311 //console.log('displayed: ' + this.displayedIndices);
312 //console.log('to display: ' + i);
313 indicesToDisplay.push(i);
315 leafTop += height +10;
319 var firstIndexToDraw = indicesToDisplay[0];
320 this.firstIndex = firstIndexToDraw;
322 // Update hash, but only if we're currently displaying a leaf
323 // Hack that fixes #365790
324 if (this.displayedIndices.length > 0) {
325 this.updateLocationHash();
328 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
330 indicesToDisplay.unshift(firstIndexToDraw);
333 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
334 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
335 indicesToDisplay.push(lastIndexToDraw+1);
340 for (i=0; i<firstIndexToDraw; i++) {
341 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
344 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
345 var viewWidth = $('#GBcontainer').attr('scrollWidth');
348 for (i=0; i<indicesToDisplay.length; i++) {
349 var index = indicesToDisplay[i];
350 var height = parseInt(this.getPageHeight(index)/this.reduce);
352 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
353 var width = parseInt(this.getPageWidth(index)/this.reduce);
354 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
355 var div = document.createElement("div");
356 div.className = 'GBpagediv1up';
357 div.id = 'pagediv'+index;
358 div.style.position = "absolute";
359 $(div).css('top', leafTop + 'px');
360 var left = (viewWidth-width)>>1;
361 if (left<0) left = 0;
362 $(div).css('left', left+'px');
363 $(div).css('width', width+'px');
364 $(div).css('height', height+'px');
365 //$(div).text('loading...');
367 this.setDragHandler1up(div);
369 $('#GBpageview').append(div);
371 var img = document.createElement("img");
372 img.src = this.getPageURI(index);
373 $(img).css('width', width+'px');
374 $(img).css('height', height+'px');
378 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
381 leafTop += height +10;
385 for (i=0; i<this.displayedIndices.length; i++) {
386 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
387 var index = this.displayedIndices[i];
388 //console.log('Removing leaf ' + index);
389 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
390 $('#pagediv'+index).remove();
392 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
396 this.displayedIndices = indicesToDisplay.slice();
397 this.updateSearchHilites();
399 if (null != this.getPageNum(firstIndexToDraw)) {
400 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
402 $("#GBpagenum").val('');
405 //var centerY = this.centerY1up();
406 //var centerX = this.centerX1up();
407 //console.log('draw center ' + centerY + ',' + centerX);
408 //console.log('scroll left ' + $('#GBcontainer').attr('scrollLeft'));
412 // drawLeafsTwoPage()
413 //______________________________________________________________________________
414 GnuBook.prototype.drawLeafsTwoPage = function() {
415 console.log('drawing two leafs!'); // XXX
417 var scrollTop = $('#GBtwopageview').attr('scrollTop');
418 var scrollBottom = scrollTop + $('#GBtwopageview').height();
420 console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.currentIndexL); // XXX
422 var index = this.currentIndexL;
423 var height = this.getPageHeight(index);
424 var width = this.getPageWidth(index);
425 var handSide= this.getPageSide(index);
427 var leafEdgeWidthL = this.leafEdgeWidth(index);
428 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
429 var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
430 var bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
431 //console.log(leafEdgeWidthL);
433 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
434 var left = middle - this.twoPageW;
435 var top = ($('#GBtwopageview').height() - this.twoPageH) >> 1;
437 var scaledW = parseInt(this.twoPageH*width/height);
438 left = 10+leafEdgeWidthL;
439 //var right = left+scaledW;
440 var right = $(this.twoPageDiv).width()-11-$(this.leafEdgeL).width()-scaledW;
442 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
444 this.prefetchImg(index);
445 $(this.prefetchedImgs[index]).css({
446 position: 'absolute',
447 /*right: gutter+'px',*/
448 left: gutter-scaledW+'px',
451 backgroundColor: 'rgb(234, 226, 205)',
452 height: this.twoPageH +'px',
453 width: scaledW + 'px',
454 borderRight: '1px solid black',
456 }).appendTo('#GBtwopageview');
457 //$('#GBcontainer').append(this.prefetchedImgs[index]);
460 var index = this.currentIndexR;
461 var height = this.getPageHeight(index);
462 var width = this.getPageWidth(index);
463 // var left = ($('#GBcontainer').width() >> 1);
466 var scaledW = this.twoPageH*width/height;
467 this.prefetchImg(index);
468 $(this.prefetchedImgs[index]).css({
469 position: 'absolute',
473 backgroundColor: 'rgb(234, 226, 205)',
474 height: this.twoPageH + 'px',
475 width: scaledW + 'px',
476 borderLeft: '1px solid black',
478 }).appendTo('#GBtwopageview');
479 //$('#GBcontainer').append(this.prefetchedImgs[index]);
482 this.displayedIndices = [this.currentIndexL, this.currentIndexR];
483 this.setClickHandlers();
485 this.updatePageNumBox2UP();
488 // updatePageNumBox2UP
489 //______________________________________________________________________________
490 GnuBook.prototype.updatePageNumBox2UP = function() {
491 if (null != this.getPageNum(this.currentIndexL)) {
492 $("#GBpagenum").val(this.getPageNum(this.currentIndexL));
494 $("#GBpagenum").val('');
496 this.updateLocationHash();
500 //______________________________________________________________________________
501 GnuBook.prototype.loadLeafs = function() {
505 if (null == this.timer) {
506 this.timer=setTimeout(function(){self.drawLeafs()},250);
508 clearTimeout(this.timer);
509 this.timer=setTimeout(function(){self.drawLeafs()},250);
515 // Pass 1 to zoom in, anything else to zoom out
516 //______________________________________________________________________________
517 GnuBook.prototype.zoom = function(direction) {
519 case this.constMode1up:
520 return this.zoom1up(direction);
521 case this.constMode2up:
522 return this.zoom2up(direction);
527 //______________________________________________________________________________
528 GnuBook.prototype.zoom1up = function(dir) {
529 if (2 == this.mode) { //can only zoom in 1-page mode
534 // $$$ with flexible zoom we could "snap" to /2 page reductions
535 // for better scaling
537 if (this.reduce <= 0.5) return;
538 this.reduce*=0.5; //zoom in
540 if (this.reduce >= 8) return;
541 this.reduce*=2; //zoom out
544 this.resizePageView();
546 $('#GBpageview').empty()
547 this.displayedIndices = [];
550 $('#GBzoom').text(100/this.reduce);
554 //______________________________________________________________________________
555 GnuBook.prototype.resizePageView = function() {
558 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
559 var viewWidth = $('#GBcontainer').attr('clientWidth');
561 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
562 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
563 var oldPageViewHeight = $('#GBpageview').height();
564 var oldPageViewWidth = $('#GBpageview').width();
566 var oldCenterY = this.centerY1up();
567 var oldCenterX = this.centerX1up();
569 if (0 != oldPageViewHeight) {
570 var scrollRatio = oldCenterY / oldPageViewHeight;
575 for (i=0; i<this.numLeafs; i++) {
576 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
577 var width = parseInt(this.getPageWidth(i)/this.reduce);
578 if (width>viewWidth) viewWidth=width;
580 $('#GBpageview').height(viewHeight);
581 $('#GBpageview').width(viewWidth);
583 var newCenterY = scrollRatio*viewHeight;
584 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
585 $('#GBcontainer').attr('scrollTop', newTop);
587 // We use clientWidth here to avoid miscalculating due to scroll bar
588 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
589 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
590 newLeft = Math.min(newLeft, 0);
591 $('#GBcontainer').attr('scrollLeft', newLeft);
592 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
594 //this.centerPageView();
600 //______________________________________________________________________________
601 // Returns the current offset of the viewport center in scaled document coordinates.
602 GnuBook.prototype.centerX1up = function() {
604 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
605 centerX = $('#GBpageview').width();
607 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
609 centerX = Math.floor(centerX);
614 //______________________________________________________________________________
615 // Returns the current offset of the viewport center in scaled document coordinates.
616 GnuBook.prototype.centerY1up = function() {
617 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
618 return Math.floor(centerY);
622 //______________________________________________________________________________
623 GnuBook.prototype.centerPageView = function() {
625 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
626 var clientWidth = $('#GBcontainer').attr('clientWidth');
627 //console.log('sW='+scrollWidth+' cW='+clientWidth);
628 if (scrollWidth > clientWidth) {
629 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
634 // zoom2up(direction)
635 //______________________________________________________________________________
636 GnuBook.prototype.zoom2up = function(direction) {
637 // $$$ this is where we can e.g. snap to %2 sizes
639 if (1 == direction) {
640 if (this.reduce <= 0.5) return;
641 return this.zoom2upPercentage( 1 / (this.reduce*=0.5) ); //zoom in
643 if (this.reduce >= 8) return;
644 return this.zoom2upPercentage( 1 / (this.reduce*2) ); // zoom out
649 // zoom2upPercentage(percentage)
650 //______________________________________________________________________________
651 GnuBook.prototype.zoom2upPercentage = function(percentage) {
652 this.reduce = 1/percentage;
653 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.currentIndexL, this.currentIndexR)) {
686 this.flipBackToIndex(index);
687 } else if (index > Math.max(this.currentIndexL, this.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();
754 $('#GBzoom').text(100/this.reduce);
756 // Bind mouse handlers
757 // Disable mouse click to avoid selected/highlighted page images - bug 354239
758 gbPageView.bind('mousedown', function(e) {
761 // Special hack for IE7
762 gbPageView[0].onselectstart = function(e) { return false; };
765 // prepareTwoPageView()
766 //______________________________________________________________________________
767 GnuBook.prototype.prepareTwoPageView = function() {
768 $('#GBcontainer').empty();
770 // Add the two page view
771 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
772 // Explicitly set sizes the same
773 $('#GBtwopageview').css( {
774 height: $('#GBcontainer').height(),
775 width: $('#GBcontainer').width(),
779 // We want to display two facing pages. We may be missing
780 // one side of the spread because it is the first/last leaf,
781 // foldouts, missing pages, etc
783 //var targetLeaf = this.displayedIndices[0];
784 var targetLeaf = this.firstIndex;
786 if (targetLeaf < this.firstDisplayableIndex()) {
787 targetLeaf = this.firstDisplayableIndex();
790 if (targetLeaf > this.lastDisplayableIndex()) {
791 targetLeaf = this.lastDisplayableIndex();
794 this.currentIndexL = null;
795 this.currentIndexR = null;
796 this.pruneUnusedImgs();
798 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
799 this.currentIndexL = currentSpreadIndices[0];
800 this.currentIndexR = currentSpreadIndices[1];
801 this.firstIndex = this.currentIndexL;
803 this.calculateSpreadSize(); //sets this.twoPageW, twoPageH, and twoPageRatio
805 // We want to minimize the unused space in two-up mode (maximize the amount of page
806 // shown). We give width to the leaf edges and these widths change (though the sum
807 // of the two remains constant) as we flip through the book. With the book
808 // cover centered and fixed in the GBcontainer div the page images will meet
809 // at the "gutter" which is generally offset from the center.
810 var middle = ($('#GBcontainer').attr('clientWidth') >> 1); // Middle of the GBcontainer div
811 //var gutter = middle+parseInt((2*this.currentIndexL - this.numLeafs)*this.twoPageEdgeW/this.numLeafs/2);
813 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
815 var scaledWL = this.getPageWidth2UP(this.currentIndexL);
816 var scaledWR = this.getPageWidth2UP(this.currentIndexR);
817 var leafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
818 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
820 //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
821 //var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
823 // The width of the book cover div. The combined width of both pages, twice the width
824 // of the book cover internal padding (2*10) and the page edges
825 var bookCoverDivWidth = scaledWL + scaledWR + 20 + this.twoPageEdgeW;
827 // The height of the book cover div
828 var bookCoverDivHeight = this.twoPageH+20;
830 //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
831 var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-10;
832 var bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
833 //console.log('bookCoverDivWidth='+bookCoverDivWidth+' bookCoverDivHeight='+bookCoverDivHeight+ ' bookCoverDivLeft='+bookCoverDivLeft+' bookCoverDivTop='+bookCoverDivTop);
835 this.twoPageDiv = document.createElement('div');
836 $(this.twoPageDiv).attr('id', 'GBbookcover').css({
837 border: '1px solid rgb(68, 25, 17)',
838 width: bookCoverDivWidth + 'px',
839 height: bookCoverDivHeight+'px',
840 visibility: 'visible',
841 position: 'absolute',
842 backgroundColor: '#663929',
843 left: bookCoverDivLeft + 'px',
844 top: bookCoverDivTop+'px',
845 MozBorderRadiusTopleft: '7px',
846 MozBorderRadiusTopright: '7px',
847 MozBorderRadiusBottomright: '7px',
848 MozBorderRadiusBottomleft: '7px'
849 }).appendTo('#GBtwopageview');
850 //$('#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;"/>');
853 var height = this.getPageHeight(this.currentIndexR);
854 var width = this.getPageWidth(this.currentIndexR);
855 var scaledW = this.twoPageH*width/height;
857 this.leafEdgeR = document.createElement('div');
858 this.leafEdgeR.className = 'leafEdgeR';
859 $(this.leafEdgeR).css({
860 borderStyle: 'solid solid solid none',
861 borderColor: 'rgb(51, 51, 34)',
862 borderWidth: '1px 1px 1px 0px',
863 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
864 width: leafEdgeWidthR + 'px',
865 height: this.twoPageH-1 + 'px',
867 left: gutter+scaledW+'px',
868 top: bookCoverDivTop+10+'px',
870 }).appendTo('#GBtwopageview');
872 this.leafEdgeL = document.createElement('div');
873 this.leafEdgeL.className = 'leafEdgeL';
874 $(this.leafEdgeL).css({
875 borderStyle: 'solid none solid solid',
876 borderColor: 'rgb(51, 51, 34)',
877 borderWidth: '1px 0px 1px 1px',
878 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
879 width: leafEdgeWidthL + 'px',
880 height: this.twoPageH-1 + 'px',
881 left: bookCoverDivLeft+10+'px',
882 top: bookCoverDivTop+10+'px',
884 }).appendTo('#GBtwopageview');
888 bookCoverDivWidth = 30;
889 bookCoverDivHeight = this.twoPageH+20;
890 bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
891 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
893 div = document.createElement('div');
894 $(div).attr('id', 'GBbookspine').css({
895 border: '1px solid rgb(68, 25, 17)',
896 width: bookCoverDivWidth+'px',
897 height: bookCoverDivHeight+'px',
898 position: 'absolute',
899 backgroundColor: 'rgb(68, 25, 17)',
900 left: bookCoverDivLeft+'px',
901 top: bookCoverDivTop+'px'
902 }).appendTo('#GBtwopageview');
903 //$('#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;"/>');
905 bookCoverDivWidth = this.twoPageW*2;
906 bookCoverDivHeight = this.twoPageH;
907 bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
908 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
911 this.prepareTwoPagePopUp();
913 this.displayedIndices = [];
915 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
916 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
918 this.drawLeafsTwoPage();
919 this.updateSearchHilites2UP();
922 $('#GBzoom').text((100*this.twoPageH/this.getPageHeight(this.currentIndexL)).toString().substr(0,4));
925 // prepareTwoPagePopUp()
927 // This function prepares the "View Page n" popup that shows while the mouse is
928 // over the left/right "stack of sheets" edges. It also binds the mouse
929 // events for these divs.
930 //______________________________________________________________________________
931 GnuBook.prototype.prepareTwoPagePopUp = function() {
933 this.twoPagePopUp = document.createElement('div');
934 $(this.twoPagePopUp).css({
935 border: '1px solid black',
937 position: 'absolute',
938 fontFamily: 'sans-serif',
941 backgroundColor: 'rgb(255, 255, 238)',
943 }).appendTo('#GBcontainer');
944 $(this.twoPagePopUp).hide();
946 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
947 $(e.data.twoPagePopUp).show();
950 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
951 $(e.data.twoPagePopUp).hide();
954 $(this.leafEdgeL).bind('click', this, function(e) {
956 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
957 e.data.jumpToIndex(jumpIndex);
960 $(this.leafEdgeR).bind('click', this, function(e) {
962 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
963 e.data.jumpToIndex(jumpIndex);
966 $(this.leafEdgeR).bind('mousemove', this, function(e) {
968 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
969 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
971 // $$$ TODO: Make sure popup is positioned so that it is in view
972 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
973 $(e.data.twoPagePopUp).css({
974 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
975 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
979 $(this.leafEdgeL).bind('mousemove', this, function(e) {
981 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
982 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
984 // $$$ TODO: Make sure popup is positioned so that it is in view
985 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
986 $(e.data.twoPagePopUp).css({
987 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
988 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
993 // calculateSpreadSize()
994 //______________________________________________________________________________
995 // Calculates 2-page spread dimensions based on this.currentIndexL and
996 // this.currentIndexR
997 // This function sets this.twoPageH, twoPageW, and twoPageRatio
999 GnuBook.prototype.calculateSpreadSize = function() {
1000 console.log('calculateSpreadSize ' + this.currentIndexL); // XXX
1002 var firstIndex = this.currentIndexL;
1003 var secondIndex = this.currentIndexR;
1004 //console.log('first page is ' + firstIndex);
1006 var canon5Dratio = 1.5;
1008 var firstIndexRatio = this.getPageHeight(firstIndex) / this.getPageWidth(firstIndex);
1009 var secondIndexRatio = this.getPageHeight(secondIndex) / this.getPageWidth(secondIndex);
1010 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1013 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1014 ratio = firstIndexRatio;
1015 //console.log('using firstIndexRatio ' + ratio);
1017 ratio = secondIndexRatio;
1018 //console.log('using secondIndexRatio ' + ratio);
1021 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1022 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1023 totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1026 $('#GBcontainer').css('overflow', 'auto');
1028 var idealWidth = ($('#GBcontainer').attr('clientWidth') - 30 - totalLeafEdgeWidth)>>1;
1029 var idealHeight = $('#GBcontainer').height() - 30; // $$$ why - 30? book edge width?
1030 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
1032 if (idealHeight/ratio <= idealWidth) {
1034 idealWidth = parseInt(idealHeight/ratio);
1037 idealHeight = parseInt(idealWidth*ratio);
1040 this.twoPageH = idealHeight;
1041 this.twoPageW = idealWidth;
1042 this.twoPageRatio = ratio;
1043 this.twoPageEdgeW = totalLeafEdgeWidth; // The combined width of both edges
1046 // this.twoPageH *= 2;
1047 // this.twoPageW *= 2;
1048 // this.twoPageEdgeW *= 2;
1053 //______________________________________________________________________________
1054 // Returns the currently active index.
1055 GnuBook.prototype.currentIndex = function() {
1056 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1057 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1058 return this.firstIndex;
1060 throw 'currentIndex called for unimplemented mode ' + this.mode;
1065 //______________________________________________________________________________
1066 // Flip the right page over onto the left
1067 GnuBook.prototype.right = function() {
1068 if ('rl' != this.pageProgression) {
1078 //______________________________________________________________________________
1079 // Flip to the rightmost page
1080 GnuBook.prototype.rightmost = function() {
1081 if ('rl' != this.pageProgression) {
1089 //______________________________________________________________________________
1090 // Flip the left page over onto the right.
1091 GnuBook.prototype.left = function() {
1092 if ('rl' != this.pageProgression) {
1102 //______________________________________________________________________________
1103 // Flip to the leftmost page
1104 GnuBook.prototype.leftmost = function() {
1105 if ('rl' != this.pageProgression) {
1113 //______________________________________________________________________________
1114 GnuBook.prototype.next = function() {
1115 if (2 == this.mode) {
1117 this.flipFwdToIndex(null);
1119 if (this.firstIndex < this.lastDisplayableIndex()) {
1120 this.jumpToIndex(this.firstIndex+1);
1126 //______________________________________________________________________________
1127 GnuBook.prototype.prev = function() {
1128 if (2 == this.mode) {
1130 this.flipBackToIndex(null);
1132 if (this.firstIndex >= 1) {
1133 this.jumpToIndex(this.firstIndex-1);
1138 GnuBook.prototype.first = function() {
1139 if (2 == this.mode) {
1140 this.jumpToIndex(2);
1143 this.jumpToIndex(0);
1147 GnuBook.prototype.last = function() {
1148 if (2 == this.mode) {
1149 this.jumpToIndex(this.lastDisplayableIndex());
1152 this.jumpToIndex(this.lastDisplayableIndex());
1156 // flipBackToIndex()
1157 //______________________________________________________________________________
1158 // to flip back one spread, pass index=null
1159 GnuBook.prototype.flipBackToIndex = function(index) {
1160 if (1 == this.mode) return;
1162 var leftIndex = this.currentIndexL;
1164 // $$$ Need to change this to be able to see first spread.
1165 // See https://bugs.launchpad.net/gnubook/+bug/296788
1166 if (leftIndex <= 2) return;
1167 if (this.animating) return;
1169 if (null != this.leafEdgeTmp) {
1170 alert('error: leafEdgeTmp should be null!');
1174 if (null == index) {
1175 index = leftIndex-2;
1177 //if (index<0) return;
1179 var previousIndices = this.getSpreadIndices(index);
1181 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1185 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1187 this.animating = true;
1189 if ('rl' != this.pageProgression) {
1190 // Assume LTR and we are going backward
1191 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1192 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1195 // RTL and going backward
1196 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1197 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1201 // flipLeftToRight()
1202 //______________________________________________________________________________
1203 // Flips the page on the left towards the page on the right
1204 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1206 var leftLeaf = this.currentIndexL;
1208 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
1209 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1210 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1212 var currWidthL = this.getPageWidth2UP(leftLeaf);
1213 var newWidthL = this.getPageWidth2UP(newIndexL);
1214 var newWidthR = this.getPageWidth2UP(newIndexR);
1216 var top = ($('#GBtwopageview').height() - this.twoPageH) >> 1;
1218 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1219 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1221 //animation strategy:
1222 // 0. remove search highlight, if any.
1223 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1224 // of the left leaf and where the user clicked in the leaf edge.
1225 // Note that if this function was triggered by left() and not a
1226 // mouse click, the width of leafEdgeTmp is very small (zero px).
1227 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1228 // leftLeaf to width=0.
1229 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1230 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1231 // its new full width.
1232 // 4. After step 3 is finished, do the following:
1233 // - remove leafEdgeTmp from the dom.
1234 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1235 // and width=twoPageEdgeW-newLeafEdgeWidthL.
1236 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1237 // and width=newLeafEdgeWidthL.
1238 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1239 // and width=newWidthL+newWidthR+twoPageEdgeW+20
1240 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1241 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1242 // - prefetch new adjacent leafs.
1243 // - set up click handlers for both new left and right leafs.
1244 // - redraw the search highlight.
1245 // - update the pagenum box and the url.
1248 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1250 this.leafEdgeTmp = document.createElement('div');
1251 $(this.leafEdgeTmp).css({
1252 borderStyle: 'solid none solid solid',
1253 borderColor: 'rgb(51, 51, 34)',
1254 borderWidth: '1px 0px 1px 1px',
1255 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1256 width: leafEdgeTmpW + 'px',
1257 height: this.twoPageH-1 + 'px',
1258 left: leftEdgeTmpLeft + 'px',
1260 position: 'absolute',
1262 }).appendTo('#GBtwopageview');
1264 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1265 $(this.leafEdgeL).css({
1266 width: newLeafEdgeWidthL+'px',
1267 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1270 // Left gets the offset of the current left leaf from the document
1271 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1272 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1273 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1274 // We change the left leaf to right positioning
1275 $(this.prefetchedImgs[leftLeaf]).css({
1280 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1282 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1284 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1285 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1289 this.removeSearchHilites();
1291 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1292 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1294 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1295 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1297 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1298 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1299 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1301 $(self.leafEdgeR).css({
1302 // Moves the right leaf edge
1303 width: self.twoPageEdgeW-newLeafEdgeWidthL+'px',
1304 left: gutter+newWidthR+'px'
1307 $(self.leafEdgeL).css({
1308 // Moves and resizes the left leaf edge
1309 width: newLeafEdgeWidthL+'px',
1310 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1314 $(self.twoPageDiv).css({
1315 // Resizes the brown border div
1316 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1317 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1320 $(self.leafEdgeTmp).remove();
1321 self.leafEdgeTmp = null;
1323 self.currentIndexL = newIndexL;
1324 self.currentIndexR = newIndexR;
1325 self.firstIndex = self.currentIndexL;
1326 self.displayedIndices = [newIndexL, newIndexR];
1327 self.setClickHandlers();
1328 self.pruneUnusedImgs();
1330 self.animating = false;
1332 self.updateSearchHilites2UP();
1333 self.updatePageNumBox2UP();
1334 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1336 if (self.animationFinishedCallback) {
1337 self.animationFinishedCallback();
1338 self.animationFinishedCallback = null;
1346 //______________________________________________________________________________
1347 // Whether we flip left or right is dependent on the page progression
1348 // to flip forward one spread, pass index=null
1349 GnuBook.prototype.flipFwdToIndex = function(index) {
1351 if (this.animating) return;
1353 if (null != this.leafEdgeTmp) {
1354 alert('error: leafEdgeTmp should be null!');
1358 if (null == index) {
1359 index = this.currentIndexR+2; // $$$ assumes indices are continuous
1361 if (index > this.lastDisplayableIndex()) return;
1363 this.animating = true;
1365 var nextIndices = this.getSpreadIndices(index);
1367 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1369 if ('rl' != this.pageProgression) {
1370 // We did not specify RTL
1371 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1372 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1375 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1376 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1380 // flipRightToLeft(nextL, nextR, gutter)
1381 // $$$ better not to have to pass gutter in
1382 //______________________________________________________________________________
1383 // Flip from left to right and show the nextL and nextR indices on those sides
1384 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1385 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
1386 var oldLeafEdgeWidthR = this.twoPageEdgeW-oldLeafEdgeWidthL;
1387 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1388 var newLeafEdgeWidthR = this.twoPageEdgeW-newLeafEdgeWidthL;
1390 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1392 var top = ($('#GBtwopageview').height() - this.twoPageH) >> 1;
1394 var scaledW = this.getPageWidth2UP(this.currentIndexR);
1396 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1397 var currGutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
1400 console.log('R->L middle(' + middle +') currGutter(' + currGutter + ') gutter(' + gutter + ')');
1402 this.leafEdgeTmp = document.createElement('div');
1403 $(this.leafEdgeTmp).css({
1404 borderStyle: 'solid none solid solid',
1405 borderColor: 'rgb(51, 51, 34)',
1406 borderWidth: '1px 0px 1px 1px',
1407 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1408 width: leafEdgeTmpW + 'px',
1409 height: this.twoPageH-1 + 'px',
1410 left: currGutter+scaledW+'px',
1412 position: 'absolute',
1414 }).appendTo('#GBtwopageview');
1416 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1417 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1419 var currWidthL = this.getPageWidth2UP(this.currentIndexL);
1420 var currWidthR = this.getPageWidth2UP(this.currentIndexR);
1421 var newWidthL = this.getPageWidth2UP(newIndexL);
1422 var newWidthR = this.getPageWidth2UP(newIndexR);
1424 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1426 var self = this; // closure-tastic!
1428 var speed = this.flipSpeed;
1430 this.removeSearchHilites();
1432 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1433 $(this.prefetchedImgs[this.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1434 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1435 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1436 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1438 $(self.leafEdgeL).css({
1439 width: newLeafEdgeWidthL+'px',
1440 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1443 $(self.twoPageDiv).css({
1444 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1445 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1448 $(self.leafEdgeTmp).remove();
1449 self.leafEdgeTmp = null;
1451 self.currentIndexL = newIndexL;
1452 self.currentIndexR = newIndexR;
1453 self.firstIndex = self.currentIndexL;
1454 self.displayedIndices = [newIndexL, newIndexR];
1455 self.setClickHandlers();
1456 self.pruneUnusedImgs();
1458 self.animating = false;
1461 self.updateSearchHilites2UP();
1462 self.updatePageNumBox2UP();
1463 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1465 if (self.animationFinishedCallback) {
1466 self.animationFinishedCallback();
1467 self.animationFinishedCallback = null;
1474 //______________________________________________________________________________
1475 GnuBook.prototype.setClickHandlers = function() {
1477 $(this.prefetchedImgs[this.currentIndexL]).click(function() {
1482 $(this.prefetchedImgs[this.currentIndexR]).click(function() {
1490 //______________________________________________________________________________
1491 GnuBook.prototype.prefetchImg = function(index) {
1492 if (undefined == this.prefetchedImgs[index]) {
1493 //console.log('prefetching ' + index);
1494 var img = document.createElement("img");
1495 img.src = this.getPageURI(index);
1496 this.prefetchedImgs[index] = img;
1501 // prepareFlipLeftToRight()
1503 //______________________________________________________________________________
1505 // Prepare to flip the left page towards the right. This corresponds to moving
1506 // backward when the page progression is left to right.
1507 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1509 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1511 this.prefetchImg(prevL);
1512 this.prefetchImg(prevR);
1514 var height = this.getPageHeight(prevL);
1515 var width = this.getPageWidth(prevL);
1516 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1517 var top = ($('#GBtwopageview').height() - this.twoPageH) >> 1;
1518 var scaledW = this.twoPageH*width/height;
1520 // The gutter is the dividing line between the left and right pages.
1521 // It is offset from the middle to create the illusion of thickness to the pages
1522 var gutter = middle + this.gutterOffsetForIndex(prevL);
1525 console.log(' gutter for ' + prevL + ' is ' + gutter);
1526 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1527 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1529 $(this.prefetchedImgs[prevL]).css({
1530 position: 'absolute',
1531 /*right: middle+'px',*/
1532 left: gutter-scaledW+'px',
1535 backgroundColor: 'rgb(234, 226, 205)',
1536 height: this.twoPageH,
1537 width: scaledW+'px',
1538 borderRight: '1px solid black',
1542 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1544 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1546 $(this.prefetchedImgs[prevR]).css({
1547 position: 'absolute',
1551 backgroundColor: 'rgb(234, 226, 205)',
1552 height: this.twoPageH,
1554 borderLeft: '1px solid black',
1558 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1565 // XXXmang we're adding an extra pixel in the middle
1566 // prepareFlipRightToLeft()
1567 //______________________________________________________________________________
1568 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1570 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1572 this.prefetchImg(nextL);
1573 this.prefetchImg(nextR);
1575 var height = this.getPageHeight(nextR);
1576 var width = this.getPageWidth(nextR);
1577 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1578 var top = ($('#GBtwopageview').height() - this.twoPageH) >> 1;
1579 var scaledW = this.twoPageH*width/height;
1581 var gutter = middle + this.gutterOffsetForIndex(nextL);
1583 console.log('right to left to %d gutter is %d', nextL, gutter); // XXX
1585 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1586 $(this.prefetchedImgs[nextR]).css({
1587 position: 'absolute',
1590 backgroundColor: 'rgb(234, 226, 205)',
1591 height: this.twoPageH,
1592 width: scaledW+'px',
1593 borderLeft: '1px solid black',
1597 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1599 height = this.getPageHeight(nextL);
1600 width = this.getPageWidth(nextL);
1601 scaledW = this.twoPageH*width/height;
1603 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1604 $(this.prefetchedImgs[nextL]).css({
1605 position: 'absolute',
1606 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1608 backgroundColor: 'rgb(234, 226, 205)',
1609 height: this.twoPageH,
1611 borderRight: '1px solid black',
1615 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1621 // getNextLeafs() -- NOT RTL AWARE
1622 //______________________________________________________________________________
1623 // GnuBook.prototype.getNextLeafs = function(o) {
1624 // //TODO: we might have two left or two right leafs in a row (damaged book)
1625 // //For now, assume that leafs are contiguous.
1627 // //return [this.currentIndexL+2, this.currentIndexL+3];
1628 // o.L = this.currentIndexL+2;
1629 // o.R = this.currentIndexL+3;
1632 // getprevLeafs() -- NOT RTL AWARE
1633 //______________________________________________________________________________
1634 // GnuBook.prototype.getPrevLeafs = function(o) {
1635 // //TODO: we might have two left or two right leafs in a row (damaged book)
1636 // //For now, assume that leafs are contiguous.
1638 // //return [this.currentIndexL-2, this.currentIndexL-1];
1639 // o.L = this.currentIndexL-2;
1640 // o.R = this.currentIndexL-1;
1643 // pruneUnusedImgs()
1644 //______________________________________________________________________________
1645 GnuBook.prototype.pruneUnusedImgs = function() {
1646 //console.log('current: ' + this.currentIndexL + ' ' + this.currentIndexR);
1647 for (var key in this.prefetchedImgs) {
1648 //console.log('key is ' + key);
1649 if ((key != this.currentIndexL) && (key != this.currentIndexR)) {
1650 //console.log('removing key '+ key);
1651 $(this.prefetchedImgs[key]).remove();
1653 if ((key < this.currentIndexL-4) || (key > this.currentIndexR+4)) {
1654 //console.log('deleting key '+ key);
1655 delete this.prefetchedImgs[key];
1661 //______________________________________________________________________________
1662 GnuBook.prototype.prefetch = function() {
1664 var lim = this.currentIndexL-4;
1666 lim = Math.max(lim, 0);
1667 for (i = lim; i < this.currentIndexL; i++) {
1668 this.prefetchImg(i);
1671 if (this.numLeafs > (this.currentIndexR+1)) {
1672 lim = Math.min(this.currentIndexR+4, this.numLeafs-1);
1673 for (i=this.currentIndexR+1; i<=lim; i++) {
1674 this.prefetchImg(i);
1679 // getPageWidth2UP()
1680 //______________________________________________________________________________
1681 GnuBook.prototype.getPageWidth2UP = function(index) {
1682 var height = this.getPageHeight(index);
1683 var width = this.getPageWidth(index);
1684 return Math.floor(this.twoPageH*width/height);
1688 //______________________________________________________________________________
1689 GnuBook.prototype.search = function(term) {
1690 $('#GnuBookSearchScript').remove();
1691 var script = document.createElement("script");
1692 script.setAttribute('id', 'GnuBookSearchScript');
1693 script.setAttribute("type", "text/javascript");
1694 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1695 document.getElementsByTagName('head')[0].appendChild(script);
1696 $('#GnuBookSearchResults').html('Searching...');
1699 // GBSearchCallback()
1700 //______________________________________________________________________________
1701 GnuBook.prototype.GBSearchCallback = function(txt) {
1703 if (jQuery.browser.msie) {
1704 var dom=new ActiveXObject("Microsoft.XMLDOM");
1708 var parser = new DOMParser();
1709 var dom = parser.parseFromString(txt, "text/xml");
1712 $('#GnuBookSearchResults').empty();
1713 $('#GnuBookSearchResults').append('<ul>');
1715 for (var key in this.searchResults) {
1716 if (null != this.searchResults[key].div) {
1717 $(this.searchResults[key].div).remove();
1719 delete this.searchResults[key];
1722 var pages = dom.getElementsByTagName('PAGE');
1724 if (0 == pages.length) {
1725 // $$$ it would be nice to echo the (sanitized) search result here
1726 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1728 for (var i = 0; i < pages.length; i++){
1729 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1732 var re = new RegExp (/_(\d{4})/);
1733 var reMatch = re.exec(pages[i].getAttribute('file'));
1734 var index = parseInt(reMatch[1], 10);
1735 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1737 var children = pages[i].childNodes;
1739 for (var j=0; j<children.length; j++) {
1740 //console.log(j + ' - ' + children[j].nodeName);
1741 //console.log(children[j].firstChild.nodeValue);
1742 if ('CONTEXT' == children[j].nodeName) {
1743 context += children[j].firstChild.nodeValue;
1744 } else if ('WORD' == children[j].nodeName) {
1745 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1747 var index = this.leafNumToIndex(index);
1748 if (null != index) {
1749 //coordinates are [left, bottom, right, top, [baseline]]
1750 //we'll skip baseline for now...
1751 var coords = children[j].getAttribute('coords').split(',',4);
1752 if (4 == coords.length) {
1753 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1758 var pageName = this.getPageName(index);
1759 //TODO: remove hardcoded instance name
1760 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1763 $('#GnuBookSearchResults').append('</ul>');
1765 this.updateSearchHilites();
1768 // updateSearchHilites()
1769 //______________________________________________________________________________
1770 GnuBook.prototype.updateSearchHilites = function() {
1771 if (2 == this.mode) {
1772 this.updateSearchHilites2UP();
1774 this.updateSearchHilites1UP();
1778 // showSearchHilites1UP()
1779 //______________________________________________________________________________
1780 GnuBook.prototype.updateSearchHilites1UP = function() {
1782 for (var key in this.searchResults) {
1784 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1785 var result = this.searchResults[key];
1786 if(null == result.div) {
1787 result.div = document.createElement('div');
1788 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1789 //console.log('appending ' + key);
1792 width: (result.r-result.l)/this.reduce + 'px',
1793 height: (result.b-result.t)/this.reduce + 'px',
1794 left: (result.l)/this.reduce + 'px',
1795 top: (result.t)/this.reduce +'px'
1799 //console.log(key + ' not displayed');
1800 this.searchResults[key].div=null;
1805 // showSearchHilites2UP()
1806 //______________________________________________________________________________
1807 GnuBook.prototype.updateSearchHilites2UP = function() {
1809 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1811 for (var key in this.searchResults) {
1812 key = parseInt(key, 10);
1813 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
1814 var result = this.searchResults[key];
1815 if(null == result.div) {
1816 result.div = document.createElement('div');
1817 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
1818 //console.log('appending ' + key);
1821 var height = this.getPageHeight(key);
1822 var width = this.getPageWidth(key)
1823 var reduce = this.twoPageH/height;
1824 var scaledW = parseInt(width*reduce);
1826 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
1828 if ('L' == this.getPageSide(key)) {
1829 var pageL = gutter-scaledW;
1833 var pageT = ($('#GBtwopagview').height() - this.twoPageH) >> 1;
1836 width: (result.r-result.l)*reduce + 'px',
1837 height: (result.b-result.t)*reduce + 'px',
1838 left: pageL+(result.l)*reduce + 'px',
1839 top: pageT+(result.t)*reduce +'px'
1843 //console.log(key + ' not displayed');
1844 if (null != this.searchResults[key].div) {
1845 //console.log('removing ' + key);
1846 $(this.searchResults[key].div).remove();
1848 this.searchResults[key].div=null;
1853 // removeSearchHilites()
1854 //______________________________________________________________________________
1855 GnuBook.prototype.removeSearchHilites = function() {
1856 for (var key in this.searchResults) {
1857 if (null != this.searchResults[key].div) {
1858 $(this.searchResults[key].div).remove();
1859 this.searchResults[key].div=null;
1865 //______________________________________________________________________________
1866 GnuBook.prototype.showEmbedCode = function() {
1867 if (null != this.embedPopup) { // check if already showing
1871 this.embedPopup = document.createElement("div");
1872 $(this.embedPopup).css({
1873 position: 'absolute',
1875 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
1878 border: "3px double #999999",
1880 backgroundColor: "#fff"
1881 }).appendTo('#GnuBook');
1883 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1884 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>';
1885 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
1886 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1888 this.embedPopup.innerHTML = htmlStr;
1889 $(this.embedPopup).find('input').bind('click', function() {
1895 //______________________________________________________________________________
1896 GnuBook.prototype.autoToggle = function() {
1898 var bComingFrom1up = false;
1899 if (2 != this.mode) {
1900 bComingFrom1up = true;
1905 if (null == this.autoTimer) {
1906 this.flipSpeed = 2000;
1908 // $$$ Draw events currently cause layout problems when they occur during animation.
1909 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1910 // we workaround for now by not triggering immediate animation in that case.
1911 // See https://bugs.launchpad.net/gnubook/+bug/328327
1912 if (('rl' == this.pageProgression) && bComingFrom1up) {
1913 // don't flip immediately -- wait until timer fires
1916 this.flipFwdToIndex();
1919 $('#GBtoolbar .play').hide();
1920 $('#GBtoolbar .pause').show();
1921 this.autoTimer=setInterval(function(){
1922 if (self.animating) {return;}
1924 if (Math.max(self.currentIndexL, self.currentIndexR) >= self.lastDisplayableIndex()) {
1925 self.flipBackToIndex(1); // $$$ really what we want?
1927 self.flipFwdToIndex();
1936 //______________________________________________________________________________
1937 GnuBook.prototype.autoStop = function() {
1938 if (null != this.autoTimer) {
1939 clearInterval(this.autoTimer);
1940 this.flipSpeed = 'fast';
1941 $('#GBtoolbar .pause').hide();
1942 $('#GBtoolbar .play').show();
1943 this.autoTimer = null;
1947 // keyboardNavigationIsDisabled(event)
1948 // - returns true if keyboard navigation should be disabled for the event
1949 //______________________________________________________________________________
1950 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
1951 if (event.target.tagName == "INPUT") {
1957 // gutterOffsetForIndex
1958 //______________________________________________________________________________
1960 // Returns the gutter offset for the spread containing the given index.
1961 // This function supports RTL
1962 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
1964 // $$$ incorporate zooming
1966 // To find the offset of the gutter from the middle we calculate our percentage distance
1967 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
1968 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPageEdgeW);
1970 // But then again for RTL it's the opposite
1971 if ('rl' == this.pageProgression) {
1979 //______________________________________________________________________________
1980 // Returns the width of the leaf edge div for the page with index given
1981 GnuBook.prototype.leafEdgeWidth = function(pindex) {
1982 // $$$ could there be single pixel rounding errors for L vs R?
1983 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
1984 return parseInt( (pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1986 return parseInt( (1 - pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1990 // jumpIndexForLeftEdgePageX
1991 //______________________________________________________________________________
1992 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
1993 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
1994 if ('rl' != this.pageProgression) {
1995 // LTR - flipping backward
1996 var jumpIndex = this.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1998 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
1999 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.currentIndexL - 2);
2003 var jumpIndex = this.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2004 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.currentIndexL + 2, this.lastDisplayableIndex());
2009 // jumpIndexForRightEdgePageX
2010 //______________________________________________________________________________
2011 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2012 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2013 if ('rl' != this.pageProgression) {
2015 var jumpIndex = this.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2016 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.currentIndexR + 2, this.lastDisplayableIndex());
2019 var jumpIndex = this.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2020 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.currentIndexR - 2);
2025 GnuBook.prototype.initToolbar = function(mode, ui) {
2027 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2028 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2029 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2030 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2031 + " <span class='label'>Zoom: <span id='GBzoom'>"+100/this.reduce+"</span>%</span>"
2032 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2033 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2034 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2037 if (ui == "embed") {
2038 $("#GnuBook a.logo").attr("target","_blank");
2041 // $$$ turn this into a member variable
2042 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2044 // We build in mode 2
2045 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2046 + "<button class='GBicon rollover embed' />"
2047 + "<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>"
2048 + "<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>"
2049 + "<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>"
2050 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2052 this.bindToolbarNavHandlers(jToolbar);
2054 // Setup tooltips -- later we could load these from a file for i18n
2055 var titles = { '.logo': 'Go to Archive.org',
2056 '.zoom_in': 'Zoom in',
2057 '.zoom_out': 'Zoom out',
2058 '.one_page_mode': 'One-page view',
2059 '.two_page_mode': 'Two-page view',
2060 '.embed': 'Embed bookreader',
2061 '.book_left': 'Flip left',
2062 '.book_right': 'Flip right',
2063 '.book_up': 'Page up',
2064 '.book_down': 'Page down',
2067 '.book_top': 'First page',
2068 '.book_bottom': 'Last page'
2070 if ('rl' == this.pageProgression) {
2071 titles['.book_leftmost'] = 'Last page';
2072 titles['.book_rightmost'] = 'First page';
2074 titles['.book_leftmost'] = 'First page';
2075 titles['.book_rightmost'] = 'Last page';
2078 for (var icon in titles) {
2079 jToolbar.find(icon).attr('title', titles[icon]);
2082 // Hide mode buttons and autoplay if 2up is not available
2083 // $$$ if we end up with more than two modes we should show the applicable buttons
2084 if ( !this.canSwitchToMode(this.constMode2up) ) {
2085 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2088 // Switch to requested mode -- binds other click handlers
2089 this.switchToolbarMode(mode);
2094 // switchToolbarMode
2095 //______________________________________________________________________________
2096 // Update the toolbar for the given mode (changes navigation buttons)
2097 // $$$ we should soon split the toolbar out into its own module
2098 GnuBook.prototype.switchToolbarMode = function(mode) {
2101 $('#GBtoolbar .GBtoolbarmode2').hide();
2102 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2105 $('#GBtoolbar .GBtoolbarmode1').hide();
2106 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2110 // bindToolbarNavHandlers
2111 //______________________________________________________________________________
2112 // Binds the toolbar handlers
2113 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2115 jToolbar.find('.book_left').bind('click', function(e) {
2120 jToolbar.find('.book_right').bind('click', function(e) {
2125 jToolbar.find('.book_up').bind('click', function(e) {
2130 jToolbar.find('.book_down').bind('click', function(e) {
2135 jToolbar.find('.embed').bind('click', function(e) {
2140 jToolbar.find('.play').bind('click', function(e) {
2145 jToolbar.find('.pause').bind('click', function(e) {
2150 jToolbar.find('.book_top').bind('click', function(e) {
2155 jToolbar.find('.book_bottom').bind('click', function(e) {
2160 jToolbar.find('.book_leftmost').bind('click', function(e) {
2165 jToolbar.find('.book_rightmost').bind('click', function(e) {
2171 // firstDisplayableIndex
2172 //______________________________________________________________________________
2173 // Returns the index of the first visible page, dependent on the mode.
2174 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2175 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2176 GnuBook.prototype.firstDisplayableIndex = function() {
2177 if (this.mode == 0) {
2180 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2184 // lastDisplayableIndex
2185 //______________________________________________________________________________
2186 // Returns the index of the last visible page, dependent on the mode.
2187 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2188 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2189 GnuBook.prototype.lastDisplayableIndex = function() {
2190 if (this.mode == 2) {
2191 if (this.lastDisplayableIndex2up === null) {
2192 // Calculate and cache
2193 var candidate = this.numLeafs - 1;
2194 for ( ; candidate >= 0; candidate--) {
2195 var spreadIndices = this.getSpreadIndices(candidate);
2196 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2200 this.lastDisplayableIndex2up = candidate;
2202 return this.lastDisplayableIndex2up;
2204 return this.numLeafs - 1;
2208 // shortTitle(maximumCharacters)
2210 // Returns a shortened version of the title with the maximum number of characters
2211 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2212 if (this.bookTitle.length < maximumCharacters) {
2213 return this.bookTitle;
2216 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2223 // Parameter related functions
2225 // updateFromParams(params)
2227 // Update ourselves from the params object.
2229 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2230 GnuBook.prototype.updateFromParams = function(params) {
2231 if ('undefined' != typeof(params.mode)) {
2232 this.switchMode(params.mode);
2235 // $$$ process /search
2236 // $$$ process /zoom
2238 // We only respect page if index is not set
2239 if ('undefined' != typeof(params.index)) {
2240 if (params.index != this.currentIndex()) {
2241 this.jumpToIndex(params.index);
2243 } else if ('undefined' != typeof(params.page)) {
2244 // $$$ this assumes page numbers are unique
2245 if (params.page != this.getPageNum(this.currentIndex())) {
2246 this.jumpToPage(params.page);
2250 // $$$ process /region
2251 // $$$ process /highlight
2254 // paramsFromFragment(urlFragment)
2256 // Returns a object with configuration parametes from a URL fragment.
2258 // E.g paramsFromFragment(window.location.hash)
2259 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2260 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2264 // For convenience we allow an initial # character (as from window.location.hash)
2265 // but don't require it
2266 if (urlFragment.substr(0,1) == '#') {
2267 urlFragment = urlFragment.substr(1);
2270 // Simple #nn syntax
2271 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2272 if ( !isNaN(oldStyleLeafNum) ) {
2273 params.index = oldStyleLeafNum;
2275 // Done processing if using old-style syntax
2279 // Split into key-value pairs
2280 var urlArray = urlFragment.split('/');
2282 for (var i = 0; i < urlArray.length; i += 2) {
2283 urlHash[urlArray[i]] = urlArray[i+1];
2287 if ('1up' == urlHash['mode']) {
2288 params.mode = this.constMode1up;
2289 } else if ('2up' == urlHash['mode']) {
2290 params.mode = this.constMode2up;
2294 if ('undefined' != typeof(urlHash['page'])) {
2295 // page was set -- may not be int
2296 params.page = urlHash['page'];
2299 // $$$ process /region
2300 // $$$ process /search
2301 // $$$ process /highlight
2306 // paramsFromCurrent()
2308 // Create a params object from the current parameters.
2309 GnuBook.prototype.paramsFromCurrent = function() {
2313 var pageNum = this.getPageNum(this.currentIndex());
2314 if ((pageNum === 0) || pageNum) {
2315 params.page = pageNum;
2318 params.index = this.currentIndex();
2319 params.mode = this.mode;
2328 // fragmentFromParams(params)
2330 // Create a fragment string from the params object.
2331 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2332 GnuBook.prototype.fragmentFromParams = function(params) {
2333 var separator = '/';
2337 if ('undefined' != typeof(params.page)) {
2338 fragments.push('page', params.page);
2340 // Don't have page numbering -- use index instead
2341 fragments.push('page', 'n' + params.index);
2349 if ('undefined' != typeof(params.mode)) {
2350 if (params.mode == this.constMode1up) {
2351 fragments.push('mode', '1up');
2352 } else if (params.mode == this.constMode2up) {
2353 fragments.push('mode', '2up');
2355 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2359 return fragments.join(separator);
2362 // getPageIndex(pageNum)
2364 // Returns the *highest* index the given page number, or undefined
2365 GnuBook.prototype.getPageIndex = function(pageNum) {
2366 var pageIndices = this.getPageIndices(pageNum);
2368 if (pageIndices.length > 0) {
2369 return pageIndices[pageIndices.length - 1];
2375 // getPageIndices(pageNum)
2377 // Returns an array (possibly empty) of the indices with the given page number
2378 GnuBook.prototype.getPageIndices = function(pageNum) {
2381 // Check for special "nXX" page number
2382 if (pageNum.slice(0,1) == 'n') {
2384 var pageIntStr = pageNum.slice(1, pageNum.length);
2385 var pageIndex = parseInt(pageIntStr);
2386 indices.append(pageIndex);
2389 // Do nothing... will run through page names and see if one matches
2394 for (i=0; i<this.numLeafs; i++) {
2395 if (this.getPageNum(i) == pageNum) {
2403 // getPageName(index)
2405 // Returns the name of the page as it should be displayed in the user interface
2406 GnuBook.prototype.getPageName = function(index) {
2407 return 'Page ' + this.getPageNum(index);
2410 // updateLocationHash
2412 // Update the location hash from the current parameters. Call this instead of manually
2413 // using window.location.replace
2414 GnuBook.prototype.updateLocationHash = function() {
2415 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2416 window.location.replace(newHash);
2418 // This is the variable checked in the timer. Only user-generated changes
2419 // to the URL will trigger the event.
2420 this.oldLocationHash = newHash;
2423 // startLocationPolling
2425 // Starts polling of window.location to see hash fragment changes
2426 GnuBook.prototype.startLocationPolling = function() {
2427 var self = this; // remember who I am
2428 self.oldLocationHash = window.location.hash;
2430 if (this.locationPollId) {
2431 clearInterval(this.locationPollID);
2432 this.locationPollId = null;
2435 this.locationPollId = setInterval(function() {
2436 var newHash = window.location.hash;
2437 if (newHash != self.oldLocationHash) {
2438 if (newHash != self.oldUserHash) { // Only process new user hash once
2439 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2441 // Queue change if animating
2442 if (self.animating) {
2444 self.animationFinishedCallback = function() {
2445 self.updateFromParams(self.paramsFromFragment(newHash));
2447 } else { // update immediately
2448 self.updateFromParams(self.paramsFromFragment(newHash));
2450 self.oldUserHash = newHash;
2458 // Returns a URL for an embedded version of the current book
2459 GnuBook.prototype.getEmbedURL = function() {
2460 // We could generate a URL hash fragment here but for now we just leave at defaults
2461 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2466 // Returns the embed code HTML fragment suitable for copy and paste
2467 GnuBook.prototype.getEmbedCode = function() {
2468 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2473 // Returns true if we can switch to the requested mode
2474 GnuBook.prototype.canSwitchToMode = function(mode) {
2475 if (mode == this.constMode2up) {
2476 // check there are enough pages to display
2477 // $$$ this is a workaround for the mis-feature that we can't display
2478 // short books in 2up mode
2479 if (this.numLeafs < 6) {
2487 // Library functions
2489 clamp: function(value, min, max) {
2490 return Math.min(Math.max(value, min), max);