2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of GnuBook.
6 GnuBook is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Affero General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GnuBook is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Affero General Public License for more details.
16 You should have received a copy of the GNU Affero General Public License
17 along with GnuBook. If not, see <http://www.gnu.org/licenses/>.
19 The GnuBook source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init():
31 // You must also add a numLeafs property before calling init().
34 if (typeof(console) == 'undefined') {
35 console = { log: function(msg) { } };
41 this.mode = 1; //1 or 2
42 this.ui = 'full'; // UI mode
44 this.displayedIndices = [];
45 //this.indicesToDisplay = [];
47 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
50 this.animating = false;
52 this.autoTimer = null;
53 this.flipSpeed = 'fast';
55 this.twoPagePopUp = null;
56 this.leafEdgeTmp = null;
57 this.embedPopup = null;
59 this.searchResults = {};
61 this.firstIndex = null;
63 this.lastDisplayableIndex2up = null;
65 // We link to index.php to avoid redirect which breaks back button
66 this.logoURL = 'http://www.archive.org/index.php';
68 // Base URL for images
69 this.imagesBaseURL = '/bookreader/images/';
72 this.constMode1up = 1;
73 this.constMode2up = 2;
75 // Object to hold parameters related to 2up mode
77 coverInternalPadding: 10, // Width of cover
78 coverExternalPadding: 10, // Padding outside of cover
79 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
85 //______________________________________________________________________________
86 GnuBook.prototype.init = function() {
88 var startIndex = undefined;
90 // Find start index and mode if set in location hash
91 var params = this.paramsFromFragment(window.location.hash);
93 if ('undefined' != typeof(params.index)) {
94 startIndex = params.index;
95 } else if ('undefined' != typeof(params.page)) {
96 startIndex = this.getPageIndex(params.page);
99 if ('undefined' == typeof(startIndex)) {
100 if ('undefined' != typeof(this.titleLeaf)) {
101 startIndex = this.leafNumToIndex(this.titleLeaf);
105 if ('undefined' == typeof(startIndex)) {
109 if ('undefined' != typeof(params.mode)) {
110 this.mode = params.mode;
113 // Set document title -- may have already been set in enclosing html for
114 // search engine visibility
115 document.title = this.shortTitle(50);
117 // Sanitize parameters
118 if ( !this.canSwitchToMode( this.mode ) ) {
119 this.mode = this.constMode1up;
122 $("#GnuBook").empty();
123 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
124 $("#GnuBook").append("<div id='GBcontainer'></div>");
125 $("#GBcontainer").append("<div id='GBpageview'></div>");
127 $("#GBcontainer").bind('scroll', this, function(e) {
131 this.setupKeyListeners();
132 this.startLocationPolling();
134 $(window).bind('resize', this, function(e) {
135 //console.log('resize!');
136 if (1 == e.data.mode) {
137 //console.log('centering 1page view');
138 e.data.centerPageView();
139 $('#GBpageview').empty()
140 e.data.displayedIndices = [];
141 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
144 //console.log('drawing 2 page view');
145 e.data.prepareTwoPageView();
149 $('.GBpagediv1up').bind('mousedown', this, function(e) {
150 //console.log('mousedown!');
153 if (1 == this.mode) {
154 this.resizePageView();
155 this.firstIndex = startIndex;
156 this.jumpToIndex(startIndex);
158 //this.resizePageView();
160 this.displayedIndices=[0];
161 this.firstIndex = startIndex;
162 this.displayedIndices = [this.firstIndex];
163 //console.log('titleLeaf: %d', this.titleLeaf);
164 //console.log('displayedIndices: %s', this.displayedIndices);
165 this.prepareTwoPageView();
166 //if (this.auto) this.nextPage();
169 // Enact other parts of initial params
170 this.updateFromParams(params);
173 GnuBook.prototype.setupKeyListeners = function() {
186 // We use document here instead of window to avoid a bug in jQuery on IE7
187 $(document).keydown(function(e) {
189 // Keyboard navigation
193 // In 1up mode page scrolling is handled by browser
194 if (2 == self.mode) {
200 if (2 == self.mode) {
211 if (self.keyboardNavigationIsDisabled(e)) {
214 if (2 == self.mode) {
219 if (self.keyboardNavigationIsDisabled(e)) {
222 if (2 == self.mode) {
231 //______________________________________________________________________________
232 GnuBook.prototype.drawLeafs = function() {
233 if (1 == this.mode) {
234 this.drawLeafsOnePage();
236 this.drawLeafsTwoPage();
240 // setDragHandler1up()
241 //______________________________________________________________________________
242 GnuBook.prototype.setDragHandler1up = function(div) {
243 div.dragging = false;
245 $(div).bind('mousedown', function(e) {
246 //console.log('mousedown at ' + e.pageY);
248 this.dragging = true;
249 this.prevMouseX = e.pageX;
250 this.prevMouseY = e.pageY;
252 var startX = e.pageX;
253 var startY = e.pageY;
254 var startTop = $('#GBcontainer').attr('scrollTop');
255 var startLeft = $('#GBcontainer').attr('scrollLeft');
260 $(div).bind('mousemove', function(ee) {
261 //console.log('mousemove ' + startY);
263 var offsetX = ee.pageX - this.prevMouseX;
264 var offsetY = ee.pageY - this.prevMouseY;
267 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
268 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
271 this.prevMouseX = ee.pageX;
272 this.prevMouseY = ee.pageY;
277 $(div).bind('mouseup', function(ee) {
278 //console.log('mouseup');
280 this.dragging = false;
284 $(div).bind('mouseleave', function(e) {
285 //console.log('mouseleave');
287 //$(this).unbind('mousemove mouseup');
288 this.dragging = false;
293 // drawLeafsOnePage()
294 //______________________________________________________________________________
295 GnuBook.prototype.drawLeafsOnePage = function() {
296 //alert('drawing leafs!');
300 var scrollTop = $('#GBcontainer').attr('scrollTop');
301 var scrollBottom = scrollTop + $('#GBcontainer').height();
302 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
304 var indicesToDisplay = [];
309 for (i=0; i<this.numLeafs; i++) {
310 var height = parseInt(this.getPageHeight(i)/this.reduce);
312 leafBottom += height;
313 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
314 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
315 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
316 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
317 if (topInView | bottomInView | middleInView) {
318 //console.log('displayed: ' + this.displayedIndices);
319 //console.log('to display: ' + i);
320 indicesToDisplay.push(i);
322 leafTop += height +10;
326 var firstIndexToDraw = indicesToDisplay[0];
327 this.firstIndex = firstIndexToDraw;
329 // Update hash, but only if we're currently displaying a leaf
330 // Hack that fixes #365790
331 if (this.displayedIndices.length > 0) {
332 this.updateLocationHash();
335 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
337 indicesToDisplay.unshift(firstIndexToDraw);
340 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
341 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
342 indicesToDisplay.push(lastIndexToDraw+1);
347 for (i=0; i<firstIndexToDraw; i++) {
348 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
351 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
352 var viewWidth = $('#GBcontainer').attr('scrollWidth');
355 for (i=0; i<indicesToDisplay.length; i++) {
356 var index = indicesToDisplay[i];
357 var height = parseInt(this.getPageHeight(index)/this.reduce);
359 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
360 var width = parseInt(this.getPageWidth(index)/this.reduce);
361 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
362 var div = document.createElement("div");
363 div.className = 'GBpagediv1up';
364 div.id = 'pagediv'+index;
365 div.style.position = "absolute";
366 $(div).css('top', leafTop + 'px');
367 var left = (viewWidth-width)>>1;
368 if (left<0) left = 0;
369 $(div).css('left', left+'px');
370 $(div).css('width', width+'px');
371 $(div).css('height', height+'px');
372 //$(div).text('loading...');
374 this.setDragHandler1up(div);
376 $('#GBpageview').append(div);
378 var img = document.createElement("img");
379 img.src = this.getPageURI(index);
380 $(img).css('width', width+'px');
381 $(img).css('height', height+'px');
385 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
388 leafTop += height +10;
392 for (i=0; i<this.displayedIndices.length; i++) {
393 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
394 var index = this.displayedIndices[i];
395 //console.log('Removing leaf ' + index);
396 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
397 $('#pagediv'+index).remove();
399 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
403 this.displayedIndices = indicesToDisplay.slice();
404 this.updateSearchHilites();
406 if (null != this.getPageNum(firstIndexToDraw)) {
407 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
409 $("#GBpagenum").val('');
412 this.updateToolbarZoom(this.reduce);
416 // drawLeafsTwoPage()
417 //______________________________________________________________________________
418 GnuBook.prototype.drawLeafsTwoPage = function() {
419 console.log('drawing two leafs!'); // XXX
421 var scrollTop = $('#GBtwopageview').attr('scrollTop');
422 var scrollBottom = scrollTop + $('#GBtwopageview').height();
424 console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.twoPage.currentIndexL); // XXX
426 var indexL = this.twoPage.currentIndexL;
427 var heightL = this.getPageHeight(indexL);
428 var widthL = this.getPageWidth(indexL);
430 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
431 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
432 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
433 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
434 //console.log(leafEdgeWidthL);
436 var middle = this.twoPage.middle; // $$$ getter instead?
437 var top = this.twoPageTop();
438 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
440 // $$$ should get getwidth2up?
441 //var scaledWL = parseInt(this.twoPage.height*widthL/heightL);
442 var scaledWL = this.getPageWidth2UP(indexL);
443 var gutter = this.twoPageGutter();
445 this.prefetchImg(indexL);
446 $(this.prefetchedImgs[indexL]).css({
447 position: 'absolute',
448 left: gutter-scaledWL+'px',
451 backgroundColor: 'rgb(234, 226, 205)',
452 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
453 width: scaledWL + 'px',
454 borderRight: '1px solid black',
456 }).appendTo('#GBtwopageview');
459 var indexR = this.twoPage.currentIndexR;
460 var heightR = this.getPageHeight(indexR);
461 var widthR = this.getPageWidth(indexR);
463 // $$$ should use getwidth2up?
464 //var scaledWR = this.twoPage.height*widthR/heightR;
465 var scaledWR = this.getPageWidth2UP(indexR);
466 this.prefetchImg(indexR);
467 $(this.prefetchedImgs[indexR]).css({
468 position: 'absolute',
472 backgroundColor: 'rgb(234, 226, 205)',
473 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
474 width: scaledWR + 'px',
475 borderLeft: '1px solid black',
477 }).appendTo('#GBtwopageview');
480 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
481 this.setClickHandlers();
483 this.updatePageNumBox2UP();
484 this.updateToolbarZoom(this.reduce);
487 // updatePageNumBox2UP
488 //______________________________________________________________________________
489 GnuBook.prototype.updatePageNumBox2UP = function() {
490 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
491 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
493 $("#GBpagenum").val('');
495 this.updateLocationHash();
499 //______________________________________________________________________________
500 GnuBook.prototype.loadLeafs = function() {
504 if (null == this.timer) {
505 this.timer=setTimeout(function(){self.drawLeafs()},250);
507 clearTimeout(this.timer);
508 this.timer=setTimeout(function(){self.drawLeafs()},250);
514 // Pass 1 to zoom in, anything else to zoom out
515 //______________________________________________________________________________
516 GnuBook.prototype.zoom = function(direction) {
518 case this.constMode1up:
519 return this.zoom1up(direction);
520 case this.constMode2up:
521 return this.zoom2up(direction);
526 //______________________________________________________________________________
527 GnuBook.prototype.zoom1up = function(dir) {
528 if (2 == this.mode) { //can only zoom in 1-page mode
533 // $$$ with flexible zoom we could "snap" to /2 page reductions
534 // for better scaling
536 if (this.reduce <= 0.5) return;
537 this.reduce*=0.5; //zoom in
539 if (this.reduce >= 8) return;
540 this.reduce*=2; //zoom out
543 this.resizePageView();
545 $('#GBpageview').empty()
546 this.displayedIndices = [];
549 this.updateToolbarZoom(this.reduce);
553 //______________________________________________________________________________
554 GnuBook.prototype.resizePageView = function() {
557 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
558 var viewWidth = $('#GBcontainer').attr('clientWidth');
560 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
561 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
562 var oldPageViewHeight = $('#GBpageview').height();
563 var oldPageViewWidth = $('#GBpageview').width();
565 var oldCenterY = this.centerY1up();
566 var oldCenterX = this.centerX1up();
568 if (0 != oldPageViewHeight) {
569 var scrollRatio = oldCenterY / oldPageViewHeight;
574 for (i=0; i<this.numLeafs; i++) {
575 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
576 var width = parseInt(this.getPageWidth(i)/this.reduce);
577 if (width>viewWidth) viewWidth=width;
579 $('#GBpageview').height(viewHeight);
580 $('#GBpageview').width(viewWidth);
582 var newCenterY = scrollRatio*viewHeight;
583 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
584 $('#GBcontainer').attr('scrollTop', newTop);
586 // We use clientWidth here to avoid miscalculating due to scroll bar
587 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
588 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
589 newLeft = Math.max(newLeft, 0);
590 $('#GBcontainer').attr('scrollLeft', newLeft);
591 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
593 //this.centerPageView();
599 //______________________________________________________________________________
600 // Returns the current offset of the viewport center in scaled document coordinates.
601 GnuBook.prototype.centerX1up = function() {
603 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
604 centerX = $('#GBpageview').width();
606 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
608 centerX = Math.floor(centerX);
613 //______________________________________________________________________________
614 // Returns the current offset of the viewport center in scaled document coordinates.
615 GnuBook.prototype.centerY1up = function() {
616 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
617 return Math.floor(centerY);
621 //______________________________________________________________________________
622 GnuBook.prototype.centerPageView = function() {
624 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
625 var clientWidth = $('#GBcontainer').attr('clientWidth');
626 //console.log('sW='+scrollWidth+' cW='+clientWidth);
627 if (scrollWidth > clientWidth) {
628 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
633 // zoom2up(direction)
634 //______________________________________________________________________________
635 GnuBook.prototype.zoom2up = function(direction) {
636 // $$$ this is where we can e.g. snap to %2 sizes
637 if (0 == direction) { // autofit mode
638 this.twoPage.autofit = true;;
639 } else if (1 == direction) {
640 if (this.reduce <= 0.5) return;
641 this.reduce*=0.5; //zoom in
642 this.twoPage.autofit = false;
644 if (this.reduce >= 8) return;
645 this.reduce *= 2; // zoom out
646 this.twoPage.autofit = false;
649 this.prepareTwoPageView();
653 //______________________________________________________________________________
654 // Attempts to jump to page. Returns true if page could be found, false otherwise.
655 GnuBook.prototype.jumpToPage = function(pageNum) {
657 var pageIndex = this.getPageIndex(pageNum);
659 if ('undefined' != typeof(pageIndex)) {
662 this.jumpToIndex(pageIndex);
663 $('#GBcontainer').attr('scrollTop', leafTop);
672 //______________________________________________________________________________
673 GnuBook.prototype.jumpToIndex = function(index) {
675 if (2 == this.mode) {
678 // By checking against min/max we do nothing if requested index
680 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
681 this.flipBackToIndex(index);
682 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
683 this.flipFwdToIndex(index);
690 for (i=0; i<index; i++) {
691 h = parseInt(this.getPageHeight(i)/this.reduce);
692 leafTop += h + this.padding;
694 //$('#GBcontainer').attr('scrollTop', leafTop);
695 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
702 //______________________________________________________________________________
703 GnuBook.prototype.switchMode = function(mode) {
705 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
707 if (mode == this.mode) return;
709 if (!this.canSwitchToMode(mode)) {
714 this.removeSearchHilites();
718 this.switchToolbarMode(mode);
721 this.prepareOnePageView();
723 this.prepareTwoPageView();
728 //prepareOnePageView()
729 //______________________________________________________________________________
730 GnuBook.prototype.prepareOnePageView = function() {
732 // var startLeaf = this.displayedIndices[0];
733 var startLeaf = this.currentIndex();
735 $('#GBcontainer').empty();
736 $('#GBcontainer').css({
741 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
743 this.resizePageView();
745 this.jumpToIndex(startLeaf);
746 this.displayedIndices = [];
748 this.drawLeafsOnePage();
750 // Bind mouse handlers
751 // Disable mouse click to avoid selected/highlighted page images - bug 354239
752 gbPageView.bind('mousedown', function(e) {
755 // Special hack for IE7
756 gbPageView[0].onselectstart = function(e) { return false; };
759 // prepareTwoPageView()
760 //______________________________________________________________________________
761 // Some decisions about two page view:
763 // Both pages will be displayed at the same height, even if they were different physical/scanned
764 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
765 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
766 // aspect ratio to determine the height.
768 // The two page view div is resized to keep the middle of the book in the middle of the div
769 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
770 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
771 GnuBook.prototype.prepareTwoPageView = function() {
772 $('#GBcontainer').empty();
773 $('#GBcontainer').css('overflow', 'auto');
775 // Add the two page view
776 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
777 // Explicitly set sizes the same
778 // $$$ calculate first then set
779 $('#GBtwopageview').css( {
780 height: $('#GBcontainer').height(),
781 width: $('#GBcontainer').width(),
785 // We want to display two facing pages. We may be missing
786 // one side of the spread because it is the first/last leaf,
787 // foldouts, missing pages, etc
789 //var targetLeaf = this.displayedIndices[0];
790 var targetLeaf = this.firstIndex;
792 if (targetLeaf < this.firstDisplayableIndex()) {
793 targetLeaf = this.firstDisplayableIndex();
796 if (targetLeaf > this.lastDisplayableIndex()) {
797 targetLeaf = this.lastDisplayableIndex();
800 this.twoPage.currentIndexL = null;
801 this.twoPage.currentIndexR = null;
802 this.pruneUnusedImgs();
804 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
805 this.twoPage.currentIndexL = currentSpreadIndices[0];
806 this.twoPage.currentIndexR = currentSpreadIndices[1];
807 this.firstIndex = this.twoPage.currentIndexL;
809 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height, and twoPage.ratio
811 $('#GBtwopageview').width(this.twoPage.totalWidth).height(this.twoPage.totalHeight);
813 this.twoPageDiv = document.createElement('div');
814 $(this.twoPageDiv).attr('id', 'GBbookcover').css({
815 border: '1px solid rgb(68, 25, 17)',
816 width: this.twoPage.bookCoverDivWidth + 'px',
817 height: this.twoPage.bookCoverDivHeight+'px',
818 visibility: 'visible',
819 position: 'absolute',
820 backgroundColor: '#663929',
821 left: this.twoPage.bookCoverDivLeft + 'px',
822 top: this.twoPage.bookCoverDivTop+'px',
823 MozBorderRadiusTopleft: '7px',
824 MozBorderRadiusTopright: '7px',
825 MozBorderRadiusBottomright: '7px',
826 MozBorderRadiusBottomleft: '7px'
827 }).appendTo('#GBtwopageview');
829 this.leafEdgeR = document.createElement('div');
830 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
831 $(this.leafEdgeR).css({
832 borderStyle: 'solid solid solid none',
833 borderColor: 'rgb(51, 51, 34)',
834 borderWidth: '1px 1px 1px 0px',
835 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
836 width: this.twoPage.leafEdgeWidthR + 'px',
837 height: this.twoPage.height-1 + 'px',
839 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
840 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
842 }).appendTo('#GBtwopageview');
844 this.leafEdgeL = document.createElement('div');
845 this.leafEdgeL.className = 'leafEdgeL';
846 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
847 borderStyle: 'solid none solid solid',
848 borderColor: 'rgb(51, 51, 34)',
849 borderWidth: '1px 0px 1px 1px',
850 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
851 width: this.twoPage.leafEdgeWidthL + 'px',
852 height: this.twoPage.height-1 + 'px',
853 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
854 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
856 }).appendTo('#GBtwopageview');
858 div = document.createElement('div');
859 $(div).attr('id', 'GBbookspine').css({
860 border: '1px solid rgb(68, 25, 17)',
861 width: this.twoPage.bookSpineDivWidth+'px',
862 height: this.twoPage.bookSpineDivHeight+'px',
863 position: 'absolute',
864 backgroundColor: 'rgb(68, 25, 17)',
865 left: this.twoPage.bookSpineDivLeft+'px',
866 top: this.twoPage.bookSpineDivTop+'px'
867 }).appendTo('#GBtwopageview');
869 this.prepareTwoPagePopUp();
871 this.displayedIndices = [];
873 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
874 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
876 this.drawLeafsTwoPage();
877 this.updateSearchHilites2UP();
878 this.updateToolbarZoom(this.reduce);
883 // prepareTwoPagePopUp()
885 // This function prepares the "View Page n" popup that shows while the mouse is
886 // over the left/right "stack of sheets" edges. It also binds the mouse
887 // events for these divs.
888 //______________________________________________________________________________
889 GnuBook.prototype.prepareTwoPagePopUp = function() {
891 this.twoPagePopUp = document.createElement('div');
892 $(this.twoPagePopUp).css({
893 border: '1px solid black',
895 position: 'absolute',
896 fontFamily: 'sans-serif',
899 backgroundColor: 'rgb(255, 255, 238)',
901 }).appendTo('#GBcontainer');
902 $(this.twoPagePopUp).hide();
904 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
905 $(e.data.twoPagePopUp).show();
908 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
909 $(e.data.twoPagePopUp).hide();
912 $(this.leafEdgeL).bind('click', this, function(e) {
914 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
915 e.data.jumpToIndex(jumpIndex);
918 $(this.leafEdgeR).bind('click', this, function(e) {
920 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
921 e.data.jumpToIndex(jumpIndex);
924 $(this.leafEdgeR).bind('mousemove', this, function(e) {
926 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
927 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
929 // $$$ TODO: Make sure popup is positioned so that it is in view
930 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
931 $(e.data.twoPagePopUp).css({
932 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
933 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
937 $(this.leafEdgeL).bind('mousemove', this, function(e) {
939 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
940 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
942 // $$$ TODO: Make sure popup is positioned so that it is in view
943 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
944 $(e.data.twoPagePopUp).css({
945 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
946 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
951 // calculateSpreadSize()
952 //______________________________________________________________________________
953 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
954 // this.twoPage.currentIndexR
955 // This function sets this.twoPage.height, twoPage.width, and twoPage.ratio
957 GnuBook.prototype.calculateSpreadSize = function() {
958 console.log('calculateSpreadSize ' + this.twoPage.currentIndexL); // XXX
960 // $$$ TODO Calculate the spread size based on the reduction factor. If we are using
961 // fit mode we recalculate the reduction factor based on the current page sizes
962 // and display size first.
964 var firstIndex = this.twoPage.currentIndexL;
965 var secondIndex = this.twoPage.currentIndexR;
966 //console.log('first page is ' + firstIndex);
969 if ( this.twoPage.autofit) {
970 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
972 // set based on reduction factor
973 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
976 this.twoPage.height = spreadSize.height;
977 this.twoPage.width = spreadSize.width;
978 this.twoPage.ratio = spreadSize.ratio;
979 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
981 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
982 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
983 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
984 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
986 // The width of the book cover div. The combined width of both pages, twice the width
987 // of the book cover internal padding (2*10) and the page edges
988 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
990 // The height of the book cover div
991 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
993 // Total height and width -- makes the spine middle centered
994 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
995 var largestWidthFromCenter = Math.max( (this.twoPage.scaledWL + leftGutterOffset), (this.twoPage.scaledWR - leftGutterOffset));
996 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
997 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
999 // We want to minimize the unused space in two-up mode (maximize the amount of page
1000 // shown). We give width to the leaf edges and these widths change (though the sum
1001 // of the two remains constant) as we flip through the book. With the book
1002 // cover centered and fixed in the GBcontainer div the page images will meet
1003 // at the "gutter" which is generally offset from the center.
1004 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1005 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1007 this.twoPage.bookCoverDivLeft = this.twoPage.coverExternalPadding; // $$$ Account for border?
1008 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding; // $$$ Account for border?
1010 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1011 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1012 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1015 this.reduce = spreadSize.reduce; // $$$ really set this here?
1018 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1021 // We check which page is closest to a "normal" page and use that to set the height
1022 // for both pages. This means that foldouts and other odd size pages will be displayed
1023 // smaller than the nominal zoom amount.
1024 var canon5Dratio = 1.5;
1027 height: this.getPageHeight(firstIndex),
1028 width: this.getPageWidth(firstIndex)
1032 height: this.getPageHeight(secondIndex),
1033 width: this.getPageWidth(secondIndex)
1036 var firstIndexRatio = first.height / first.width;
1037 var secondIndexRatio = second.height / second.width;
1038 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1040 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1041 ideal.ratio = firstIndexRatio;
1042 //console.log('using firstIndexRatio ' + ratio);
1044 ideal.ratio = secondIndexRatio;
1045 //console.log('using secondIndexRatio ' + ratio);
1048 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1049 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1050 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1052 ideal.width = ($('#GBcontainer').attr('clientWidth') - 30 - ideal.totalLeafEdgeWidth)>>1;
1053 ideal.height = $('#GBcontainer').height() - 30; // $$$ why - 30? book edge width?
1054 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
1056 if (ideal.height/ideal.ratio <= ideal.width) {
1058 ideal.width = parseInt(ideal.height/ideal.ratio);
1061 ideal.height = parseInt(ideal.width*ideal.ratio);
1064 // XXX check this logic with large spreads
1065 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1070 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1071 var spreadSize = {};
1072 // $$$ Scale this based on reduce?
1073 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1074 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1075 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1077 // $$$ this isn't quite right when the pages are different sizes
1078 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1079 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1080 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1081 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1082 spreadSize.reduce = reduce;
1085 console.log('spread size: ' + firstIndex + ',' + secondIndex + ',' + reduce);
1091 //______________________________________________________________________________
1092 // Returns the currently active index.
1093 GnuBook.prototype.currentIndex = function() {
1094 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1095 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1096 return this.firstIndex;
1098 throw 'currentIndex called for unimplemented mode ' + this.mode;
1103 //______________________________________________________________________________
1104 // Flip the right page over onto the left
1105 GnuBook.prototype.right = function() {
1106 if ('rl' != this.pageProgression) {
1116 //______________________________________________________________________________
1117 // Flip to the rightmost page
1118 GnuBook.prototype.rightmost = function() {
1119 if ('rl' != this.pageProgression) {
1127 //______________________________________________________________________________
1128 // Flip the left page over onto the right.
1129 GnuBook.prototype.left = function() {
1130 if ('rl' != this.pageProgression) {
1140 //______________________________________________________________________________
1141 // Flip to the leftmost page
1142 GnuBook.prototype.leftmost = function() {
1143 if ('rl' != this.pageProgression) {
1151 //______________________________________________________________________________
1152 GnuBook.prototype.next = function() {
1153 if (2 == this.mode) {
1155 this.flipFwdToIndex(null);
1157 if (this.firstIndex < this.lastDisplayableIndex()) {
1158 this.jumpToIndex(this.firstIndex+1);
1164 //______________________________________________________________________________
1165 GnuBook.prototype.prev = function() {
1166 if (2 == this.mode) {
1168 this.flipBackToIndex(null);
1170 if (this.firstIndex >= 1) {
1171 this.jumpToIndex(this.firstIndex-1);
1176 GnuBook.prototype.first = function() {
1177 if (2 == this.mode) {
1178 this.jumpToIndex(2);
1181 this.jumpToIndex(0);
1185 GnuBook.prototype.last = function() {
1186 if (2 == this.mode) {
1187 this.jumpToIndex(this.lastDisplayableIndex());
1190 this.jumpToIndex(this.lastDisplayableIndex());
1194 // flipBackToIndex()
1195 //______________________________________________________________________________
1196 // to flip back one spread, pass index=null
1197 GnuBook.prototype.flipBackToIndex = function(index) {
1198 if (1 == this.mode) return;
1200 var leftIndex = this.twoPage.currentIndexL;
1202 // $$$ Need to change this to be able to see first spread.
1203 // See https://bugs.launchpad.net/gnubook/+bug/296788
1204 if (leftIndex <= 2) return;
1205 if (this.animating) return;
1207 if (null != this.leafEdgeTmp) {
1208 alert('error: leafEdgeTmp should be null!');
1212 if (null == index) {
1213 index = leftIndex-2;
1215 //if (index<0) return;
1217 var previousIndices = this.getSpreadIndices(index);
1219 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1223 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1225 this.animating = true;
1227 if ('rl' != this.pageProgression) {
1228 // Assume LTR and we are going backward
1229 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1230 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1233 // RTL and going backward
1234 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1235 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1239 // flipLeftToRight()
1240 //______________________________________________________________________________
1241 // Flips the page on the left towards the page on the right
1242 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1244 var leftLeaf = this.twoPage.currentIndexL;
1246 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1247 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1248 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1250 var currWidthL = this.getPageWidth2UP(leftLeaf);
1251 var newWidthL = this.getPageWidth2UP(newIndexL);
1252 var newWidthR = this.getPageWidth2UP(newIndexR);
1254 var top = this.twoPageTop();
1255 var gutter = this.twoPageGutter();
1257 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1258 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1260 //animation strategy:
1261 // 0. remove search highlight, if any.
1262 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1263 // of the left leaf and where the user clicked in the leaf edge.
1264 // Note that if this function was triggered by left() and not a
1265 // mouse click, the width of leafEdgeTmp is very small (zero px).
1266 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1267 // leftLeaf to width=0.
1268 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1269 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1270 // its new full width.
1271 // 4. After step 3 is finished, do the following:
1272 // - remove leafEdgeTmp from the dom.
1273 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1274 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1275 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1276 // and width=newLeafEdgeWidthL.
1277 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1278 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1279 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1280 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1281 // - prefetch new adjacent leafs.
1282 // - set up click handlers for both new left and right leafs.
1283 // - redraw the search highlight.
1284 // - update the pagenum box and the url.
1287 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1289 this.leafEdgeTmp = document.createElement('div');
1290 $(this.leafEdgeTmp).css({
1291 borderStyle: 'solid none solid solid',
1292 borderColor: 'rgb(51, 51, 34)',
1293 borderWidth: '1px 0px 1px 1px',
1294 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1295 width: leafEdgeTmpW + 'px',
1296 height: this.twoPage.height-1 + 'px',
1297 left: leftEdgeTmpLeft + 'px',
1299 position: 'absolute',
1301 }).appendTo('#GBtwopageview');
1303 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1304 $(this.leafEdgeL).css({
1305 width: newLeafEdgeWidthL+'px',
1306 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1309 // Left gets the offset of the current left leaf from the document
1310 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1311 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1312 // XXX need to recalc
1313 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1314 // We change the left leaf to right positioning
1315 $(this.prefetchedImgs[leftLeaf]).css({
1320 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1322 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1324 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1325 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1329 this.removeSearchHilites();
1331 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1332 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1334 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1335 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1337 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1338 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1339 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1341 $(self.leafEdgeR).css({
1342 // Moves the right leaf edge
1343 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1344 left: gutter+newWidthR+'px'
1347 $(self.leafEdgeL).css({
1348 // Moves and resizes the left leaf edge
1349 width: newLeafEdgeWidthL+'px',
1350 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1354 $(self.twoPageDiv).css({
1355 // Resizes the brown border div
1356 width: newWidthL+newWidthR+self.twoPage.edgeWidth+20+'px',
1357 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1360 $(self.leafEdgeTmp).remove();
1361 self.leafEdgeTmp = null;
1363 self.twoPage.currentIndexL = newIndexL;
1364 self.twoPage.currentIndexR = newIndexR;
1365 self.firstIndex = self.twoPage.currentIndexL;
1366 self.displayedIndices = [newIndexL, newIndexR];
1367 self.setClickHandlers();
1368 self.pruneUnusedImgs();
1370 self.animating = false;
1372 self.updateSearchHilites2UP();
1373 self.updatePageNumBox2UP();
1375 if (self.animationFinishedCallback) {
1376 self.animationFinishedCallback();
1377 self.animationFinishedCallback = null;
1385 //______________________________________________________________________________
1386 // Whether we flip left or right is dependent on the page progression
1387 // to flip forward one spread, pass index=null
1388 GnuBook.prototype.flipFwdToIndex = function(index) {
1390 if (this.animating) return;
1392 if (null != this.leafEdgeTmp) {
1393 alert('error: leafEdgeTmp should be null!');
1397 if (null == index) {
1398 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1400 if (index > this.lastDisplayableIndex()) return;
1402 this.animating = true;
1404 var nextIndices = this.getSpreadIndices(index);
1406 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1408 if ('rl' != this.pageProgression) {
1409 // We did not specify RTL
1410 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1411 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1414 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1415 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1419 // flipRightToLeft(nextL, nextR, gutter)
1420 // $$$ better not to have to pass gutter in
1421 //______________________________________________________________________________
1422 // Flip from left to right and show the nextL and nextR indices on those sides
1423 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1424 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1425 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1426 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1427 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1429 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1431 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1433 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1435 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1436 var currGutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1439 console.log('R->L middle(' + middle +') currGutter(' + currGutter + ') gutter(' + gutter + ')');
1441 this.leafEdgeTmp = document.createElement('div');
1442 $(this.leafEdgeTmp).css({
1443 borderStyle: 'solid none solid solid',
1444 borderColor: 'rgb(51, 51, 34)',
1445 borderWidth: '1px 0px 1px 1px',
1446 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1447 width: leafEdgeTmpW + 'px',
1448 height: this.twoPage.height-1 + 'px',
1449 left: currGutter+scaledW+'px',
1451 position: 'absolute',
1453 }).appendTo('#GBtwopageview');
1455 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1456 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1458 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1459 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1460 var newWidthL = this.getPageWidth2UP(newIndexL);
1461 var newWidthR = this.getPageWidth2UP(newIndexR);
1463 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1465 var self = this; // closure-tastic!
1467 var speed = this.flipSpeed;
1469 this.removeSearchHilites();
1471 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1472 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1473 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1474 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1475 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1477 $(self.leafEdgeL).css({
1478 width: newLeafEdgeWidthL+'px',
1479 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1482 $(self.twoPageDiv).css({
1483 width: newWidthL+newWidthR+self.twoPage.edgeWidth+20+'px',
1484 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1487 $(self.leafEdgeTmp).remove();
1488 self.leafEdgeTmp = null;
1490 self.twoPage.currentIndexL = newIndexL;
1491 self.twoPage.currentIndexR = newIndexR;
1492 self.firstIndex = self.twoPage.currentIndexL;
1493 self.displayedIndices = [newIndexL, newIndexR];
1494 self.setClickHandlers();
1495 self.pruneUnusedImgs();
1497 self.animating = false;
1500 self.updateSearchHilites2UP();
1501 self.updatePageNumBox2UP();
1503 if (self.animationFinishedCallback) {
1504 self.animationFinishedCallback();
1505 self.animationFinishedCallback = null;
1512 //______________________________________________________________________________
1513 GnuBook.prototype.setClickHandlers = function() {
1515 // $$$ TODO don't set again if already set
1516 $(this.prefetchedImgs[this.twoPage.currentIndexL]).click(function() {
1521 $(this.prefetchedImgs[this.twoPage.currentIndexR]).click(function() {
1529 //______________________________________________________________________________
1530 GnuBook.prototype.prefetchImg = function(index) {
1531 if (undefined == this.prefetchedImgs[index]) {
1532 //console.log('prefetching ' + index);
1533 var img = document.createElement("img");
1534 img.src = this.getPageURI(index);
1535 this.prefetchedImgs[index] = img;
1540 // prepareFlipLeftToRight()
1542 //______________________________________________________________________________
1544 // Prepare to flip the left page towards the right. This corresponds to moving
1545 // backward when the page progression is left to right.
1546 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1548 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1550 this.prefetchImg(prevL);
1551 this.prefetchImg(prevR);
1553 var height = this.getPageHeight(prevL);
1554 var width = this.getPageWidth(prevL);
1555 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1556 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1557 var scaledW = this.twoPage.height*width/height;
1559 // The gutter is the dividing line between the left and right pages.
1560 // It is offset from the middle to create the illusion of thickness to the pages
1561 var gutter = middle + this.gutterOffsetForIndex(prevL);
1564 console.log(' gutter for ' + prevL + ' is ' + gutter);
1565 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1566 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1568 $(this.prefetchedImgs[prevL]).css({
1569 position: 'absolute',
1570 /*right: middle+'px',*/
1571 left: gutter-scaledW+'px',
1574 backgroundColor: 'rgb(234, 226, 205)',
1575 height: this.twoPage.height,
1576 width: scaledW+'px',
1577 borderRight: '1px solid black',
1581 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1583 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1585 $(this.prefetchedImgs[prevR]).css({
1586 position: 'absolute',
1590 backgroundColor: 'rgb(234, 226, 205)',
1591 height: this.twoPage.height,
1593 borderLeft: '1px solid black',
1597 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1604 // XXXmang we're adding an extra pixel in the middle
1605 // prepareFlipRightToLeft()
1606 //______________________________________________________________________________
1607 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1609 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1611 this.prefetchImg(nextL);
1612 this.prefetchImg(nextR);
1614 var height = this.getPageHeight(nextR);
1615 var width = this.getPageWidth(nextR);
1616 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1617 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1618 var scaledW = this.twoPage.height*width/height;
1620 var gutter = middle + this.gutterOffsetForIndex(nextL);
1622 console.log('right to left to %d gutter is %d', nextL, gutter); // XXX
1624 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1625 $(this.prefetchedImgs[nextR]).css({
1626 position: 'absolute',
1629 backgroundColor: 'rgb(234, 226, 205)',
1630 height: this.twoPage.height,
1631 width: scaledW+'px',
1632 borderLeft: '1px solid black',
1636 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1638 height = this.getPageHeight(nextL);
1639 width = this.getPageWidth(nextL);
1640 scaledW = this.twoPage.height*width/height;
1642 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1643 $(this.prefetchedImgs[nextL]).css({
1644 position: 'absolute',
1645 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1647 backgroundColor: 'rgb(234, 226, 205)',
1648 height: this.twoPage.height,
1650 borderRight: '1px solid black',
1654 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1660 // getNextLeafs() -- NOT RTL AWARE
1661 //______________________________________________________________________________
1662 // GnuBook.prototype.getNextLeafs = function(o) {
1663 // //TODO: we might have two left or two right leafs in a row (damaged book)
1664 // //For now, assume that leafs are contiguous.
1666 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1667 // o.L = this.twoPage.currentIndexL+2;
1668 // o.R = this.twoPage.currentIndexL+3;
1671 // getprevLeafs() -- NOT RTL AWARE
1672 //______________________________________________________________________________
1673 // GnuBook.prototype.getPrevLeafs = function(o) {
1674 // //TODO: we might have two left or two right leafs in a row (damaged book)
1675 // //For now, assume that leafs are contiguous.
1677 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1678 // o.L = this.twoPage.currentIndexL-2;
1679 // o.R = this.twoPage.currentIndexL-1;
1682 // pruneUnusedImgs()
1683 //______________________________________________________________________________
1684 GnuBook.prototype.pruneUnusedImgs = function() {
1685 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1686 for (var key in this.prefetchedImgs) {
1687 //console.log('key is ' + key);
1688 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1689 //console.log('removing key '+ key);
1690 $(this.prefetchedImgs[key]).remove();
1692 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1693 //console.log('deleting key '+ key);
1694 delete this.prefetchedImgs[key];
1700 //______________________________________________________________________________
1701 GnuBook.prototype.prefetch = function() {
1703 var lim = this.twoPage.currentIndexL-4;
1705 lim = Math.max(lim, 0);
1706 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1707 this.prefetchImg(i);
1710 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1711 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1712 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1713 this.prefetchImg(i);
1718 // getPageWidth2UP()
1719 //______________________________________________________________________________
1720 GnuBook.prototype.getPageWidth2UP = function(index) {
1721 // We return the width based on the dominant height
1722 var height = this.getPageHeight(index);
1723 var width = this.getPageWidth(index);
1724 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
1728 //______________________________________________________________________________
1729 GnuBook.prototype.search = function(term) {
1730 $('#GnuBookSearchScript').remove();
1731 var script = document.createElement("script");
1732 script.setAttribute('id', 'GnuBookSearchScript');
1733 script.setAttribute("type", "text/javascript");
1734 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1735 document.getElementsByTagName('head')[0].appendChild(script);
1736 $('#GnuBookSearchResults').html('Searching...');
1739 // GBSearchCallback()
1740 //______________________________________________________________________________
1741 GnuBook.prototype.GBSearchCallback = function(txt) {
1743 if (jQuery.browser.msie) {
1744 var dom=new ActiveXObject("Microsoft.XMLDOM");
1748 var parser = new DOMParser();
1749 var dom = parser.parseFromString(txt, "text/xml");
1752 $('#GnuBookSearchResults').empty();
1753 $('#GnuBookSearchResults').append('<ul>');
1755 for (var key in this.searchResults) {
1756 if (null != this.searchResults[key].div) {
1757 $(this.searchResults[key].div).remove();
1759 delete this.searchResults[key];
1762 var pages = dom.getElementsByTagName('PAGE');
1764 if (0 == pages.length) {
1765 // $$$ it would be nice to echo the (sanitized) search result here
1766 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1768 for (var i = 0; i < pages.length; i++){
1769 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1772 var re = new RegExp (/_(\d{4})/);
1773 var reMatch = re.exec(pages[i].getAttribute('file'));
1774 var index = parseInt(reMatch[1], 10);
1775 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1777 var children = pages[i].childNodes;
1779 for (var j=0; j<children.length; j++) {
1780 //console.log(j + ' - ' + children[j].nodeName);
1781 //console.log(children[j].firstChild.nodeValue);
1782 if ('CONTEXT' == children[j].nodeName) {
1783 context += children[j].firstChild.nodeValue;
1784 } else if ('WORD' == children[j].nodeName) {
1785 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1787 var index = this.leafNumToIndex(index);
1788 if (null != index) {
1789 //coordinates are [left, bottom, right, top, [baseline]]
1790 //we'll skip baseline for now...
1791 var coords = children[j].getAttribute('coords').split(',',4);
1792 if (4 == coords.length) {
1793 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1798 var pageName = this.getPageName(index);
1799 //TODO: remove hardcoded instance name
1800 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1803 $('#GnuBookSearchResults').append('</ul>');
1805 this.updateSearchHilites();
1808 // updateSearchHilites()
1809 //______________________________________________________________________________
1810 GnuBook.prototype.updateSearchHilites = function() {
1811 if (2 == this.mode) {
1812 this.updateSearchHilites2UP();
1814 this.updateSearchHilites1UP();
1818 // showSearchHilites1UP()
1819 //______________________________________________________________________________
1820 GnuBook.prototype.updateSearchHilites1UP = function() {
1822 for (var key in this.searchResults) {
1824 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1825 var result = this.searchResults[key];
1826 if(null == result.div) {
1827 result.div = document.createElement('div');
1828 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1829 //console.log('appending ' + key);
1832 width: (result.r-result.l)/this.reduce + 'px',
1833 height: (result.b-result.t)/this.reduce + 'px',
1834 left: (result.l)/this.reduce + 'px',
1835 top: (result.t)/this.reduce +'px'
1839 //console.log(key + ' not displayed');
1840 this.searchResults[key].div=null;
1845 // XXX move, clean up, use everywhere
1846 GnuBook.prototype.twoPageGutter = function() {
1847 var middle = ($('#GBtwopageview').width() >> 1);
1848 return middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1851 // XXX move, clean up, use everywhere
1852 GnuBook.prototype.twoPageTop = function() {
1853 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
1856 // showSearchHilites2UP()
1857 //______________________________________________________________________________
1858 GnuBook.prototype.updateSearchHilites2UP = function() {
1860 for (var key in this.searchResults) {
1861 key = parseInt(key, 10);
1862 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
1863 var result = this.searchResults[key];
1864 if(null == result.div) {
1865 result.div = document.createElement('div');
1866 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
1867 //console.log('appending ' + key);
1870 // We calculate the reduction factor for the specific page because it can be different
1871 // for each page in the spread
1872 var height = this.getPageHeight(key);
1873 var width = this.getPageWidth(key)
1874 var reduce = this.twoPage.height/height;
1875 var scaledW = parseInt(width*reduce);
1877 var gutter = this.twoPageGutter();
1879 if ('L' == this.getPageSide(key)) {
1880 pageL = gutter-scaledW;
1884 var pageT = this.twoPageTop();
1887 width: (result.r-result.l)*reduce + 'px',
1888 height: (result.b-result.t)*reduce + 'px',
1889 left: pageL+(result.l)*reduce + 'px',
1890 top: pageT+(result.t)*reduce +'px'
1894 //console.log(key + ' not displayed');
1895 if (null != this.searchResults[key].div) {
1896 //console.log('removing ' + key);
1897 $(this.searchResults[key].div).remove();
1899 this.searchResults[key].div=null;
1904 // removeSearchHilites()
1905 //______________________________________________________________________________
1906 GnuBook.prototype.removeSearchHilites = function() {
1907 for (var key in this.searchResults) {
1908 if (null != this.searchResults[key].div) {
1909 $(this.searchResults[key].div).remove();
1910 this.searchResults[key].div=null;
1916 //______________________________________________________________________________
1917 GnuBook.prototype.showEmbedCode = function() {
1918 if (null != this.embedPopup) { // check if already showing
1922 this.embedPopup = document.createElement("div");
1923 $(this.embedPopup).css({
1924 position: 'absolute',
1926 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
1929 border: "3px double #999999",
1931 backgroundColor: "#fff"
1932 }).appendTo('#GnuBook');
1934 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1935 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>';
1936 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
1937 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1939 this.embedPopup.innerHTML = htmlStr;
1940 $(this.embedPopup).find('input').bind('click', function() {
1946 //______________________________________________________________________________
1947 GnuBook.prototype.autoToggle = function() {
1949 var bComingFrom1up = false;
1950 if (2 != this.mode) {
1951 bComingFrom1up = true;
1956 if (null == this.autoTimer) {
1957 this.flipSpeed = 2000;
1959 // $$$ Draw events currently cause layout problems when they occur during animation.
1960 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1961 // we workaround for now by not triggering immediate animation in that case.
1962 // See https://bugs.launchpad.net/gnubook/+bug/328327
1963 if (('rl' == this.pageProgression) && bComingFrom1up) {
1964 // don't flip immediately -- wait until timer fires
1967 this.flipFwdToIndex();
1970 $('#GBtoolbar .play').hide();
1971 $('#GBtoolbar .pause').show();
1972 this.autoTimer=setInterval(function(){
1973 if (self.animating) {return;}
1975 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
1976 self.flipBackToIndex(1); // $$$ really what we want?
1978 self.flipFwdToIndex();
1987 //______________________________________________________________________________
1988 GnuBook.prototype.autoStop = function() {
1989 if (null != this.autoTimer) {
1990 clearInterval(this.autoTimer);
1991 this.flipSpeed = 'fast';
1992 $('#GBtoolbar .pause').hide();
1993 $('#GBtoolbar .play').show();
1994 this.autoTimer = null;
1998 // keyboardNavigationIsDisabled(event)
1999 // - returns true if keyboard navigation should be disabled for the event
2000 //______________________________________________________________________________
2001 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2002 if (event.target.tagName == "INPUT") {
2008 // gutterOffsetForIndex
2009 //______________________________________________________________________________
2011 // Returns the gutter offset for the spread containing the given index.
2012 // This function supports RTL
2013 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2015 // To find the offset of the gutter from the middle we calculate our percentage distance
2016 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2017 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2019 // But then again for RTL it's the opposite
2020 if ('rl' == this.pageProgression) {
2028 //______________________________________________________________________________
2029 // Returns the width of the leaf edge div for the page with index given
2030 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2031 // $$$ could there be single pixel rounding errors for L vs R?
2032 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2033 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2035 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2039 // jumpIndexForLeftEdgePageX
2040 //______________________________________________________________________________
2041 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2042 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2043 if ('rl' != this.pageProgression) {
2044 // LTR - flipping backward
2045 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2047 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2048 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2052 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2053 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2058 // jumpIndexForRightEdgePageX
2059 //______________________________________________________________________________
2060 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2061 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2062 if ('rl' != this.pageProgression) {
2064 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2065 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2068 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2069 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2074 GnuBook.prototype.initToolbar = function(mode, ui) {
2076 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2077 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2078 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2079 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2080 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span>%</span>"
2081 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2082 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2083 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2086 if (ui == "embed") {
2087 $("#GnuBook a.logo").attr("target","_blank");
2090 // $$$ turn this into a member variable
2091 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2093 // We build in mode 2
2094 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2095 + "<button class='GBicon rollover embed' />"
2096 + "<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>"
2097 + "<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>"
2098 + "<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>"
2099 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2101 this.bindToolbarNavHandlers(jToolbar);
2103 // Setup tooltips -- later we could load these from a file for i18n
2104 var titles = { '.logo': 'Go to Archive.org',
2105 '.zoom_in': 'Zoom in',
2106 '.zoom_out': 'Zoom out',
2107 '.one_page_mode': 'One-page view',
2108 '.two_page_mode': 'Two-page view',
2109 '.embed': 'Embed bookreader',
2110 '.book_left': 'Flip left',
2111 '.book_right': 'Flip right',
2112 '.book_up': 'Page up',
2113 '.book_down': 'Page down',
2116 '.book_top': 'First page',
2117 '.book_bottom': 'Last page'
2119 if ('rl' == this.pageProgression) {
2120 titles['.book_leftmost'] = 'Last page';
2121 titles['.book_rightmost'] = 'First page';
2123 titles['.book_leftmost'] = 'First page';
2124 titles['.book_rightmost'] = 'Last page';
2127 for (var icon in titles) {
2128 jToolbar.find(icon).attr('title', titles[icon]);
2131 // Hide mode buttons and autoplay if 2up is not available
2132 // $$$ if we end up with more than two modes we should show the applicable buttons
2133 if ( !this.canSwitchToMode(this.constMode2up) ) {
2134 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2137 // Switch to requested mode -- binds other click handlers
2138 this.switchToolbarMode(mode);
2143 // switchToolbarMode
2144 //______________________________________________________________________________
2145 // Update the toolbar for the given mode (changes navigation buttons)
2146 // $$$ we should soon split the toolbar out into its own module
2147 GnuBook.prototype.switchToolbarMode = function(mode) {
2150 $('#GBtoolbar .GBtoolbarmode2').hide();
2151 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2154 $('#GBtoolbar .GBtoolbarmode1').hide();
2155 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2159 // bindToolbarNavHandlers
2160 //______________________________________________________________________________
2161 // Binds the toolbar handlers
2162 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2164 jToolbar.find('.book_left').bind('click', function(e) {
2169 jToolbar.find('.book_right').bind('click', function(e) {
2174 jToolbar.find('.book_up').bind('click', function(e) {
2179 jToolbar.find('.book_down').bind('click', function(e) {
2184 jToolbar.find('.embed').bind('click', function(e) {
2189 jToolbar.find('.play').bind('click', function(e) {
2194 jToolbar.find('.pause').bind('click', function(e) {
2199 jToolbar.find('.book_top').bind('click', function(e) {
2204 jToolbar.find('.book_bottom').bind('click', function(e) {
2209 jToolbar.find('.book_leftmost').bind('click', function(e) {
2214 jToolbar.find('.book_rightmost').bind('click', function(e) {
2220 // updateToolbarZoom(reduce)
2221 //______________________________________________________________________________
2222 // Update the displayed zoom factor based on reduction factor
2223 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2224 // $$$ TODO: Move toolbar to it's own object/plugin
2225 $('#GBzoom').text(parseInt(100/reduce));
2228 // firstDisplayableIndex
2229 //______________________________________________________________________________
2230 // Returns the index of the first visible page, dependent on the mode.
2231 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2232 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2233 GnuBook.prototype.firstDisplayableIndex = function() {
2234 if (this.mode == 0) {
2237 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2241 // lastDisplayableIndex
2242 //______________________________________________________________________________
2243 // Returns the index of the last visible page, dependent on the mode.
2244 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2245 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2246 GnuBook.prototype.lastDisplayableIndex = function() {
2247 if (this.mode == 2) {
2248 if (this.lastDisplayableIndex2up === null) {
2249 // Calculate and cache
2250 var candidate = this.numLeafs - 1;
2251 for ( ; candidate >= 0; candidate--) {
2252 var spreadIndices = this.getSpreadIndices(candidate);
2253 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2257 this.lastDisplayableIndex2up = candidate;
2259 return this.lastDisplayableIndex2up;
2261 return this.numLeafs - 1;
2265 // shortTitle(maximumCharacters)
2267 // Returns a shortened version of the title with the maximum number of characters
2268 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2269 if (this.bookTitle.length < maximumCharacters) {
2270 return this.bookTitle;
2273 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2280 // Parameter related functions
2282 // updateFromParams(params)
2284 // Update ourselves from the params object.
2286 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2287 GnuBook.prototype.updateFromParams = function(params) {
2288 if ('undefined' != typeof(params.mode)) {
2289 this.switchMode(params.mode);
2292 // $$$ process /search
2293 // $$$ process /zoom
2295 // We only respect page if index is not set
2296 if ('undefined' != typeof(params.index)) {
2297 if (params.index != this.currentIndex()) {
2298 this.jumpToIndex(params.index);
2300 } else if ('undefined' != typeof(params.page)) {
2301 // $$$ this assumes page numbers are unique
2302 if (params.page != this.getPageNum(this.currentIndex())) {
2303 this.jumpToPage(params.page);
2307 // $$$ process /region
2308 // $$$ process /highlight
2311 // paramsFromFragment(urlFragment)
2313 // Returns a object with configuration parametes from a URL fragment.
2315 // E.g paramsFromFragment(window.location.hash)
2316 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2317 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2321 // For convenience we allow an initial # character (as from window.location.hash)
2322 // but don't require it
2323 if (urlFragment.substr(0,1) == '#') {
2324 urlFragment = urlFragment.substr(1);
2327 // Simple #nn syntax
2328 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2329 if ( !isNaN(oldStyleLeafNum) ) {
2330 params.index = oldStyleLeafNum;
2332 // Done processing if using old-style syntax
2336 // Split into key-value pairs
2337 var urlArray = urlFragment.split('/');
2339 for (var i = 0; i < urlArray.length; i += 2) {
2340 urlHash[urlArray[i]] = urlArray[i+1];
2344 if ('1up' == urlHash['mode']) {
2345 params.mode = this.constMode1up;
2346 } else if ('2up' == urlHash['mode']) {
2347 params.mode = this.constMode2up;
2351 if ('undefined' != typeof(urlHash['page'])) {
2352 // page was set -- may not be int
2353 params.page = urlHash['page'];
2356 // $$$ process /region
2357 // $$$ process /search
2358 // $$$ process /highlight
2363 // paramsFromCurrent()
2365 // Create a params object from the current parameters.
2366 GnuBook.prototype.paramsFromCurrent = function() {
2370 var pageNum = this.getPageNum(this.currentIndex());
2371 if ((pageNum === 0) || pageNum) {
2372 params.page = pageNum;
2375 params.index = this.currentIndex();
2376 params.mode = this.mode;
2385 // fragmentFromParams(params)
2387 // Create a fragment string from the params object.
2388 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2389 GnuBook.prototype.fragmentFromParams = function(params) {
2390 var separator = '/';
2394 if ('undefined' != typeof(params.page)) {
2395 fragments.push('page', params.page);
2397 // Don't have page numbering -- use index instead
2398 fragments.push('page', 'n' + params.index);
2406 if ('undefined' != typeof(params.mode)) {
2407 if (params.mode == this.constMode1up) {
2408 fragments.push('mode', '1up');
2409 } else if (params.mode == this.constMode2up) {
2410 fragments.push('mode', '2up');
2412 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2416 return fragments.join(separator);
2419 // getPageIndex(pageNum)
2421 // Returns the *highest* index the given page number, or undefined
2422 GnuBook.prototype.getPageIndex = function(pageNum) {
2423 var pageIndices = this.getPageIndices(pageNum);
2425 if (pageIndices.length > 0) {
2426 return pageIndices[pageIndices.length - 1];
2432 // getPageIndices(pageNum)
2434 // Returns an array (possibly empty) of the indices with the given page number
2435 GnuBook.prototype.getPageIndices = function(pageNum) {
2438 // Check for special "nXX" page number
2439 if (pageNum.slice(0,1) == 'n') {
2441 var pageIntStr = pageNum.slice(1, pageNum.length);
2442 var pageIndex = parseInt(pageIntStr);
2443 indices.append(pageIndex);
2446 // Do nothing... will run through page names and see if one matches
2451 for (i=0; i<this.numLeafs; i++) {
2452 if (this.getPageNum(i) == pageNum) {
2460 // getPageName(index)
2462 // Returns the name of the page as it should be displayed in the user interface
2463 GnuBook.prototype.getPageName = function(index) {
2464 return 'Page ' + this.getPageNum(index);
2467 // updateLocationHash
2469 // Update the location hash from the current parameters. Call this instead of manually
2470 // using window.location.replace
2471 GnuBook.prototype.updateLocationHash = function() {
2472 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2473 window.location.replace(newHash);
2475 // This is the variable checked in the timer. Only user-generated changes
2476 // to the URL will trigger the event.
2477 this.oldLocationHash = newHash;
2480 // startLocationPolling
2482 // Starts polling of window.location to see hash fragment changes
2483 GnuBook.prototype.startLocationPolling = function() {
2484 var self = this; // remember who I am
2485 self.oldLocationHash = window.location.hash;
2487 if (this.locationPollId) {
2488 clearInterval(this.locationPollID);
2489 this.locationPollId = null;
2492 this.locationPollId = setInterval(function() {
2493 var newHash = window.location.hash;
2494 if (newHash != self.oldLocationHash) {
2495 if (newHash != self.oldUserHash) { // Only process new user hash once
2496 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2498 // Queue change if animating
2499 if (self.animating) {
2501 self.animationFinishedCallback = function() {
2502 self.updateFromParams(self.paramsFromFragment(newHash));
2504 } else { // update immediately
2505 self.updateFromParams(self.paramsFromFragment(newHash));
2507 self.oldUserHash = newHash;
2515 // Returns a URL for an embedded version of the current book
2516 GnuBook.prototype.getEmbedURL = function() {
2517 // We could generate a URL hash fragment here but for now we just leave at defaults
2518 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2523 // Returns the embed code HTML fragment suitable for copy and paste
2524 GnuBook.prototype.getEmbedCode = function() {
2525 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2530 // Returns true if we can switch to the requested mode
2531 GnuBook.prototype.canSwitchToMode = function(mode) {
2532 if (mode == this.constMode2up) {
2533 // check there are enough pages to display
2534 // $$$ this is a workaround for the mis-feature that we can't display
2535 // short books in 2up mode
2536 if (this.numLeafs < 6) {
2544 // Library functions
2546 clamp: function(value, min, max) {
2547 return Math.min(Math.max(value, min), max);