2 Copyright(c)2008 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.69 $ $Date: 2009-04-01 22:00: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().
36 this.mode = 1; //1 or 2
38 this.displayedLeafs = [];
39 //this.leafsToDisplay = [];
41 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to leafNum
44 this.animating = false;
46 this.autoTimer = null;
47 this.flipSpeed = 'fast';
49 this.twoPagePopUp = null;
50 this.leafEdgeTmp = null;
51 this.embedPopup = null;
53 this.searchResults = {};
55 this.firstIndex = null;
57 this.lastDisplayableIndex2up = null;
59 // We link to index.php to avoid redirect which breaks back button
60 this.logoURL = 'http://www.archive.org/index.php';
65 //______________________________________________________________________________
66 GnuBook.prototype.init = function() {
67 var startLeaf = window.location.hash;
68 //console.log("startLeaf from location.hash: %s", startLeaf);
69 if ('' == startLeaf) {
71 startLeaf = "#" + this.leafNumToIndex(this.titleLeaf);
75 // Ideally this would be set in the HTML/PHP for better search engine visibility but
76 // it takes some time to locate the item and retrieve the metadata
77 document.title = this.shortTitle(50);
79 $("#GnuBook").empty();
80 this.initToolbar(this.mode); // Build inside of toolbar div
81 $("#GnuBook").append("<div id='GBcontainer'></div>");
82 $("#GBcontainer").append("<div id='GBpageview'></div>");
84 $("#GBcontainer").bind('scroll', this, function(e) {
88 this.setupKeyListeners();
90 $(window).bind('resize', this, function(e) {
91 //console.log('resize!');
92 if (1 == e.data.mode) {
93 //console.log('centering 1page view');
94 e.data.centerPageView();
95 $('#GBpageview').empty()
96 e.data.displayedLeafs = [];
97 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
100 //console.log('drawing 2 page view');
101 e.data.prepareTwoPageView();
105 $('.GBpagediv1up').bind('mousedown', this, function(e) {
106 //console.log('mousedown!');
109 if (1 == this.mode) {
110 this.resizePageView();
112 if ('' != startLeaf) { // Jump to the leaf specified in the URL
113 this.jumpToIndex(parseInt(startLeaf.substr(1)));
114 //console.log('jump to ' + parseInt(startLeaf.substr(1)));
117 //this.resizePageView();
119 this.displayedLeafs=[0];
120 if ('' != startLeaf) {
121 this.displayedLeafs = [parseInt(startLeaf.substr(1))];
123 //console.log('titleLeaf: %d', this.titleLeaf);
124 //console.log('displayedLeafs: %s', this.displayedLeafs);
125 this.prepareTwoPageView();
126 //if (this.auto) this.nextPage();
130 GnuBook.prototype.setupKeyListeners = function() {
143 // We use document here instead of window to avoid a bug in jQuery on IE7
144 $(document).keydown(function(e) {
146 // Keyboard navigation
150 // In 1up mode page scrolling is handled by browser
151 if (2 == self.mode) {
157 if (2 == self.mode) {
168 if (self.keyboardNavigationIsDisabled(e)) {
171 if (2 == self.mode) {
176 if (self.keyboardNavigationIsDisabled(e)) {
179 if (2 == self.mode) {
188 //______________________________________________________________________________
189 GnuBook.prototype.drawLeafs = function() {
190 if (1 == this.mode) {
191 this.drawLeafsOnePage();
193 this.drawLeafsTwoPage();
197 // setDragHandler1up()
198 //______________________________________________________________________________
199 GnuBook.prototype.setDragHandler1up = function(div) {
200 div.dragging = false;
202 $(div).bind('mousedown', function(e) {
203 //console.log('mousedown at ' + e.pageY);
205 this.dragging = true;
206 this.prevMouseX = e.pageX;
207 this.prevMouseY = e.pageY;
209 var startX = e.pageX;
210 var startY = e.pageY;
211 var startTop = $('#GBcontainer').attr('scrollTop');
212 var startLeft = $('#GBcontainer').attr('scrollLeft');
217 $(div).bind('mousemove', function(ee) {
218 //console.log('mousemove ' + startY);
220 var offsetX = ee.pageX - this.prevMouseX;
221 var offsetY = ee.pageY - this.prevMouseY;
224 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
225 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
228 this.prevMouseX = ee.pageX;
229 this.prevMouseY = ee.pageY;
234 $(div).bind('mouseup', function(ee) {
235 //console.log('mouseup');
237 this.dragging = false;
241 $(div).bind('mouseleave', function(e) {
242 //console.log('mouseleave');
244 //$(this).unbind('mousemove mouseup');
245 this.dragging = false;
250 // drawLeafsOnePage()
251 //______________________________________________________________________________
252 GnuBook.prototype.drawLeafsOnePage = function() {
253 //alert('drawing leafs!');
257 var scrollTop = $('#GBcontainer').attr('scrollTop');
258 var scrollBottom = scrollTop + $('#GBcontainer').height();
259 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
261 var leafsToDisplay = [];
266 for (i=0; i<this.numLeafs; i++) {
267 var height = parseInt(this.getPageHeight(i)/this.reduce);
269 leafBottom += height;
270 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
271 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
272 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
273 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
274 if (topInView | bottomInView | middleInView) {
275 //console.log('to display: ' + i);
276 leafsToDisplay.push(i);
278 leafTop += height +10;
282 var firstLeafToDraw = leafsToDisplay[0];
283 window.location.replace('#' + firstLeafToDraw);
284 this.firstIndex = firstLeafToDraw;
286 if ((0 != firstLeafToDraw) && (1 < this.reduce)) {
288 leafsToDisplay.unshift(firstLeafToDraw);
291 var lastLeafToDraw = leafsToDisplay[leafsToDisplay.length-1];
292 if ( ((this.numLeafs-1) != lastLeafToDraw) && (1 < this.reduce) ) {
293 leafsToDisplay.push(lastLeafToDraw+1);
298 for (i=0; i<firstLeafToDraw; i++) {
299 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
302 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
303 var viewWidth = $('#GBcontainer').attr('scrollWidth');
306 for (i=0; i<leafsToDisplay.length; i++) {
307 var leafNum = leafsToDisplay[i];
308 var height = parseInt(this.getPageHeight(leafNum)/this.reduce);
310 if(-1 == jQuery.inArray(leafsToDisplay[i], this.displayedLeafs)) {
311 var width = parseInt(this.getPageWidth(leafNum)/this.reduce);
312 //console.log("displaying leaf " + leafsToDisplay[i] + ' leafTop=' +leafTop);
313 var div = document.createElement("div");
314 div.className = 'GBpagediv1up';
315 div.id = 'pagediv'+leafNum;
316 div.style.position = "absolute";
317 $(div).css('top', leafTop + 'px');
318 var left = (viewWidth-width)>>1;
319 if (left<0) left = 0;
320 $(div).css('left', left+'px');
321 $(div).css('width', width+'px');
322 $(div).css('height', height+'px');
323 //$(div).text('loading...');
325 this.setDragHandler1up(div);
327 $('#GBpageview').append(div);
329 var img = document.createElement("img");
330 img.src = this.getPageURI(leafNum);
331 $(img).css('width', width+'px');
332 $(img).css('height', height+'px');
336 //console.log("not displaying " + leafsToDisplay[i] + ' score=' + jQuery.inArray(leafsToDisplay[i], this.displayedLeafs));
339 leafTop += height +10;
343 for (i=0; i<this.displayedLeafs.length; i++) {
344 if (-1 == jQuery.inArray(this.displayedLeafs[i], leafsToDisplay)) {
345 var leafNum = this.displayedLeafs[i];
346 //console.log('Removing leaf ' + leafNum);
347 //console.log('id='+'#pagediv'+leafNum+ ' top = ' +$('#pagediv'+leafNum).css('top'));
348 $('#pagediv'+leafNum).remove();
350 //console.log('NOT Removing leaf ' + this.displayedLeafs[i]);
354 this.displayedLeafs = leafsToDisplay.slice();
355 this.updateSearchHilites();
357 if (null != this.getPageNum(firstLeafToDraw)) {
358 $("#GBpagenum").val(this.getPageNum(firstLeafToDraw));
360 $("#GBpagenum").val('');
364 // drawLeafsTwoPage()
365 //______________________________________________________________________________
366 GnuBook.prototype.drawLeafsTwoPage = function() {
367 //alert('drawing two leafs!');
369 var scrollTop = $('#GBcontainer').attr('scrollTop');
370 var scrollBottom = scrollTop + $('#GBcontainer').height();
372 //console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.currentLeafL);
374 var leafNum = this.currentLeafL;
375 var height = this.getPageHeight(leafNum);
376 var width = this.getPageWidth(leafNum);
377 var handSide= this.getPageSide(leafNum);
379 var leafEdgeWidthL = this.leafEdgeWidth(leafNum);
380 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
381 var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
382 var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
383 //console.log(leafEdgeWidthL);
385 var middle = ($('#GBcontainer').width() >> 1);
386 var left = middle - this.twoPageW;
387 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
389 var scaledW = parseInt(this.twoPageH*width/height);
390 left = 10+leafEdgeWidthL;
391 //var right = left+scaledW;
392 var right = $(this.twoPageDiv).width()-11-$(this.leafEdgeL).width()-scaledW;
394 var gutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
396 this.prefetchImg(leafNum);
397 $(this.prefetchedImgs[leafNum]).css({
398 position: 'absolute',
399 /*right: gutter+'px',*/
400 left: gutter-scaledW+'px',
403 backgroundColor: 'rgb(234, 226, 205)',
404 height: this.twoPageH +'px',
405 width: scaledW + 'px',
406 borderRight: '1px solid black',
408 }).appendTo('#GBcontainer');
409 //$('#GBcontainer').append(this.prefetchedImgs[leafNum]);
412 var leafNum = this.currentLeafR;
413 var height = this.getPageHeight(leafNum);
414 var width = this.getPageWidth(leafNum);
415 // var left = ($('#GBcontainer').width() >> 1);
418 var scaledW = this.twoPageH*width/height;
419 this.prefetchImg(leafNum);
420 $(this.prefetchedImgs[leafNum]).css({
421 position: 'absolute',
425 backgroundColor: 'rgb(234, 226, 205)',
426 height: this.twoPageH + 'px',
427 width: scaledW + 'px',
428 borderLeft: '1px solid black',
430 }).appendTo('#GBcontainer');
431 //$('#GBcontainer').append(this.prefetchedImgs[leafNum]);
434 this.displayedLeafs = [this.currentLeafL, this.currentLeafR];
435 this.setClickHandlers();
437 this.updatePageNumBox2UP();
440 // updatePageNumBox2UP
441 //______________________________________________________________________________
442 GnuBook.prototype.updatePageNumBox2UP = function() {
443 if (null != this.getPageNum(this.currentLeafL)) {
444 $("#GBpagenum").val(this.getPageNum(this.currentLeafL));
446 $("#GBpagenum").val('');
448 window.location.replace('#' + this.currentLeafL);
452 //______________________________________________________________________________
453 GnuBook.prototype.loadLeafs = function() {
457 if (null == this.timer) {
458 this.timer=setTimeout(function(){self.drawLeafs()},250);
460 clearTimeout(this.timer);
461 this.timer=setTimeout(function(){self.drawLeafs()},250);
467 //______________________________________________________________________________
468 GnuBook.prototype.zoom1up = function(dir) {
469 if (2 == this.mode) { //can only zoom in 1-page mode
475 if (this.reduce <= 0.5) return;
476 this.reduce*=0.5; //zoom in
478 if (this.reduce >= 8) return;
479 this.reduce*=2; //zoom out
482 this.resizePageView();
484 $('#GBpageview').empty()
485 this.displayedLeafs = [];
488 $('#GBzoom').text(100/this.reduce);
493 //______________________________________________________________________________
494 GnuBook.prototype.resizePageView = function() {
497 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
498 var viewWidth = $('#GBcontainer').attr('clientWidth');
500 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
501 var oldViewHeight = $('#GBpageview').height();
502 if (0 != oldViewHeight) {
503 var scrollRatio = oldScrollTop / oldViewHeight;
508 for (i=0; i<this.numLeafs; i++) {
509 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
510 var width = parseInt(this.getPageWidth(i)/this.reduce);
511 if (width>viewWidth) viewWidth=width;
513 $('#GBpageview').height(viewHeight);
514 $('#GBpageview').width(viewWidth);
516 $('#GBcontainer').attr('scrollTop', Math.floor(scrollRatio*viewHeight));
518 this.centerPageView();
524 //______________________________________________________________________________
525 GnuBook.prototype.centerPageView = function() {
527 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
528 var clientWidth = $('#GBcontainer').attr('clientWidth');
529 //console.log('sW='+scrollWidth+' cW='+clientWidth);
530 if (scrollWidth > clientWidth) {
531 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
537 //______________________________________________________________________________
538 GnuBook.prototype.jumpToPage = function(pageNum) {
541 var foundPage = false;
542 var foundLeaf = null;
543 for (i=0; i<this.numLeafs; i++) {
544 if (this.getPageNum(i) == pageNum) {
554 this.jumpToIndex(foundLeaf);
555 $('#GBcontainer').attr('scrollTop', leafTop);
557 alert('Page not found. This book might not have pageNumbers in scandata.');
562 //______________________________________________________________________________
563 GnuBook.prototype.jumpToIndex = function(index) {
565 if (2 == this.mode) {
568 // By checking against min/max we do nothing if requested index
570 if (index < Math.min(this.currentLeafL, this.currentLeafR)) {
571 this.flipBackToIndex(index);
572 } else if (index > Math.max(this.currentLeafL, this.currentLeafR)) {
573 this.flipFwdToIndex(index);
580 for (i=0; i<index; i++) {
581 h = parseInt(this.getPageHeight(i)/this.reduce);
582 leafTop += h + this.padding;
584 //$('#GBcontainer').attr('scrollTop', leafTop);
585 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
592 //______________________________________________________________________________
593 GnuBook.prototype.switchMode = function(mode) {
595 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
597 if (mode == this.mode) return;
600 this.removeSearchHilites();
604 this.switchToolbarMode(mode);
607 this.prepareOnePageView();
609 this.prepareTwoPageView();
614 //prepareOnePageView()
615 //______________________________________________________________________________
616 GnuBook.prototype.prepareOnePageView = function() {
618 var startLeaf = this.displayedLeafs[0];
620 $('#GBcontainer').empty();
621 $('#GBcontainer').css({
626 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
627 this.resizePageView();
628 this.jumpToIndex(startLeaf);
629 this.displayedLeafs = [];
630 this.drawLeafsOnePage();
631 $('#GBzoom').text(100/this.reduce);
633 // Bind mouse handlers
634 // Disable mouse click to avoid selected/highlighted page images - bug 354239
635 gbPageView.bind('mousedown', function(e) {
638 // Special hack for IE7
639 gbPageView[0].onselectstart = function(e) { return false; };
642 // prepareTwoPageView()
643 //______________________________________________________________________________
644 GnuBook.prototype.prepareTwoPageView = function() {
645 $('#GBcontainer').empty();
647 // We want to display two facing pages. We may be missing
648 // one side of the spread because it is the first/last leaf,
649 // foldouts, missing pages, etc
651 var targetLeaf = this.displayedLeafs[0];
653 if (targetLeaf < this.firstDisplayableIndex()) {
654 targetLeaf = this.firstDisplayableIndex();
657 if (targetLeaf > this.lastDisplayableIndex()) {
658 targetLeaf = this.lastDisplayableIndex();
661 this.currentLeafL = null;
662 this.currentLeafR = null;
663 this.pruneUnusedImgs();
665 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
666 this.currentLeafL = currentSpreadIndices[0];
667 this.currentLeafR = currentSpreadIndices[1];
669 this.calculateSpreadSize(); //sets this.twoPageW, twoPageH, and twoPageRatio
671 // We want to minimize the unused space in two-up mode (maximize the amount of page
672 // shown). We give width to the leaf edges and these widths change (though the sum
673 // of the two remains constant) as we flip through the book. With the book
674 // cover centered and fixed in the GBcontainer div the page images will meet
675 // at the "gutter" which is generally offset from the center.
676 var middle = ($('#GBcontainer').width() >> 1); // Middle of the GBcontainer div
677 //var gutter = middle+parseInt((2*this.currentLeafL - this.numLeafs)*this.twoPageEdgeW/this.numLeafs/2);
679 var gutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
681 var scaledWL = this.getPageWidth2UP(this.currentLeafL);
682 var scaledWR = this.getPageWidth2UP(this.currentLeafR);
683 var leafEdgeWidthL = this.leafEdgeWidth(this.currentLeafL);
684 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
686 //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
687 //var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
689 // The width of the book cover div. The combined width of both pages, twice the width
690 // of the book cover internal padding (2*10) and the page edges
691 var bookCoverDivWidth = scaledWL + scaledWR + 20 + this.twoPageEdgeW;
693 // The height of the book cover div
694 var bookCoverDivHeight = this.twoPageH+20;
696 //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
697 var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-10;
698 var bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
699 //console.log('bookCoverDivWidth='+bookCoverDivWidth+' bookCoverDivHeight='+bookCoverDivHeight+ ' bookCoverDivLeft='+bookCoverDivLeft+' bookCoverDivTop='+bookCoverDivTop);
701 this.twoPageDiv = document.createElement('div');
702 $(this.twoPageDiv).attr('id', 'book_div_1').css({
703 border: '1px solid rgb(68, 25, 17)',
704 width: bookCoverDivWidth + 'px',
705 height: bookCoverDivHeight+'px',
706 visibility: 'visible',
707 position: 'absolute',
708 backgroundColor: '#663929',
709 left: bookCoverDivLeft + 'px',
710 top: bookCoverDivTop+'px',
711 MozBorderRadiusTopleft: '7px',
712 MozBorderRadiusTopright: '7px',
713 MozBorderRadiusBottomright: '7px',
714 MozBorderRadiusBottomleft: '7px'
715 }).appendTo('#GBcontainer');
716 //$('#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;"/>');
719 var height = this.getPageHeight(this.currentLeafR);
720 var width = this.getPageWidth(this.currentLeafR);
721 var scaledW = this.twoPageH*width/height;
723 this.leafEdgeR = document.createElement('div');
724 this.leafEdgeR.className = 'leafEdgeR';
725 $(this.leafEdgeR).css({
726 borderStyle: 'solid solid solid none',
727 borderColor: 'rgb(51, 51, 34)',
728 borderWidth: '1px 1px 1px 0px',
729 background: 'transparent url(images/right_edges.png) repeat scroll 0% 0%',
730 width: leafEdgeWidthR + 'px',
731 height: this.twoPageH-1 + 'px',
733 left: gutter+scaledW+'px',
734 top: bookCoverDivTop+10+'px',
736 }).appendTo('#GBcontainer');
738 this.leafEdgeL = document.createElement('div');
739 this.leafEdgeL.className = 'leafEdgeL';
740 $(this.leafEdgeL).css({
741 borderStyle: 'solid none solid solid',
742 borderColor: 'rgb(51, 51, 34)',
743 borderWidth: '1px 0px 1px 1px',
744 background: 'transparent url(images/left_edges.png) repeat scroll 0% 0%',
745 width: leafEdgeWidthL + 'px',
746 height: this.twoPageH-1 + 'px',
747 left: bookCoverDivLeft+10+'px',
748 top: bookCoverDivTop+10+'px',
750 }).appendTo('#GBcontainer');
754 bookCoverDivWidth = 30;
755 bookCoverDivHeight = this.twoPageH+20;
756 bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
757 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
759 div = document.createElement('div');
760 $(div).attr('id', 'book_div_2').css({
761 border: '1px solid rgb(68, 25, 17)',
762 width: bookCoverDivWidth+'px',
763 height: bookCoverDivHeight+'px',
764 position: 'absolute',
765 backgroundColor: 'rgb(68, 25, 17)',
766 left: bookCoverDivLeft+'px',
767 top: bookCoverDivTop+'px'
768 }).appendTo('#GBcontainer');
769 //$('#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;"/>');
771 bookCoverDivWidth = this.twoPageW*2;
772 bookCoverDivHeight = this.twoPageH;
773 bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
774 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
777 this.prepareTwoPagePopUp();
779 this.displayedLeafs = [];
781 //this.leafsToDisplay=[firstLeaf, firstLeaf+1];
782 //console.log('leafsToDisplay: ' + this.leafsToDisplay[0] + ' ' + this.leafsToDisplay[1]);
784 this.drawLeafsTwoPage();
785 this.updateSearchHilites2UP();
788 $('#GBzoom').text((100*this.twoPageH/this.getPageHeight(this.currentLeafL)).toString().substr(0,4));
791 // prepareTwoPagePopUp()
793 // This function prepares the "View leaf n" popup that shows while the mouse is
794 // over the left/right "stack of sheets" edges. It also binds the mouse
795 // events for these divs.
796 //______________________________________________________________________________
797 GnuBook.prototype.prepareTwoPagePopUp = function() {
798 this.twoPagePopUp = document.createElement('div');
799 $(this.twoPagePopUp).css({
800 border: '1px solid black',
802 position: 'absolute',
803 fontFamily: 'sans-serif',
806 backgroundColor: 'rgb(255, 255, 238)',
808 }).appendTo('#GBcontainer');
809 $(this.twoPagePopUp).hide();
811 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
812 $(e.data.twoPagePopUp).show();
815 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
816 $(e.data.twoPagePopUp).hide();
819 $(this.leafEdgeL).bind('click', this, function(e) {
821 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
822 e.data.jumpToIndex(jumpIndex);
825 $(this.leafEdgeR).bind('click', this, function(e) {
827 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
828 e.data.jumpToIndex(jumpIndex);
831 $(this.leafEdgeR).bind('mousemove', this, function(e) {
833 var jumpLeaf = e.data.jumpIndexForRightEdgePageX(e.pageX);
834 $(e.data.twoPagePopUp).text('View Leaf '+jumpLeaf);
836 $(e.data.twoPagePopUp).css({
837 left: e.pageX +5+ 'px',
838 top: e.pageY-$('#GBcontainer').offset().top+ 'px'
842 $(this.leafEdgeL).bind('mousemove', this, function(e) {
844 var jumpLeaf = e.data.jumpIndexForLeftEdgePageX(e.pageX);
845 $(e.data.twoPagePopUp).text('View Leaf '+jumpLeaf);
847 $(e.data.twoPagePopUp).css({
848 left: e.pageX - $(e.data.twoPagePopUp).width() - 30 + 'px',
849 top: e.pageY-$('#GBcontainer').offset().top+ 'px'
854 // calculateSpreadSize()
855 //______________________________________________________________________________
856 // Calculates 2-page spread dimensions based on this.currentLeafL and
858 // This function sets this.twoPageH, twoPageW, and twoPageRatio
860 GnuBook.prototype.calculateSpreadSize = function() {
861 var firstLeaf = this.currentLeafL;
862 var secondLeaf = this.currentLeafR;
863 //console.log('first page is ' + firstLeaf);
865 var canon5Dratio = 1.5;
867 var firstLeafRatio = this.getPageHeight(firstLeaf) / this.getPageWidth(firstLeaf);
868 var secondLeafRatio = this.getPageHeight(secondLeaf) / this.getPageWidth(secondLeaf);
869 //console.log('firstLeafRatio = ' + firstLeafRatio + ' secondLeafRatio = ' + secondLeafRatio);
872 if (Math.abs(firstLeafRatio - canon5Dratio) < Math.abs(secondLeafRatio - canon5Dratio)) {
873 ratio = firstLeafRatio;
874 //console.log('using firstLeafRatio ' + ratio);
876 ratio = secondLeafRatio;
877 //console.log('using secondLeafRatio ' + ratio);
880 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
881 var maxLeafEdgeWidth = parseInt($('#GBcontainer').width() * 0.1);
882 totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
884 $('#GBcontainer').css('overflow', 'hidden');
886 var idealWidth = ($('#GBcontainer').width() - 30 - totalLeafEdgeWidth)>>1;
887 var idealHeight = $('#GBcontainer').height() - 30;
888 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
890 if (idealHeight/ratio <= idealWidth) {
892 idealWidth = parseInt(idealHeight/ratio);
895 idealHeight = parseInt(idealWidth*ratio);
898 this.twoPageH = idealHeight;
899 this.twoPageW = idealWidth;
900 this.twoPageRatio = ratio;
901 this.twoPageEdgeW = totalLeafEdgeWidth; // The combined width of both edges
906 //______________________________________________________________________________
907 // Flip the right page over onto the left
908 GnuBook.prototype.right = function() {
909 if ('rl' != this.pageProgression) {
919 //______________________________________________________________________________
920 // Flip the left page over onto the right.
921 GnuBook.prototype.left = function() {
922 if ('rl' != this.pageProgression) {
932 //______________________________________________________________________________
933 GnuBook.prototype.next = function() {
934 if (2 == this.mode) {
936 this.flipFwdToIndex(null);
938 if (this.firstIndex < this.lastDisplayableIndex()) {
939 this.jumpToIndex(this.firstIndex+1);
945 //______________________________________________________________________________
946 GnuBook.prototype.prev = function() {
947 if (2 == this.mode) {
949 this.flipBackToIndex(null);
951 if (this.firstIndex >= 1) {
952 this.jumpToIndex(this.firstIndex-1);
957 GnuBook.prototype.home = function() {
958 if (2 == this.mode) {
966 GnuBook.prototype.end = function() {
967 if (2 == this.mode) {
968 this.jumpToIndex(this.lastDisplayableIndex());
971 this.jumpToIndex(this.lastDisplayableIndex());
976 //______________________________________________________________________________
977 // to flip back one spread, pass index=null
978 GnuBook.prototype.flipBackToIndex = function(index) {
979 if (1 == this.mode) return;
981 var leftIndex = this.currentLeafL;
983 // $$$ Need to change this to be able to see first spread.
984 // See https://bugs.launchpad.net/gnubook/+bug/296788
985 if (leftIndex <= 2) return;
986 if (this.animating) return;
988 if (null != this.leafEdgeTmp) {
989 alert('error: leafEdgeTmp should be null!');
996 //if (index<0) return;
998 var previousIndices = this.getSpreadIndices(index);
1000 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1004 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1006 this.animating = true;
1008 if ('rl' != this.pageProgression) {
1009 // Assume LTR and we are going backward
1010 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1011 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1014 // RTL and going backward
1015 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1016 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1020 // flipLeftToRight()
1021 //______________________________________________________________________________
1022 // Flips the page on the left towards the page on the right
1023 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1025 var leftLeaf = this.currentLeafL;
1027 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentLeafL);
1028 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1029 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1031 var currWidthL = this.getPageWidth2UP(leftLeaf);
1032 var newWidthL = this.getPageWidth2UP(newIndexL);
1033 var newWidthR = this.getPageWidth2UP(newIndexR);
1035 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1037 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1038 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1040 //animation strategy:
1041 // 0. remove search highlight, if any.
1042 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1043 // of the left leaf and where the user clicked in the leaf edge.
1044 // Note that if this function was triggered by left() and not a
1045 // mouse click, the width of leafEdgeTmp is very small (zero px).
1046 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1047 // leftLeaf to width=0.
1048 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1049 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1050 // its new full width.
1051 // 4. After step 3 is finished, do the following:
1052 // - remove leafEdgeTmp from the dom.
1053 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1054 // and width=twoPageEdgeW-newLeafEdgeWidthL.
1055 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1056 // and width=newLeafEdgeWidthL.
1057 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1058 // and width=newWidthL+newWidthR+twoPageEdgeW+20
1059 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1060 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1061 // - prefetch new adjacent leafs.
1062 // - set up click handlers for both new left and right leafs.
1063 // - redraw the search highlight.
1064 // - update the pagenum box and the url.
1067 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1069 this.leafEdgeTmp = document.createElement('div');
1070 $(this.leafEdgeTmp).css({
1071 borderStyle: 'solid none solid solid',
1072 borderColor: 'rgb(51, 51, 34)',
1073 borderWidth: '1px 0px 1px 1px',
1074 background: 'transparent url(images/left_edges.png) repeat scroll 0% 0%',
1075 width: leafEdgeTmpW + 'px',
1076 height: this.twoPageH-1 + 'px',
1077 left: leftEdgeTmpLeft + 'px',
1079 position: 'absolute',
1081 }).appendTo('#GBcontainer');
1083 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1084 $(this.leafEdgeL).css({
1085 width: newLeafEdgeWidthL+'px',
1086 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1089 // Left gets the offset of the current left leaf from the document
1090 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1091 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1092 var right = $('#GBcontainer').width()-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBcontainer').offset().left-2+'px';
1093 // We change the left leaf to right positioning
1094 $(this.prefetchedImgs[leftLeaf]).css({
1099 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1101 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1103 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1104 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1108 this.removeSearchHilites();
1110 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1111 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1113 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1114 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1116 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1117 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1118 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1120 $(self.leafEdgeR).css({
1121 // Moves the right leaf edge
1122 width: self.twoPageEdgeW-newLeafEdgeWidthL+'px',
1123 left: gutter+newWidthR+'px'
1126 $(self.leafEdgeL).css({
1127 // Moves and resizes the left leaf edge
1128 width: newLeafEdgeWidthL+'px',
1129 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1133 $(self.twoPageDiv).css({
1134 // Resizes the brown border div
1135 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1136 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1139 $(self.leafEdgeTmp).remove();
1140 self.leafEdgeTmp = null;
1142 self.currentLeafL = newIndexL;
1143 self.currentLeafR = newIndexR;
1144 self.displayedLeafs = [newIndexL, newIndexR];
1145 self.setClickHandlers();
1146 self.pruneUnusedImgs();
1148 self.animating = false;
1150 self.updateSearchHilites2UP();
1151 self.updatePageNumBox2UP();
1152 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1159 //______________________________________________________________________________
1160 // Whether we flip left or right is dependent on the page progression
1161 // to flip forward one spread, pass index=null
1162 GnuBook.prototype.flipFwdToIndex = function(index) {
1164 if (this.animating) return;
1166 if (null != this.leafEdgeTmp) {
1167 alert('error: leafEdgeTmp should be null!');
1171 if (null == index) {
1172 index = this.currentLeafR+2; // $$$ assumes indices are continuous
1174 if (index > this.lastDisplayableIndex()) return;
1176 this.animating = true;
1178 var nextIndices = this.getSpreadIndices(index);
1180 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1182 if ('rl' != this.pageProgression) {
1183 // We did not specify RTL
1184 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1185 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1188 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1189 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1193 // flipRightToLeft(nextL, nextR, gutter)
1194 // $$$ better not to have to pass gutter in
1195 //______________________________________________________________________________
1196 // Flip from left to right and show the nextL and nextR indices on those sides
1197 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1198 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentLeafL);
1199 var oldLeafEdgeWidthR = this.twoPageEdgeW-oldLeafEdgeWidthL;
1200 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1201 var newLeafEdgeWidthR = this.twoPageEdgeW-newLeafEdgeWidthL;
1203 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1205 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1207 var scaledW = this.getPageWidth2UP(this.currentLeafR);
1209 var middle = ($('#GBcontainer').width() >> 1);
1210 var currGutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
1212 this.leafEdgeTmp = document.createElement('div');
1213 $(this.leafEdgeTmp).css({
1214 borderStyle: 'solid none solid solid',
1215 borderColor: 'rgb(51, 51, 34)',
1216 borderWidth: '1px 0px 1px 1px',
1217 background: 'transparent url(images/left_edges.png) repeat scroll 0% 0%',
1218 width: leafEdgeTmpW + 'px',
1219 height: this.twoPageH-1 + 'px',
1220 left: currGutter+scaledW+'px',
1222 position: 'absolute',
1224 }).appendTo('#GBcontainer');
1226 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1227 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1229 var currWidthL = this.getPageWidth2UP(this.currentLeafL);
1230 var currWidthR = this.getPageWidth2UP(this.currentLeafR);
1231 var newWidthL = this.getPageWidth2UP(newIndexL);
1232 var newWidthR = this.getPageWidth2UP(newIndexR);
1234 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1236 var self = this; // closure-tastic!
1238 var speed = this.flipSpeed;
1240 this.removeSearchHilites();
1242 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1243 $(this.prefetchedImgs[this.currentLeafR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1244 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1245 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1246 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1248 $(self.leafEdgeL).css({
1249 width: newLeafEdgeWidthL+'px',
1250 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1253 $(self.twoPageDiv).css({
1254 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1255 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1258 $(self.leafEdgeTmp).remove();
1259 self.leafEdgeTmp = null;
1261 self.currentLeafL = newIndexL;
1262 self.currentLeafR = newIndexR;
1263 self.displayedLeafs = [newIndexL, newIndexR];
1264 self.setClickHandlers();
1265 self.pruneUnusedImgs();
1267 self.animating = false;
1269 self.updateSearchHilites2UP();
1270 self.updatePageNumBox2UP();
1271 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1277 //______________________________________________________________________________
1278 GnuBook.prototype.setClickHandlers = function() {
1280 $(this.prefetchedImgs[this.currentLeafL]).click(function() {
1285 $(this.prefetchedImgs[this.currentLeafR]).click(function() {
1293 //______________________________________________________________________________
1294 GnuBook.prototype.prefetchImg = function(leafNum) {
1295 if (undefined == this.prefetchedImgs[leafNum]) {
1296 //console.log('prefetching ' + leafNum);
1297 var img = document.createElement("img");
1298 img.src = this.getPageURI(leafNum);
1299 this.prefetchedImgs[leafNum] = img;
1304 // prepareFlipLeftToRight()
1306 //______________________________________________________________________________
1308 // Prepare to flip the left page towards the right. This corresponds to moving
1309 // backward when the page progression is left to right.
1310 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1312 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1314 this.prefetchImg(prevL);
1315 this.prefetchImg(prevR);
1317 var height = this.getPageHeight(prevL);
1318 var width = this.getPageWidth(prevL);
1319 var middle = ($('#GBcontainer').width() >> 1);
1320 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1321 var scaledW = this.twoPageH*width/height;
1323 // The gutter is the dividing line between the left and right pages.
1324 // It is offset from the middle to create the illusion of thickness to the pages
1325 var gutter = middle + this.gutterOffsetForIndex(prevL);
1327 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1328 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1329 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1331 $(this.prefetchedImgs[prevL]).css({
1332 position: 'absolute',
1333 /*right: middle+'px',*/
1334 left: gutter-scaledW+'px',
1337 backgroundColor: 'rgb(234, 226, 205)',
1338 height: this.twoPageH,
1339 width: scaledW+'px',
1340 borderRight: '1px solid black',
1344 $('#GBcontainer').append(this.prefetchedImgs[prevL]);
1346 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1348 $(this.prefetchedImgs[prevR]).css({
1349 position: 'absolute',
1353 backgroundColor: 'rgb(234, 226, 205)',
1354 height: this.twoPageH,
1356 borderLeft: '1px solid black',
1360 $('#GBcontainer').append(this.prefetchedImgs[prevR]);
1367 // prepareFlipRightToLeft()
1368 //______________________________________________________________________________
1369 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1371 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1373 this.prefetchImg(nextL);
1374 this.prefetchImg(nextR);
1376 var height = this.getPageHeight(nextR);
1377 var width = this.getPageWidth(nextR);
1378 var middle = ($('#GBcontainer').width() >> 1);
1379 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1380 var scaledW = this.twoPageH*width/height;
1382 var gutter = middle + this.gutterOffsetForIndex(nextL);
1384 //console.log('right to left to %d gutter is %d', nextL, gutter);
1386 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1387 $(this.prefetchedImgs[nextR]).css({
1388 position: 'absolute',
1391 backgroundColor: 'rgb(234, 226, 205)',
1392 height: this.twoPageH,
1393 width: scaledW+'px',
1394 borderLeft: '1px solid black',
1398 $('#GBcontainer').append(this.prefetchedImgs[nextR]);
1400 height = this.getPageHeight(nextL);
1401 width = this.getPageWidth(nextL);
1402 scaledW = this.twoPageH*width/height;
1404 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1405 $(this.prefetchedImgs[nextL]).css({
1406 position: 'absolute',
1407 right: $('#GBcontainer').width()-gutter+'px',
1409 backgroundColor: 'rgb(234, 226, 205)',
1410 height: this.twoPageH,
1412 borderRight: '1px solid black',
1416 $('#GBcontainer').append(this.prefetchedImgs[nextL]);
1422 // getNextLeafs() -- NOT RTL AWARE
1423 //______________________________________________________________________________
1424 // GnuBook.prototype.getNextLeafs = function(o) {
1425 // //TODO: we might have two left or two right leafs in a row (damaged book)
1426 // //For now, assume that leafs are contiguous.
1428 // //return [this.currentLeafL+2, this.currentLeafL+3];
1429 // o.L = this.currentLeafL+2;
1430 // o.R = this.currentLeafL+3;
1433 // getprevLeafs() -- NOT RTL AWARE
1434 //______________________________________________________________________________
1435 // GnuBook.prototype.getPrevLeafs = function(o) {
1436 // //TODO: we might have two left or two right leafs in a row (damaged book)
1437 // //For now, assume that leafs are contiguous.
1439 // //return [this.currentLeafL-2, this.currentLeafL-1];
1440 // o.L = this.currentLeafL-2;
1441 // o.R = this.currentLeafL-1;
1444 // pruneUnusedImgs()
1445 //______________________________________________________________________________
1446 GnuBook.prototype.pruneUnusedImgs = function() {
1447 //console.log('current: ' + this.currentLeafL + ' ' + this.currentLeafR);
1448 for (var key in this.prefetchedImgs) {
1449 //console.log('key is ' + key);
1450 if ((key != this.currentLeafL) && (key != this.currentLeafR)) {
1451 //console.log('removing key '+ key);
1452 $(this.prefetchedImgs[key]).remove();
1454 if ((key < this.currentLeafL-4) || (key > this.currentLeafR+4)) {
1455 //console.log('deleting key '+ key);
1456 delete this.prefetchedImgs[key];
1462 //______________________________________________________________________________
1463 GnuBook.prototype.prefetch = function() {
1465 var lim = this.currentLeafL-4;
1467 lim = Math.max(lim, 0);
1468 for (i = lim; i < this.currentLeafL; i++) {
1469 this.prefetchImg(i);
1472 if (this.numLeafs > (this.currentLeafR+1)) {
1473 lim = Math.min(this.currentLeafR+4, this.numLeafs-1);
1474 for (i=this.currentLeafR+1; i<=lim; i++) {
1475 this.prefetchImg(i);
1480 // getPageWidth2UP()
1481 //______________________________________________________________________________
1482 GnuBook.prototype.getPageWidth2UP = function(index) {
1483 var height = this.getPageHeight(index);
1484 var width = this.getPageWidth(index);
1485 return Math.floor(this.twoPageH*width/height);
1489 //______________________________________________________________________________
1490 GnuBook.prototype.search = function(term) {
1491 $('#GnuBookSearchScript').remove();
1492 var script = document.createElement("script");
1493 script.setAttribute('id', 'GnuBookSearchScript');
1494 script.setAttribute("type", "text/javascript");
1495 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath+'/'+this.bookId+'_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1496 document.getElementsByTagName('head')[0].appendChild(script);
1499 // GBSearchCallback()
1500 //______________________________________________________________________________
1501 GnuBook.prototype.GBSearchCallback = function(txt) {
1503 if (jQuery.browser.msie) {
1504 var dom=new ActiveXObject("Microsoft.XMLDOM");
1508 var parser = new DOMParser();
1509 var dom = parser.parseFromString(txt, "text/xml");
1512 $('#GnuBookSearchResults').empty();
1513 $('#GnuBookSearchResults').append('<ul>');
1515 for (var key in this.searchResults) {
1516 if (null != this.searchResults[key].div) {
1517 $(this.searchResults[key].div).remove();
1519 delete this.searchResults[key];
1522 var pages = dom.getElementsByTagName('PAGE');
1524 if (0 == pages.length) {
1525 // $$$ it would be nice to echo the (sanitized) search result here
1526 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1528 for (var i = 0; i < pages.length; i++){
1529 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1532 var re = new RegExp (/_(\d{4})/);
1533 var reMatch = re.exec(pages[i].getAttribute('file'));
1534 var leafNum = parseInt(reMatch[1], 10);
1535 //var leafNum = parseInt(pages[i].getAttribute('file').substr(1), 10);
1537 var children = pages[i].childNodes;
1539 for (var j=0; j<children.length; j++) {
1540 //console.log(j + ' - ' + children[j].nodeName);
1541 //console.log(children[j].firstChild.nodeValue);
1542 if ('CONTEXT' == children[j].nodeName) {
1543 context += children[j].firstChild.nodeValue;
1544 } else if ('WORD' == children[j].nodeName) {
1545 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1547 var index = this.leafNumToIndex(leafNum);
1548 if (null != index) {
1549 //coordinates are [left, bottom, right, top, [baseline]]
1550 //we'll skip baseline for now...
1551 var coords = children[j].getAttribute('coords').split(',',4);
1552 if (4 == coords.length) {
1553 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1558 //TODO: remove hardcoded instance name
1559 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">Leaf ' + leafNum + '</a></b> - ' + context+'</li>');
1562 $('#GnuBookSearchResults').append('</ul>');
1564 this.updateSearchHilites();
1567 // updateSearchHilites()
1568 //______________________________________________________________________________
1569 GnuBook.prototype.updateSearchHilites = function() {
1570 if (2 == this.mode) {
1571 this.updateSearchHilites2UP();
1573 this.updateSearchHilites1UP();
1577 // showSearchHilites1UP()
1578 //______________________________________________________________________________
1579 GnuBook.prototype.updateSearchHilites1UP = function() {
1581 for (var key in this.searchResults) {
1583 if (-1 != jQuery.inArray(parseInt(key), this.displayedLeafs)) {
1584 var result = this.searchResults[key];
1585 if(null == result.div) {
1586 result.div = document.createElement('div');
1587 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1588 //console.log('appending ' + key);
1591 width: (result.r-result.l)/this.reduce + 'px',
1592 height: (result.b-result.t)/this.reduce + 'px',
1593 left: (result.l)/this.reduce + 'px',
1594 top: (result.t)/this.reduce +'px'
1598 //console.log(key + ' not displayed');
1599 this.searchResults[key].div=null;
1604 // showSearchHilites2UP()
1605 //______________________________________________________________________________
1606 GnuBook.prototype.updateSearchHilites2UP = function() {
1608 var middle = ($('#GBcontainer').width() >> 1);
1610 for (var key in this.searchResults) {
1611 key = parseInt(key, 10);
1612 if (-1 != jQuery.inArray(key, this.displayedLeafs)) {
1613 var result = this.searchResults[key];
1614 if(null == result.div) {
1615 result.div = document.createElement('div');
1616 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBcontainer');
1617 //console.log('appending ' + key);
1620 var height = this.getPageHeight(key);
1621 var width = this.getPageWidth(key)
1622 var reduce = this.twoPageH/height;
1623 var scaledW = parseInt(width*reduce);
1625 var gutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
1627 if ('L' == this.getPageSide(key)) {
1628 var pageL = gutter-scaledW;
1632 var pageT = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1635 width: (result.r-result.l)*reduce + 'px',
1636 height: (result.b-result.t)*reduce + 'px',
1637 left: pageL+(result.l)*reduce + 'px',
1638 top: pageT+(result.t)*reduce +'px'
1642 //console.log(key + ' not displayed');
1643 if (null != this.searchResults[key].div) {
1644 //console.log('removing ' + key);
1645 $(this.searchResults[key].div).remove();
1647 this.searchResults[key].div=null;
1652 // removeSearchHilites()
1653 //______________________________________________________________________________
1654 GnuBook.prototype.removeSearchHilites = function() {
1655 for (var key in this.searchResults) {
1656 if (null != this.searchResults[key].div) {
1657 $(this.searchResults[key].div).remove();
1658 this.searchResults[key].div=null;
1664 //______________________________________________________________________________
1665 GnuBook.prototype.showEmbedCode = function() {
1666 if (null != this.embedPopup) { // check if already showing
1670 this.embedPopup = document.createElement("div");
1671 $(this.embedPopup).css({
1672 position: 'absolute',
1674 left: ($('#GBcontainer').width()-400)/2 + 'px',
1677 border: "3px double #999999",
1679 backgroundColor: "#fff"
1680 }).appendTo('#GnuBook');
1682 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1683 htmlStr += '<p><b>Note:</b> The bookreader is still in beta testing. URLs may change in the future, breaking embedded books. This feature is just for testing!</b></p>';
1684 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>';
1685 htmlStr += '<p>Embed Code: <input type="text" size="40" value="<iframe src=\'http://www.us.archive.org/GnuBook/GnuBookEmbed.php?id='+this.bookId+'\' width=\'430px\' height=\'430px\'></iframe>"></p>';
1686 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1688 this.embedPopup.innerHTML = htmlStr;
1692 //______________________________________________________________________________
1693 GnuBook.prototype.autoToggle = function() {
1695 var bComingFrom1up = false;
1696 if (2 != this.mode) {
1697 bComingFrom1up = true;
1702 if (null == this.autoTimer) {
1703 this.flipSpeed = 2000;
1705 // $$$ Draw events currently cause layout problems when they occur during animation.
1706 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1707 // we workaround for now by not triggering immediate animation in that case.
1708 // See https://bugs.launchpad.net/gnubook/+bug/328327
1709 if (('rl' == this.pageProgression) && bComingFrom1up) {
1710 // don't flip immediately -- wait until timer fires
1713 this.flipFwdToIndex();
1716 $('#GBtoolbar .play').hide();
1717 $('#GBtoolbar .pause').show();
1718 this.autoTimer=setInterval(function(){
1719 if (self.animating) {return;}
1721 if (Math.max(self.currentLeafL, self.currentLeafR) >= self.lastDisplayableIndex()) {
1722 self.flipBackToIndex(1); // $$$ really what we want?
1724 self.flipFwdToIndex();
1733 //______________________________________________________________________________
1734 GnuBook.prototype.autoStop = function() {
1735 if (null != this.autoTimer) {
1736 clearInterval(this.autoTimer);
1737 this.flipSpeed = 'fast';
1738 $('#GBtoolbar .pause').hide();
1739 $('#GBtoolbar .play').show();
1740 this.autoTimer = null;
1744 // keyboardNavigationIsDisabled(event)
1745 // - returns true if keyboard navigation should be disabled for the event
1746 //______________________________________________________________________________
1747 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
1748 if (event.target.tagName == "INPUT") {
1754 // gutterOffsetForIndex
1755 //______________________________________________________________________________
1757 // Returns the gutter offset for the spread containing the given index.
1758 // This function supports RTL
1759 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
1761 // To find the offset of the gutter from the middle we calculate our percentage distance
1762 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
1763 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPageEdgeW);
1765 // But then again for RTL it's the opposite
1766 if ('rl' == this.pageProgression) {
1774 //______________________________________________________________________________
1775 // Returns the width of the leaf edge div for the page with index given
1776 GnuBook.prototype.leafEdgeWidth = function(pindex) {
1777 // $$$ could there be single pixel rounding errors for L vs R?
1778 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
1779 return parseInt( (pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1781 return parseInt( (1 - pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1785 // jumpIndexForLeftEdgePageX
1786 //______________________________________________________________________________
1787 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
1788 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
1789 if ('rl' != this.pageProgression) {
1790 // LTR - flipping backward
1791 var jumpLeaf = this.currentLeafL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1792 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
1793 jumpLeaf = Math.min(jumpLeaf, this.currentLeafL - 2);
1794 jumpLeaf = Math.max(jumpLeaf, this.firstDisplayableIndex());
1797 var jumpLeaf = this.currentLeafL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1798 jumpLeaf = Math.max(jumpLeaf, this.currentLeafL + 2);
1799 jumpLeaf = Math.min(jumpLeaf, this.lastDisplayableIndex());
1804 // jumpIndexForRightEdgePageX
1805 //______________________________________________________________________________
1806 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
1807 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
1808 if ('rl' != this.pageProgression) {
1810 var jumpLeaf = this.currentLeafR + (pageX - $(this.leafEdgeR).offset().left) * 10;
1811 jumpLeaf = Math.max(jumpLeaf, this.currentLeafR + 2);
1812 jumpLeaf = Math.min(jumpLeaf, this.lastDisplayableIndex());
1815 var jumpLeaf = this.currentLeafR - (pageX - $(this.leafEdgeR).offset().left) * 10;
1816 jumpLeaf = Math.min(jumpLeaf, this.currentLeafR - 2);
1817 jumpLeaf = Math.max(jumpLeaf, this.firstDisplayableIndex());
1822 GnuBook.prototype.initToolbar = function(mode) {
1823 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
1824 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
1825 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom1up(-1); return false;'/>"
1826 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom1up(1); return false;'/>"
1827 + " <span class='label'>Zoom: <span id='GBzoom'>25</span>%</span>"
1828 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
1829 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
1830 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
1833 // $$$ turn this into a member variable
1834 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
1836 // We build in mode 2
1837 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
1838 + "<button class='GBicon rollover embed' />"
1839 + "<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>"
1840 + "<div class='GBtoolbarmode2' style='display: inline'><button class='GBicon rollover book_left' /><button class='GBicon rollover book_right' /></div>"
1841 + "<div class='GBtoolbarmode1' style='display: hidden'><button class='GBicon rollover book_up' /> <button class='GBicon rollover book_down' /></div>"
1842 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
1844 // Bind the non-changing click handlers
1845 jToolbar.find('.embed').bind('click', function(e) {
1849 jToolbar.find('.play').bind('click', function(e) {
1853 jToolbar.find('.pause').bind('click', function(e) {
1858 // Setup tooltips -- later we could load these from a file for i18n
1859 var titles = { '.logo': 'Go to Archive.org',
1860 '.zoom_in': 'Zoom in',
1861 '.zoom_out': 'Zoom out',
1862 '.one_page_mode': 'One-page view',
1863 '.two_page_mode': 'Two-page view',
1864 '.embed': 'Embed bookreader',
1865 '.book_left': 'Flip left',
1866 '.book_right': 'Flip right',
1867 '.book_up': 'Page up',
1868 '.book_down': 'Page down',
1872 for (var icon in titles) {
1873 jToolbar.find(icon).attr('title', titles[icon]);
1876 // Switch to requested mode -- binds other click handlers
1877 this.switchToolbarMode(mode);
1882 // switchToolbarMode
1883 //______________________________________________________________________________
1884 // Update the toolbar for the given mode (changes navigation buttons)
1885 // $$$ we should soon split the toolbar out into its own module
1886 GnuBook.prototype.switchToolbarMode = function(mode) {
1889 $('#GBtoolbar .GBtoolbarmode2').hide();
1890 $('#GBtoolbar .GBtoolbarmode1').css('display', 'inline').show();
1893 $('#GBtoolbar .GBtoolbarmode1').hide();
1894 $('#GBtoolbar .GBtoolbarmode2').css('display', 'inline').show();
1897 this.bindToolbarNavHandlers($('#GBtoolbar'));
1900 // bindToolbarNavHandlers
1901 //______________________________________________________________________________
1902 // Binds the toolbar handlers
1903 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
1905 jToolbar.find('.book_left').unbind('click')
1906 .bind('click', function(e) {
1911 jToolbar.find('.book_right').unbind('click')
1912 .bind('click', function(e) {
1917 jToolbar.find('.book_up').unbind('click')
1918 .bind('click', function(e) {
1923 jToolbar.find('.book_down').unbind('click')
1924 .bind('click', function(e) {
1930 // firstDisplayableIndex
1931 //______________________________________________________________________________
1932 // Returns the index of the first visible page, dependent on the mode.
1933 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
1934 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
1935 GnuBook.prototype.firstDisplayableIndex = function() {
1936 if (this.mode == 0) {
1939 return 1; // $$$ we assume there are enough pages... we need logic for very short books
1943 // lastDisplayableIndex
1944 //______________________________________________________________________________
1945 // Returns the index of the last visible page, dependent on the mode.
1946 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
1947 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
1948 GnuBook.prototype.lastDisplayableIndex = function() {
1949 if (this.mode == 2) {
1950 if (this.lastDisplayableIndex2up === null) {
1951 // Calculate and cache
1952 var candidate = this.numLeafs - 1;
1953 for ( ; candidate >= 0; candidate--) {
1954 var spreadIndices = this.getSpreadIndices(candidate);
1955 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
1959 this.lastDisplayableIndex2up = candidate;
1961 return this.lastDisplayableIndex2up;
1963 return this.numLeafs - 1;
1967 // shortTitle(maximumCharacters)
1969 // Returns a shortened version of the title with the maximum number of characters
1970 GnuBook.prototype.shortTitle = function(maximumCharacters) {
1971 if (this.bookTitle.length < maximumCharacters) {
1972 return this.bookTitle;
1975 var title = this.bookTitle.substr(0, maximumCharacters - 3);