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().
36 this.mode = 1; //1 or 2
37 this.ui = 'full'; // UI mode
39 this.displayedIndices = [];
40 //this.indicesToDisplay = [];
42 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
45 this.animating = false;
47 this.autoTimer = null;
48 this.flipSpeed = 'fast';
50 this.twoPagePopUp = null;
51 this.leafEdgeTmp = null;
52 this.embedPopup = null;
53 this.printPopup = null;
56 this.searchResults = {};
58 this.firstIndex = null;
60 this.lastDisplayableIndex2up = null;
62 // We link to index.php to avoid redirect which breaks back button
63 this.logoURL = 'http://www.archive.org/index.php';
65 // Base URL for images
66 this.imagesBaseURL = '/bookreader/images/';
69 this.constMode1up = 1;
70 this.constMode2up = 2;
73 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
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
83 // Background color for pages (e.g. when loading page image)
84 // $$$ TODO dynamically calculate based on page images
85 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
89 //______________________________________________________________________________
90 GnuBook.prototype.init = function() {
92 var startIndex = undefined;
94 // Find start index and mode if set in location hash
95 var params = this.paramsFromFragment(window.location.hash);
97 if ('undefined' != typeof(params.index)) {
98 startIndex = params.index;
99 } else if ('undefined' != typeof(params.page)) {
100 startIndex = this.getPageIndex(params.page);
103 if ('undefined' == typeof(startIndex)) {
104 if ('undefined' != typeof(this.titleLeaf)) {
105 startIndex = this.leafNumToIndex(this.titleLeaf);
109 if ('undefined' == typeof(startIndex)) {
113 if ('undefined' != typeof(params.mode)) {
114 this.mode = params.mode;
117 // Set document title -- may have already been set in enclosing html for
118 // search engine visibility
119 document.title = this.shortTitle(50);
121 // Sanitize parameters
122 if ( !this.canSwitchToMode( this.mode ) ) {
123 this.mode = this.constMode1up;
126 $("#GnuBook").empty();
127 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
128 $("#GnuBook").append("<div id='GBcontainer'></div>");
129 $("#GBcontainer").append("<div id='GBpageview'></div>");
131 $("#GBcontainer").bind('scroll', this, function(e) {
135 this.setupKeyListeners();
136 this.startLocationPolling();
138 $(window).bind('resize', this, function(e) {
139 //console.log('resize!');
140 if (1 == e.data.mode) {
141 //console.log('centering 1page view');
142 e.data.centerPageView();
143 $('#GBpageview').empty()
144 e.data.displayedIndices = [];
145 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
148 //console.log('drawing 2 page view');
150 // We only need to prepare again in autofit (size of spread changes)
151 if (e.data.twoPage.autofit) {
152 e.data.prepareTwoPageView();
154 // Re-center if the scrollbars have disappeared
155 var center = e.data.twoPageGetViewCenter();
156 var doRecenter = false;
157 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
158 center.percentageX = 0.5;
161 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
162 center.percentageY = 0.5;
166 e.data.twoPageCenterView(center.percentageX, center.percentageY);
172 $('.GBpagediv1up').bind('mousedown', this, function(e) {
173 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
174 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
177 if (1 == this.mode) {
178 this.resizePageView();
179 this.firstIndex = startIndex;
180 this.jumpToIndex(startIndex);
182 //this.resizePageView();
184 this.displayedIndices=[0];
185 this.firstIndex = startIndex;
186 this.displayedIndices = [this.firstIndex];
187 //console.log('titleLeaf: %d', this.titleLeaf);
188 //console.log('displayedIndices: %s', this.displayedIndices);
189 this.prepareTwoPageView();
192 // Enact other parts of initial params
193 this.updateFromParams(params);
196 GnuBook.prototype.setupKeyListeners = function() {
209 // We use document here instead of window to avoid a bug in jQuery on IE7
210 $(document).keydown(function(e) {
212 // Keyboard navigation
213 if (!self.keyboardNavigationIsDisabled(e)) {
217 // In 1up mode page scrolling is handled by browser
218 if (2 == self.mode) {
225 if (2 == self.mode) {
239 if (2 == self.mode) {
245 if (2 == self.mode) {
256 //______________________________________________________________________________
257 GnuBook.prototype.drawLeafs = function() {
258 if (1 == this.mode) {
259 this.drawLeafsOnePage();
261 this.drawLeafsTwoPage();
266 //______________________________________________________________________________
267 GnuBook.prototype.setDragHandler = function(div) {
268 div.dragging = false;
270 $(div).unbind('mousedown').bind('mousedown', function(e) {
273 //console.log('mousedown at ' + e.pageY);
275 this.dragging = true;
276 this.prevMouseX = e.pageX;
277 this.prevMouseY = e.pageY;
279 var startX = e.pageX;
280 var startY = e.pageY;
281 var startTop = $('#GBcontainer').attr('scrollTop');
282 var startLeft = $('#GBcontainer').attr('scrollLeft');
286 $(div).unbind('mousemove').bind('mousemove', function(ee) {
289 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
291 var offsetX = ee.pageX - this.prevMouseX;
292 var offsetY = ee.pageY - this.prevMouseY;
295 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
296 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
299 this.prevMouseX = ee.pageX;
300 this.prevMouseY = ee.pageY;
304 $(div).unbind('mouseup').bind('mouseup', function(ee) {
306 //console.log('mouseup');
308 this.dragging = false;
311 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
313 //console.log('mouseleave');
315 this.dragging = false;
318 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
320 //console.log('mouseenter');
322 this.dragging = false;
326 // setDragHandler2UP()
327 //______________________________________________________________________________
328 GnuBook.prototype.setDragHandler2UP = function(div) {
329 div.dragging = false;
331 $(div).unbind('mousedown').bind('mousedown', function(e) {
334 //console.log('mousedown at ' + e.pageY);
336 this.dragStart = {x: e.pageX, y: e.pageY };
337 this.mouseDown = true;
338 this.dragging = false; // wait until drag distance
339 this.prevMouseX = e.pageX;
340 this.prevMouseY = e.pageY;
342 var startX = e.pageX;
343 var startY = e.pageY;
344 var startTop = $('#GBcontainer').attr('scrollTop');
345 var startLeft = $('#GBcontainer').attr('scrollLeft');
349 $(div).unbind('mousemove').bind('mousemove', function(ee) {
352 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
354 var offsetX = ee.pageX - this.prevMouseX;
355 var offsetY = ee.pageY - this.prevMouseY;
357 var minDragDistance = 5; // $$$ constant
359 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
361 if (this.mouseDown && (distance > minDragDistance)) {
362 //console.log('drag start!');
364 this.dragging = true;
368 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
369 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
370 this.prevMouseX = ee.pageX;
371 this.prevMouseY = ee.pageY;
378 $(div).unbind('mouseup').bind('mouseup', function(ee) {
380 //console.log('mouseup');
382 this.dragging = false;
383 this.mouseDown = false;
388 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
390 //console.log('mouseleave');
392 this.dragging = false;
393 this.mouseDown = false;
396 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
398 //console.log('mouseenter');
400 this.dragging = false;
401 this.mouseDown = false;
405 GnuBook.prototype.setClickHandler2UP = function( element, data, handler) {
406 //console.log('setting handler');
407 //console.log(element.tagName);
409 $(element).unbind('click').bind('click', data, function(e) {
412 //console.log('click!');
414 if (this.mouseDown && (!this.dragging)) {
415 //console.log('click not dragging!');
419 this.dragging = false;
420 this.mouseDown = false;
424 // drawLeafsOnePage()
425 //______________________________________________________________________________
426 GnuBook.prototype.drawLeafsOnePage = function() {
427 //alert('drawing leafs!');
431 var scrollTop = $('#GBcontainer').attr('scrollTop');
432 var scrollBottom = scrollTop + $('#GBcontainer').height();
433 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
435 var indicesToDisplay = [];
440 for (i=0; i<this.numLeafs; i++) {
441 var height = parseInt(this.getPageHeight(i)/this.reduce);
443 leafBottom += height;
444 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
445 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
446 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
447 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
448 if (topInView | bottomInView | middleInView) {
449 //console.log('displayed: ' + this.displayedIndices);
450 //console.log('to display: ' + i);
451 indicesToDisplay.push(i);
453 leafTop += height +10;
457 var firstIndexToDraw = indicesToDisplay[0];
458 this.firstIndex = firstIndexToDraw;
460 // Update hash, but only if we're currently displaying a leaf
461 // Hack that fixes #365790
462 if (this.displayedIndices.length > 0) {
463 this.updateLocationHash();
466 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
468 indicesToDisplay.unshift(firstIndexToDraw);
471 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
472 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
473 indicesToDisplay.push(lastIndexToDraw+1);
478 for (i=0; i<firstIndexToDraw; i++) {
479 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
482 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
483 var viewWidth = $('#GBcontainer').attr('scrollWidth');
486 for (i=0; i<indicesToDisplay.length; i++) {
487 var index = indicesToDisplay[i];
488 var height = parseInt(this.getPageHeight(index)/this.reduce);
490 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
491 var width = parseInt(this.getPageWidth(index)/this.reduce);
492 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
493 var div = document.createElement("div");
494 div.className = 'GBpagediv1up';
495 div.id = 'pagediv'+index;
496 div.style.position = "absolute";
497 $(div).css('top', leafTop + 'px');
498 var left = (viewWidth-width)>>1;
499 if (left<0) left = 0;
500 $(div).css('left', left+'px');
501 $(div).css('width', width+'px');
502 $(div).css('height', height+'px');
503 //$(div).text('loading...');
505 this.setDragHandler(div);
507 $('#GBpageview').append(div);
509 var img = document.createElement("img");
510 img.src = this.getPageURI(index, this.reduce, 0);
511 $(img).css('width', width+'px');
512 $(img).css('height', height+'px');
516 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
519 leafTop += height +10;
523 for (i=0; i<this.displayedIndices.length; i++) {
524 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
525 var index = this.displayedIndices[i];
526 //console.log('Removing leaf ' + index);
527 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
528 $('#pagediv'+index).remove();
530 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
534 this.displayedIndices = indicesToDisplay.slice();
535 this.updateSearchHilites();
537 if (null != this.getPageNum(firstIndexToDraw)) {
538 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
540 $("#GBpagenum").val('');
543 this.updateToolbarZoom(this.reduce);
547 // drawLeafsTwoPage()
548 //______________________________________________________________________________
549 GnuBook.prototype.drawLeafsTwoPage = function() {
550 var scrollTop = $('#GBtwopageview').attr('scrollTop');
551 var scrollBottom = scrollTop + $('#GBtwopageview').height();
553 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
555 var indexL = this.twoPage.currentIndexL;
557 var heightL = this.getPageHeight(indexL);
558 var widthL = this.getPageWidth(indexL);
560 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
561 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
562 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
563 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
564 //console.log(leafEdgeWidthL);
566 var middle = this.twoPage.middle; // $$$ getter instead?
567 var top = this.twoPageTop();
568 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
570 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
571 this.twoPage.gutter = this.twoPageGutter();
573 this.prefetchImg(indexL);
574 $(this.prefetchedImgs[indexL]).css({
575 position: 'absolute',
576 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
579 backgroundColor: this.getPageBackgroundColor(indexL),
580 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
581 width: this.twoPage.scaledWL + 'px',
582 borderRight: '1px solid black',
584 }).appendTo('#GBtwopageview');
586 var indexR = this.twoPage.currentIndexR;
587 var heightR = this.getPageHeight(indexR);
588 var widthR = this.getPageWidth(indexR);
590 // $$$ should use getwidth2up?
591 //var scaledWR = this.twoPage.height*widthR/heightR;
592 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
593 this.prefetchImg(indexR);
594 $(this.prefetchedImgs[indexR]).css({
595 position: 'absolute',
596 left: this.twoPage.gutter+'px',
599 backgroundColor: this.getPageBackgroundColor(indexR),
600 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
601 width: this.twoPage.scaledWR + 'px',
602 borderLeft: '1px solid black',
604 }).appendTo('#GBtwopageview');
607 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
608 this.setMouseHandlers2UP();
609 this.twoPageSetCursor();
611 this.updatePageNumBox2UP();
612 this.updateToolbarZoom(this.reduce);
614 // this.twoPagePlaceFlipAreas(); // No longer used
618 // updatePageNumBox2UP
619 //______________________________________________________________________________
620 GnuBook.prototype.updatePageNumBox2UP = function() {
621 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
622 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
624 $("#GBpagenum").val('');
626 this.updateLocationHash();
630 //______________________________________________________________________________
631 GnuBook.prototype.loadLeafs = function() {
635 if (null == this.timer) {
636 this.timer=setTimeout(function(){self.drawLeafs()},250);
638 clearTimeout(this.timer);
639 this.timer=setTimeout(function(){self.drawLeafs()},250);
645 // Pass 1 to zoom in, anything else to zoom out
646 //______________________________________________________________________________
647 GnuBook.prototype.zoom = function(direction) {
649 case this.constMode1up:
650 return this.zoom1up(direction);
651 case this.constMode2up:
652 return this.zoom2up(direction);
657 //______________________________________________________________________________
658 GnuBook.prototype.zoom1up = function(dir) {
659 if (2 == this.mode) { //can only zoom in 1-page mode
664 // $$$ with flexible zoom we could "snap" to /2 page reductions
665 // for better scaling
667 if (this.reduce <= 0.5) return;
668 this.reduce*=0.5; //zoom in
670 if (this.reduce >= 8) return;
671 this.reduce*=2; //zoom out
674 this.resizePageView();
676 $('#GBpageview').empty()
677 this.displayedIndices = [];
680 this.updateToolbarZoom(this.reduce);
684 //______________________________________________________________________________
685 GnuBook.prototype.resizePageView = function() {
688 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
689 var viewWidth = $('#GBcontainer').attr('clientWidth');
691 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
692 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
693 var oldPageViewHeight = $('#GBpageview').height();
694 var oldPageViewWidth = $('#GBpageview').width();
696 var oldCenterY = this.centerY1up();
697 var oldCenterX = this.centerX1up();
699 if (0 != oldPageViewHeight) {
700 var scrollRatio = oldCenterY / oldPageViewHeight;
705 for (i=0; i<this.numLeafs; i++) {
706 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
707 var width = parseInt(this.getPageWidth(i)/this.reduce);
708 if (width>viewWidth) viewWidth=width;
710 $('#GBpageview').height(viewHeight);
711 $('#GBpageview').width(viewWidth);
713 var newCenterY = scrollRatio*viewHeight;
714 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
715 $('#GBcontainer').attr('scrollTop', newTop);
717 // We use clientWidth here to avoid miscalculating due to scroll bar
718 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
719 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
720 newLeft = Math.max(newLeft, 0);
721 $('#GBcontainer').attr('scrollLeft', newLeft);
722 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
724 //this.centerPageView();
730 //______________________________________________________________________________
731 // Returns the current offset of the viewport center in scaled document coordinates.
732 GnuBook.prototype.centerX1up = function() {
734 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
735 centerX = $('#GBpageview').width();
737 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
739 centerX = Math.floor(centerX);
744 //______________________________________________________________________________
745 // Returns the current offset of the viewport center in scaled document coordinates.
746 GnuBook.prototype.centerY1up = function() {
747 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
748 return Math.floor(centerY);
752 //______________________________________________________________________________
753 GnuBook.prototype.centerPageView = function() {
755 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
756 var clientWidth = $('#GBcontainer').attr('clientWidth');
757 //console.log('sW='+scrollWidth+' cW='+clientWidth);
758 if (scrollWidth > clientWidth) {
759 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
764 // zoom2up(direction)
765 //______________________________________________________________________________
766 GnuBook.prototype.zoom2up = function(direction) {
768 // Hard stop autoplay
769 this.stopFlipAnimations();
771 // Get new zoom state
772 var newZoom = this.twoPageNextReduce(this.reduce, direction);
773 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
776 this.twoPage.autofit = newZoom.autofit;
777 this.reduce = newZoom.reduce;
779 // Preserve view center position
780 var oldCenter = this.twoPageGetViewCenter();
782 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
783 // $$$ An improvement would be to use the low res image until the larger one is loaded.
784 if (1 == direction) {
785 for (var img in this.prefetchedImgs) {
786 delete this.prefetchedImgs[img];
790 // Prepare view with new center to minimize visual glitches
791 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
795 // quantizeReduce(reduce)
796 //______________________________________________________________________________
797 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
798 GnuBook.prototype.quantizeReduce = function(reduce) {
799 var quantized = this.reductionFactors[0];
800 var distance = Math.abs(reduce - quantized);
801 for (var i = 1; i < this.reductionFactors.length; i++) {
802 newDistance = Math.abs(reduce - this.reductionFactors[i]);
803 if (newDistance < distance) {
804 distance = newDistance;
805 quantized = this.reductionFactors[i];
812 // twoPageNextReduce()
813 //______________________________________________________________________________
814 // Returns the next reduction level
815 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
817 var autofitReduce = this.twoPageGetAutofitReduce();
819 if (0 == direction) { // autofit
820 result.autofit = true;
821 result.reduce = autofitReduce;
823 } else if (1 == direction) { // zoom in
824 var newReduce = this.reductionFactors[0];
826 for (var i = 1; i < this.reductionFactors.length; i++) {
827 if (this.reductionFactors[i] < reduce) {
828 newReduce = this.reductionFactors[i];
832 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
834 result.autofit = true;
835 result.reduce = autofitReduce;
837 result.autofit = false;
838 result.reduce = newReduce;
842 var lastIndex = this.reductionFactors.length - 1;
843 var newReduce = this.reductionFactors[lastIndex];
845 for (var i = lastIndex; i >= 0; i--) {
846 if (this.reductionFactors[i] > reduce) {
847 newReduce = this.reductionFactors[i];
851 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
853 result.autofit = true;
854 result.reduce = autofitReduce;
856 result.autofit = false;
857 result.reduce = newReduce;
865 //______________________________________________________________________________
866 // Attempts to jump to page. Returns true if page could be found, false otherwise.
867 GnuBook.prototype.jumpToPage = function(pageNum) {
869 var pageIndex = this.getPageIndex(pageNum);
871 if ('undefined' != typeof(pageIndex)) {
874 this.jumpToIndex(pageIndex);
875 $('#GBcontainer').attr('scrollTop', leafTop);
884 //______________________________________________________________________________
885 GnuBook.prototype.jumpToIndex = function(index) {
887 if (2 == this.mode) {
890 // By checking against min/max we do nothing if requested index
892 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
893 this.flipBackToIndex(index);
894 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
895 this.flipFwdToIndex(index);
902 for (i=0; i<index; i++) {
903 h = parseInt(this.getPageHeight(i)/this.reduce);
904 leafTop += h + this.padding;
906 //$('#GBcontainer').attr('scrollTop', leafTop);
907 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
914 //______________________________________________________________________________
915 GnuBook.prototype.switchMode = function(mode) {
917 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
919 if (mode == this.mode) return;
921 if (!this.canSwitchToMode(mode)) {
926 this.removeSearchHilites();
930 this.switchToolbarMode(mode);
932 // $$$ TODO preserve center of view when switching between mode
933 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
936 this.reduce = this.quantizeReduce(this.reduce);
937 this.prepareOnePageView();
939 this.twoPage.autofit = false; // Take zoom level from other mode
940 this.reduce = this.quantizeReduce(this.reduce);
941 this.prepareTwoPageView();
942 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
947 //prepareOnePageView()
948 //______________________________________________________________________________
949 GnuBook.prototype.prepareOnePageView = function() {
951 // var startLeaf = this.displayedIndices[0];
952 var startLeaf = this.currentIndex();
954 $('#GBcontainer').empty();
955 $('#GBcontainer').css({
960 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
962 this.resizePageView();
964 this.jumpToIndex(startLeaf);
965 this.displayedIndices = [];
967 this.drawLeafsOnePage();
969 // Bind mouse handlers
970 // Disable mouse click to avoid selected/highlighted page images - bug 354239
971 gbPageView.bind('mousedown', function(e) {
972 // $$$ check here for right-click and don't disable. Also use jQuery style
973 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
976 // Special hack for IE7
977 gbPageView[0].onselectstart = function(e) { return false; };
980 // prepareTwoPageView()
981 //______________________________________________________________________________
982 // Some decisions about two page view:
984 // Both pages will be displayed at the same height, even if they were different physical/scanned
985 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
986 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
987 // aspect ratio to determine the height.
989 // The two page view div is resized to keep the middle of the book in the middle of the div
990 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
991 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
992 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
993 $('#GBcontainer').empty();
994 $('#GBcontainer').css('overflow', 'auto');
996 // We want to display two facing pages. We may be missing
997 // one side of the spread because it is the first/last leaf,
998 // foldouts, missing pages, etc
1000 //var targetLeaf = this.displayedIndices[0];
1001 var targetLeaf = this.firstIndex;
1003 if (targetLeaf < this.firstDisplayableIndex()) {
1004 targetLeaf = this.firstDisplayableIndex();
1007 if (targetLeaf > this.lastDisplayableIndex()) {
1008 targetLeaf = this.lastDisplayableIndex();
1011 //this.twoPage.currentIndexL = null;
1012 //this.twoPage.currentIndexR = null;
1013 //this.pruneUnusedImgs();
1015 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1016 this.twoPage.currentIndexL = currentSpreadIndices[0];
1017 this.twoPage.currentIndexR = currentSpreadIndices[1];
1018 this.firstIndex = this.twoPage.currentIndexL;
1020 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1022 this.pruneUnusedImgs();
1023 this.prefetch(); // Preload images or reload if scaling has changed
1025 //console.dir(this.twoPage);
1027 // Add the two page view
1028 // $$$ Can we get everything set up and then append?
1029 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
1031 // $$$ calculate first then set
1032 $('#GBtwopageview').css( {
1033 height: this.twoPage.totalHeight + 'px',
1034 width: this.twoPage.totalWidth + 'px',
1035 position: 'absolute'
1038 // If there will not be scrollbars (e.g. when zooming out) we center the book
1039 // since otherwise the book will be stuck off-center
1040 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
1041 centerPercentageX = 0.5;
1043 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
1044 centerPercentageY = 0.5;
1047 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1049 this.twoPage.coverDiv = document.createElement('div');
1050 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
1051 border: '1px solid rgb(68, 25, 17)',
1052 width: this.twoPage.bookCoverDivWidth + 'px',
1053 height: this.twoPage.bookCoverDivHeight+'px',
1054 visibility: 'visible',
1055 position: 'absolute',
1056 backgroundColor: '#663929',
1057 left: this.twoPage.bookCoverDivLeft + 'px',
1058 top: this.twoPage.bookCoverDivTop+'px',
1059 MozBorderRadiusTopleft: '7px',
1060 MozBorderRadiusTopright: '7px',
1061 MozBorderRadiusBottomright: '7px',
1062 MozBorderRadiusBottomleft: '7px'
1063 }).appendTo('#GBtwopageview');
1065 this.leafEdgeR = document.createElement('div');
1066 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1067 $(this.leafEdgeR).css({
1068 borderStyle: 'solid solid solid none',
1069 borderColor: 'rgb(51, 51, 34)',
1070 borderWidth: '1px 1px 1px 0px',
1071 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1072 width: this.twoPage.leafEdgeWidthR + 'px',
1073 height: this.twoPage.height-1 + 'px',
1075 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1076 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1077 position: 'absolute'
1078 }).appendTo('#GBtwopageview');
1080 this.leafEdgeL = document.createElement('div');
1081 this.leafEdgeL.className = 'leafEdgeL';
1082 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1083 borderStyle: 'solid none solid solid',
1084 borderColor: 'rgb(51, 51, 34)',
1085 borderWidth: '1px 0px 1px 1px',
1086 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1087 width: this.twoPage.leafEdgeWidthL + 'px',
1088 height: this.twoPage.height-1 + 'px',
1089 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1090 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1091 position: 'absolute'
1092 }).appendTo('#GBtwopageview');
1094 div = document.createElement('div');
1095 $(div).attr('id', 'GBbookspine').css({
1096 border: '1px solid rgb(68, 25, 17)',
1097 width: this.twoPage.bookSpineDivWidth+'px',
1098 height: this.twoPage.bookSpineDivHeight+'px',
1099 position: 'absolute',
1100 backgroundColor: 'rgb(68, 25, 17)',
1101 left: this.twoPage.bookSpineDivLeft+'px',
1102 top: this.twoPage.bookSpineDivTop+'px'
1103 }).appendTo('#GBtwopageview');
1105 var self = this; // for closure
1107 /* Flip areas no longer used
1108 this.twoPage.leftFlipArea = document.createElement('div');
1109 this.twoPage.leftFlipArea.className = 'GBfliparea';
1110 $(this.twoPage.leftFlipArea).attr('id', 'GBleftflip').css({
1112 width: this.twoPageFlipAreaWidth() + 'px',
1113 height: this.twoPageFlipAreaHeight() + 'px',
1114 position: 'absolute',
1115 left: this.twoPageLeftFlipAreaLeft() + 'px',
1116 top: this.twoPageFlipAreaTop() + 'px',
1119 }).bind('click', function(e) {
1121 }).bind('mousedown', function(e) {
1123 }).appendTo('#GBtwopageview');
1125 this.twoPage.rightFlipArea = document.createElement('div');
1126 this.twoPage.rightFlipArea.className = 'GBfliparea';
1127 $(this.twoPage.rightFlipArea).attr('id', 'GBrightflip').css({
1129 width: this.twoPageFlipAreaWidth() + 'px',
1130 height: this.twoPageFlipAreaHeight() + 'px',
1131 position: 'absolute',
1132 left: this.twoPageRightFlipAreaLeft() + 'px',
1133 top: this.twoPageFlipAreaTop() + 'px',
1136 }).bind('click', function(e) {
1138 }).bind('mousedown', function(e) {
1140 }).appendTo('#GBtwopageview');
1143 this.prepareTwoPagePopUp();
1145 this.displayedIndices = [];
1147 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1148 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1150 this.drawLeafsTwoPage();
1151 this.updateSearchHilites2UP();
1152 this.updateToolbarZoom(this.reduce);
1157 // prepareTwoPagePopUp()
1159 // This function prepares the "View Page n" popup that shows while the mouse is
1160 // over the left/right "stack of sheets" edges. It also binds the mouse
1161 // events for these divs.
1162 //______________________________________________________________________________
1163 GnuBook.prototype.prepareTwoPagePopUp = function() {
1165 this.twoPagePopUp = document.createElement('div');
1166 $(this.twoPagePopUp).css({
1167 border: '1px solid black',
1169 position: 'absolute',
1170 fontFamily: 'sans-serif',
1173 backgroundColor: 'rgb(255, 255, 238)',
1175 }).appendTo('#GBcontainer');
1176 $(this.twoPagePopUp).hide();
1178 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1179 $(e.data.twoPagePopUp).show();
1182 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1183 $(e.data.twoPagePopUp).hide();
1186 $(this.leafEdgeL).bind('click', this, function(e) {
1188 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1189 e.data.jumpToIndex(jumpIndex);
1192 $(this.leafEdgeR).bind('click', this, function(e) {
1194 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1195 e.data.jumpToIndex(jumpIndex);
1198 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1200 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1201 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1203 // $$$ TODO: Make sure popup is positioned so that it is in view
1204 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1205 $(e.data.twoPagePopUp).css({
1206 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1207 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1211 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1213 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1214 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1216 // $$$ TODO: Make sure popup is positioned so that it is in view
1217 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1218 $(e.data.twoPagePopUp).css({
1219 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1220 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1225 // calculateSpreadSize()
1226 //______________________________________________________________________________
1227 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1228 // this.twoPage.currentIndexR
1229 // This function sets this.twoPage.height, twoPage.width
1231 GnuBook.prototype.calculateSpreadSize = function() {
1233 var firstIndex = this.twoPage.currentIndexL;
1234 var secondIndex = this.twoPage.currentIndexR;
1235 //console.log('first page is ' + firstIndex);
1237 // Calculate page sizes and total leaf width
1239 if ( this.twoPage.autofit) {
1240 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1242 // set based on reduction factor
1243 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1246 // Both pages together
1247 this.twoPage.height = spreadSize.height;
1248 this.twoPage.width = spreadSize.width;
1251 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1252 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1255 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1256 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1257 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1261 // The width of the book cover div. The combined width of both pages, twice the width
1262 // of the book cover internal padding (2*10) and the page edges
1263 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1264 // The height of the book cover div
1265 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1268 // We calculate the total width and height for the div so that we can make the book
1270 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1271 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1272 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1273 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1274 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1275 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1277 // We want to minimize the unused space in two-up mode (maximize the amount of page
1278 // shown). We give width to the leaf edges and these widths change (though the sum
1279 // of the two remains constant) as we flip through the book. With the book
1280 // cover centered and fixed in the GBcontainer div the page images will meet
1281 // at the "gutter" which is generally offset from the center.
1282 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1283 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1285 // The left edge of the book cover moves depending on the width of the pages
1286 // $$$ change to getter
1287 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1288 // The top edge of the book cover stays a fixed distance from the top
1289 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1292 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1293 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1294 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1297 this.reduce = spreadSize.reduce; // $$$ really set this here?
1300 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1303 // We check which page is closest to a "normal" page and use that to set the height
1304 // for both pages. This means that foldouts and other odd size pages will be displayed
1305 // smaller than the nominal zoom amount.
1306 var canon5Dratio = 1.5;
1309 height: this.getPageHeight(firstIndex),
1310 width: this.getPageWidth(firstIndex)
1314 height: this.getPageHeight(secondIndex),
1315 width: this.getPageWidth(secondIndex)
1318 var firstIndexRatio = first.height / first.width;
1319 var secondIndexRatio = second.height / second.width;
1320 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1323 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1324 ratio = firstIndexRatio;
1325 //console.log('using firstIndexRatio ' + ratio);
1327 ratio = secondIndexRatio;
1328 //console.log('using secondIndexRatio ' + ratio);
1331 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1332 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1333 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1335 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1336 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1338 ideal.width = ($('#GBcontainer').width() - widthOutsidePages) >> 1;
1339 ideal.width -= 10; // $$$ fudge factor
1340 ideal.height = $('#GBcontainer').height() - heightOutsidePages;
1341 ideal.height -= 20; // fudge factor
1342 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1344 if (ideal.height/ratio <= ideal.width) {
1346 ideal.width = parseInt(ideal.height/ratio);
1349 ideal.height = parseInt(ideal.width*ratio);
1352 // $$$ check this logic with large spreads
1353 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1358 // getSpreadSizeFromReduce()
1359 //______________________________________________________________________________
1360 // Returns the spread size calculated from the reduction factor for the given pages
1361 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1362 var spreadSize = {};
1363 // $$$ Scale this based on reduce?
1364 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1365 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1366 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1368 // $$$ Possibly incorrect -- we should make height "dominant"
1369 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1370 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1371 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1372 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1373 spreadSize.reduce = reduce;
1378 // twoPageGetAutofitReduce()
1379 //______________________________________________________________________________
1380 // Returns the current ideal reduction factor
1381 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1382 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1383 return spreadSize.reduce;
1386 // twoPageSetCursor()
1387 //______________________________________________________________________________
1388 // Set the cursor for two page view
1389 GnuBook.prototype.twoPageSetCursor = function() {
1390 // console.log('setting cursor');
1391 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1392 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1393 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1394 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1396 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1397 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1402 //______________________________________________________________________________
1403 // Returns the currently active index.
1404 GnuBook.prototype.currentIndex = function() {
1405 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1406 if (this.mode == this.constMode1up) {
1407 return this.firstIndex; // $$$ TODO page in center of view would be better
1408 } else if (this.mode == this.constMode2up) {
1409 // Only allow indices that are actually present in book
1410 return GnuBook.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1412 throw 'currentIndex called for unimplemented mode ' + this.mode;
1417 //______________________________________________________________________________
1418 // Flip the right page over onto the left
1419 GnuBook.prototype.right = function() {
1420 if ('rl' != this.pageProgression) {
1430 //______________________________________________________________________________
1431 // Flip to the rightmost page
1432 GnuBook.prototype.rightmost = function() {
1433 if ('rl' != this.pageProgression) {
1441 //______________________________________________________________________________
1442 // Flip the left page over onto the right.
1443 GnuBook.prototype.left = function() {
1444 if ('rl' != this.pageProgression) {
1454 //______________________________________________________________________________
1455 // Flip to the leftmost page
1456 GnuBook.prototype.leftmost = function() {
1457 if ('rl' != this.pageProgression) {
1465 //______________________________________________________________________________
1466 GnuBook.prototype.next = function() {
1467 if (2 == this.mode) {
1469 this.flipFwdToIndex(null);
1471 if (this.firstIndex < this.lastDisplayableIndex()) {
1472 this.jumpToIndex(this.firstIndex+1);
1478 //______________________________________________________________________________
1479 GnuBook.prototype.prev = function() {
1480 if (2 == this.mode) {
1482 this.flipBackToIndex(null);
1484 if (this.firstIndex >= 1) {
1485 this.jumpToIndex(this.firstIndex-1);
1490 GnuBook.prototype.first = function() {
1491 this.jumpToIndex(this.firstDisplayableIndex());
1494 GnuBook.prototype.last = function() {
1495 this.jumpToIndex(this.lastDisplayableIndex());
1498 // flipBackToIndex()
1499 //______________________________________________________________________________
1500 // to flip back one spread, pass index=null
1501 GnuBook.prototype.flipBackToIndex = function(index) {
1503 if (1 == this.mode) return;
1505 var leftIndex = this.twoPage.currentIndexL;
1507 if (this.animating) return;
1509 if (null != this.leafEdgeTmp) {
1510 alert('error: leafEdgeTmp should be null!');
1514 if (null == index) {
1515 index = leftIndex-2;
1517 //if (index<0) return;
1519 var previousIndices = this.getSpreadIndices(index);
1521 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1525 this.animating = true;
1527 if ('rl' != this.pageProgression) {
1528 // Assume LTR and we are going backward
1529 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1530 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1532 // RTL and going backward
1533 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1534 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1538 // flipLeftToRight()
1539 //______________________________________________________________________________
1540 // Flips the page on the left towards the page on the right
1541 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1543 var leftLeaf = this.twoPage.currentIndexL;
1545 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1546 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1547 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1549 var currWidthL = this.getPageWidth2UP(leftLeaf);
1550 var newWidthL = this.getPageWidth2UP(newIndexL);
1551 var newWidthR = this.getPageWidth2UP(newIndexR);
1553 var top = this.twoPageTop();
1554 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1556 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1557 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1559 //animation strategy:
1560 // 0. remove search highlight, if any.
1561 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1562 // of the left leaf and where the user clicked in the leaf edge.
1563 // Note that if this function was triggered by left() and not a
1564 // mouse click, the width of leafEdgeTmp is very small (zero px).
1565 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1566 // leftLeaf to width=0.
1567 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1568 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1569 // its new full width.
1570 // 4. After step 3 is finished, do the following:
1571 // - remove leafEdgeTmp from the dom.
1572 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1573 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1574 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1575 // and width=newLeafEdgeWidthL.
1576 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1577 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1578 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1579 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1580 // - prefetch new adjacent leafs.
1581 // - set up click handlers for both new left and right leafs.
1582 // - redraw the search highlight.
1583 // - update the pagenum box and the url.
1586 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1588 this.leafEdgeTmp = document.createElement('div');
1589 $(this.leafEdgeTmp).css({
1590 borderStyle: 'solid none solid solid',
1591 borderColor: 'rgb(51, 51, 34)',
1592 borderWidth: '1px 0px 1px 1px',
1593 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1594 width: leafEdgeTmpW + 'px',
1595 height: this.twoPage.height-1 + 'px',
1596 left: leftEdgeTmpLeft + 'px',
1598 position: 'absolute',
1600 }).appendTo('#GBtwopageview');
1602 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1603 $(this.leafEdgeL).css({
1604 width: newLeafEdgeWidthL+'px',
1605 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1608 // Left gets the offset of the current left leaf from the document
1609 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1610 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1611 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1613 // We change the left leaf to right positioning
1614 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1615 $(this.prefetchedImgs[leftLeaf]).css({
1620 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1621 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1625 this.removeSearchHilites();
1627 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1628 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1630 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1631 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1633 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1634 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1635 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1637 $(self.leafEdgeR).css({
1638 // Moves the right leaf edge
1639 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1640 left: gutter+newWidthR+'px'
1643 $(self.leafEdgeL).css({
1644 // Moves and resizes the left leaf edge
1645 width: newLeafEdgeWidthL+'px',
1646 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1649 // Resizes the brown border div
1650 $(self.twoPage.coverDiv).css({
1651 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1652 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1655 $(self.leafEdgeTmp).remove();
1656 self.leafEdgeTmp = null;
1658 // $$$ TODO refactor with opposite direction flip
1660 self.twoPage.currentIndexL = newIndexL;
1661 self.twoPage.currentIndexR = newIndexR;
1662 self.twoPage.scaledWL = newWidthL;
1663 self.twoPage.scaledWR = newWidthR;
1664 self.twoPage.gutter = gutter;
1666 self.firstIndex = self.twoPage.currentIndexL;
1667 self.displayedIndices = [newIndexL, newIndexR];
1668 self.pruneUnusedImgs();
1670 self.animating = false;
1672 self.updateSearchHilites2UP();
1673 self.updatePageNumBox2UP();
1675 // self.twoPagePlaceFlipAreas(); // No longer used
1676 self.setMouseHandlers2UP();
1677 self.twoPageSetCursor();
1679 if (self.animationFinishedCallback) {
1680 self.animationFinishedCallback();
1681 self.animationFinishedCallback = null;
1689 //______________________________________________________________________________
1690 // Whether we flip left or right is dependent on the page progression
1691 // to flip forward one spread, pass index=null
1692 GnuBook.prototype.flipFwdToIndex = function(index) {
1694 if (this.animating) return;
1696 if (null != this.leafEdgeTmp) {
1697 alert('error: leafEdgeTmp should be null!');
1701 if (null == index) {
1702 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1704 if (index > this.lastDisplayableIndex()) return;
1706 this.animating = true;
1708 var nextIndices = this.getSpreadIndices(index);
1710 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1712 if ('rl' != this.pageProgression) {
1713 // We did not specify RTL
1714 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1715 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1718 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1719 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1723 // flipRightToLeft(nextL, nextR, gutter)
1724 // $$$ better not to have to pass gutter in
1725 //______________________________________________________________________________
1726 // Flip from left to right and show the nextL and nextR indices on those sides
1727 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1728 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1729 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1730 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1731 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1733 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1735 var top = this.twoPageTop();
1736 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1738 var middle = this.twoPage.middle;
1739 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1741 this.leafEdgeTmp = document.createElement('div');
1742 $(this.leafEdgeTmp).css({
1743 borderStyle: 'solid none solid solid',
1744 borderColor: 'rgb(51, 51, 34)',
1745 borderWidth: '1px 0px 1px 1px',
1746 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1747 width: leafEdgeTmpW + 'px',
1748 height: this.twoPage.height-1 + 'px',
1749 left: gutter+scaledW+'px',
1751 position: 'absolute',
1753 }).appendTo('#GBtwopageview');
1755 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1756 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1758 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1759 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1760 var newWidthL = this.getPageWidth2UP(newIndexL);
1761 var newWidthR = this.getPageWidth2UP(newIndexR);
1763 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1765 var self = this; // closure-tastic!
1767 var speed = this.flipSpeed;
1769 this.removeSearchHilites();
1771 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1772 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1773 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1774 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1775 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1777 $(self.leafEdgeL).css({
1778 width: newLeafEdgeWidthL+'px',
1779 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1782 // Resizes the book cover
1783 $(self.twoPage.coverDiv).css({
1784 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1785 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1788 $(self.leafEdgeTmp).remove();
1789 self.leafEdgeTmp = null;
1791 self.twoPage.currentIndexL = newIndexL;
1792 self.twoPage.currentIndexR = newIndexR;
1793 self.twoPage.scaledWL = newWidthL;
1794 self.twoPage.scaledWR = newWidthR;
1795 self.twoPage.gutter = gutter;
1797 self.firstIndex = self.twoPage.currentIndexL;
1798 self.displayedIndices = [newIndexL, newIndexR];
1799 self.pruneUnusedImgs();
1801 self.animating = false;
1804 self.updateSearchHilites2UP();
1805 self.updatePageNumBox2UP();
1807 // self.twoPagePlaceFlipAreas(); // No longer used
1808 self.setMouseHandlers2UP();
1809 self.twoPageSetCursor();
1811 if (self.animationFinishedCallback) {
1812 self.animationFinishedCallback();
1813 self.animationFinishedCallback = null;
1819 // setMouseHandlers2UP
1820 //______________________________________________________________________________
1821 GnuBook.prototype.setMouseHandlers2UP = function() {
1823 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1828 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1835 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
1836 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
1843 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
1844 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
1847 e.data.self.right();
1853 //______________________________________________________________________________
1854 GnuBook.prototype.prefetchImg = function(index) {
1855 var pageURI = this.getPageURI(index);
1857 // Load image if not loaded or URI has changed (e.g. due to scaling)
1858 var loadImage = false;
1859 if (undefined == this.prefetchedImgs[index]) {
1860 //console.log('no image for ' + index);
1862 } else if (pageURI != this.prefetchedImgs[index].uri) {
1863 //console.log('uri changed for ' + index);
1868 //console.log('prefetching ' + index);
1869 var img = document.createElement("img");
1871 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
1872 this.prefetchedImgs[index] = img;
1877 // prepareFlipLeftToRight()
1879 //______________________________________________________________________________
1881 // Prepare to flip the left page towards the right. This corresponds to moving
1882 // backward when the page progression is left to right.
1883 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1885 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1887 this.prefetchImg(prevL);
1888 this.prefetchImg(prevR);
1890 var height = this.getPageHeight(prevL);
1891 var width = this.getPageWidth(prevL);
1892 var middle = this.twoPage.middle;
1893 var top = this.twoPageTop();
1894 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1896 // The gutter is the dividing line between the left and right pages.
1897 // It is offset from the middle to create the illusion of thickness to the pages
1898 var gutter = middle + this.gutterOffsetForIndex(prevL);
1900 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1901 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1902 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1905 position: 'absolute',
1906 left: gutter-scaledW+'px',
1907 right: '', // clear right property
1909 height: this.twoPage.height,
1910 width: scaledW+'px',
1911 backgroundColor: this.getPageBackgroundColor(prevL),
1912 borderRight: '1px solid black',
1916 $(this.prefetchedImgs[prevL]).css(leftCSS);
1918 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1920 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1923 position: 'absolute',
1927 height: this.twoPage.height,
1929 backgroundColor: this.getPageBackgroundColor(prevR),
1930 borderLeft: '1px solid black',
1934 $(this.prefetchedImgs[prevR]).css(rightCSS);
1936 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1940 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1941 // prepareFlipRightToLeft()
1942 //______________________________________________________________________________
1943 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1945 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1948 this.prefetchImg(nextL);
1949 this.prefetchImg(nextR);
1951 var height = this.getPageHeight(nextR);
1952 var width = this.getPageWidth(nextR);
1953 var middle = this.twoPage.middle;
1954 var top = this.twoPageTop();
1955 var scaledW = this.twoPage.height*width/height;
1957 var gutter = middle + this.gutterOffsetForIndex(nextL);
1959 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1960 $(this.prefetchedImgs[nextR]).css({
1961 position: 'absolute',
1964 backgroundColor: this.getPageBackgroundColor(nextR),
1965 height: this.twoPage.height,
1966 width: scaledW+'px',
1967 borderLeft: '1px solid black',
1971 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1973 height = this.getPageHeight(nextL);
1974 width = this.getPageWidth(nextL);
1975 scaledW = this.twoPage.height*width/height;
1977 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1978 $(this.prefetchedImgs[nextL]).css({
1979 position: 'absolute',
1980 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1982 backgroundColor: this.getPageBackgroundColor(nextL),
1983 height: this.twoPage.height,
1984 width: 0+'px', // Start at 0 width, then grow to the left
1985 borderRight: '1px solid black',
1989 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1993 // getNextLeafs() -- NOT RTL AWARE
1994 //______________________________________________________________________________
1995 // GnuBook.prototype.getNextLeafs = function(o) {
1996 // //TODO: we might have two left or two right leafs in a row (damaged book)
1997 // //For now, assume that leafs are contiguous.
1999 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2000 // o.L = this.twoPage.currentIndexL+2;
2001 // o.R = this.twoPage.currentIndexL+3;
2004 // getprevLeafs() -- NOT RTL AWARE
2005 //______________________________________________________________________________
2006 // GnuBook.prototype.getPrevLeafs = function(o) {
2007 // //TODO: we might have two left or two right leafs in a row (damaged book)
2008 // //For now, assume that leafs are contiguous.
2010 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2011 // o.L = this.twoPage.currentIndexL-2;
2012 // o.R = this.twoPage.currentIndexL-1;
2015 // pruneUnusedImgs()
2016 //______________________________________________________________________________
2017 GnuBook.prototype.pruneUnusedImgs = function() {
2018 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2019 for (var key in this.prefetchedImgs) {
2020 //console.log('key is ' + key);
2021 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2022 //console.log('removing key '+ key);
2023 $(this.prefetchedImgs[key]).remove();
2025 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2026 //console.log('deleting key '+ key);
2027 delete this.prefetchedImgs[key];
2033 //______________________________________________________________________________
2034 GnuBook.prototype.prefetch = function() {
2036 // prefetch visible pages first
2037 this.prefetchImg(this.twoPage.currentIndexL);
2038 this.prefetchImg(this.twoPage.currentIndexR);
2040 var adjacentPagesToLoad = 3;
2042 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2043 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2045 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2046 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2048 // Load images spreading out from current
2049 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2050 var goingDown = lowCurrent - i;
2051 if (goingDown >= start) {
2052 this.prefetchImg(goingDown);
2054 var goingUp = highCurrent + i;
2055 if (goingUp <= end) {
2056 this.prefetchImg(goingUp);
2061 var lim = this.twoPage.currentIndexL-4;
2063 lim = Math.max(lim, 0);
2064 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2065 this.prefetchImg(i);
2068 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2069 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2070 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2071 this.prefetchImg(i);
2077 // getPageWidth2UP()
2078 //______________________________________________________________________________
2079 GnuBook.prototype.getPageWidth2UP = function(index) {
2080 // We return the width based on the dominant height
2081 var height = this.getPageHeight(index);
2082 var width = this.getPageWidth(index);
2083 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2087 //______________________________________________________________________________
2088 GnuBook.prototype.search = function(term) {
2089 term = term.replace(/\//g, ' '); // strip slashes
2090 this.searchTerm = term;
2091 $('#GnuBookSearchScript').remove();
2092 var script = document.createElement("script");
2093 script.setAttribute('id', 'GnuBookSearchScript');
2094 script.setAttribute("type", "text/javascript");
2095 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
2096 document.getElementsByTagName('head')[0].appendChild(script);
2097 $('#GnuBookSearchBox').val(term);
2098 $('#GnuBookSearchResults').html('Searching...');
2101 // GBSearchCallback()
2102 //______________________________________________________________________________
2103 GnuBook.prototype.GBSearchCallback = function(txt) {
2105 if (jQuery.browser.msie) {
2106 var dom=new ActiveXObject("Microsoft.XMLDOM");
2110 var parser = new DOMParser();
2111 var dom = parser.parseFromString(txt, "text/xml");
2114 $('#GnuBookSearchResults').empty();
2115 $('#GnuBookSearchResults').append('<ul>');
2117 for (var key in this.searchResults) {
2118 if (null != this.searchResults[key].div) {
2119 $(this.searchResults[key].div).remove();
2121 delete this.searchResults[key];
2124 var pages = dom.getElementsByTagName('PAGE');
2126 if (0 == pages.length) {
2127 // $$$ it would be nice to echo the (sanitized) search result here
2128 $('#GnuBookSearchResults').append('<li>No search results found</li>');
2130 for (var i = 0; i < pages.length; i++){
2131 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2134 var re = new RegExp (/_(\d{4})/);
2135 var reMatch = re.exec(pages[i].getAttribute('file'));
2136 var index = parseInt(reMatch[1], 10);
2137 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2139 var children = pages[i].childNodes;
2141 for (var j=0; j<children.length; j++) {
2142 //console.log(j + ' - ' + children[j].nodeName);
2143 //console.log(children[j].firstChild.nodeValue);
2144 if ('CONTEXT' == children[j].nodeName) {
2145 context += children[j].firstChild.nodeValue;
2146 } else if ('WORD' == children[j].nodeName) {
2147 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2149 var index = this.leafNumToIndex(index);
2150 if (null != index) {
2151 //coordinates are [left, bottom, right, top, [baseline]]
2152 //we'll skip baseline for now...
2153 var coords = children[j].getAttribute('coords').split(',',4);
2154 if (4 == coords.length) {
2155 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
2160 var pageName = this.getPageName(index);
2161 //TODO: remove hardcoded instance name
2162 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
2165 $('#GnuBookSearchResults').append('</ul>');
2167 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2168 $('#GnuBookSearchBox').val(this.searchTerm);
2170 this.updateSearchHilites();
2173 // updateSearchHilites()
2174 //______________________________________________________________________________
2175 GnuBook.prototype.updateSearchHilites = function() {
2176 if (2 == this.mode) {
2177 this.updateSearchHilites2UP();
2179 this.updateSearchHilites1UP();
2183 // showSearchHilites1UP()
2184 //______________________________________________________________________________
2185 GnuBook.prototype.updateSearchHilites1UP = function() {
2187 for (var key in this.searchResults) {
2189 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2190 var result = this.searchResults[key];
2191 if(null == result.div) {
2192 result.div = document.createElement('div');
2193 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
2194 //console.log('appending ' + key);
2197 width: (result.r-result.l)/this.reduce + 'px',
2198 height: (result.b-result.t)/this.reduce + 'px',
2199 left: (result.l)/this.reduce + 'px',
2200 top: (result.t)/this.reduce +'px'
2204 //console.log(key + ' not displayed');
2205 this.searchResults[key].div=null;
2211 //______________________________________________________________________________
2212 // Returns the position of the gutter (line between the page images)
2213 GnuBook.prototype.twoPageGutter = function() {
2214 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2218 //______________________________________________________________________________
2219 // Returns the offset for the top of the page images
2220 GnuBook.prototype.twoPageTop = function() {
2221 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2224 // twoPageCoverWidth()
2225 //______________________________________________________________________________
2226 // Returns the width of the cover div given the total page width
2227 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2228 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2231 // twoPageGetViewCenter()
2232 //______________________________________________________________________________
2233 // Returns the percentage offset into twopageview div at the center of container div
2234 // { percentageX: float, percentageY: float }
2235 GnuBook.prototype.twoPageGetViewCenter = function() {
2238 var containerOffset = $('#GBcontainer').offset();
2239 var viewOffset = $('#GBtwopageview').offset();
2240 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2241 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2246 // twoPageCenterView(percentageX, percentageY)
2247 //______________________________________________________________________________
2248 // Centers the point given by percentage from left,top of twopageview
2249 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2250 if ('undefined' == typeof(percentageX)) {
2253 if ('undefined' == typeof(percentageY)) {
2257 var viewWidth = $('#GBtwopageview').width();
2258 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2259 var intoViewX = percentageX * viewWidth;
2261 var viewHeight = $('#GBtwopageview').height();
2262 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2263 var intoViewY = percentageY * viewHeight;
2265 if (viewWidth < containerClientWidth) {
2266 // Can fit width without scrollbars - center by adjusting offset
2267 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2269 // Need to scroll to center
2270 $('#GBtwopageview').css('left', 0);
2271 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2274 if (viewHeight < containerClientHeight) {
2275 // Fits with scrollbars - add offset
2276 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2278 $('#GBtwopageview').css('top', 0);
2279 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2283 // twoPageFlipAreaHeight
2284 //______________________________________________________________________________
2285 // Returns the integer height of the click-to-flip areas at the edges of the book
2286 GnuBook.prototype.twoPageFlipAreaHeight = function() {
2287 return parseInt(this.twoPage.height);
2290 // twoPageFlipAreaWidth
2291 //______________________________________________________________________________
2292 // Returns the integer width of the flip areas
2293 GnuBook.prototype.twoPageFlipAreaWidth = function() {
2294 var max = 100; // $$$ TODO base on view width?
2297 var width = this.twoPage.width * 0.15;
2298 return parseInt(GnuBook.util.clamp(width, min, max));
2301 // twoPageFlipAreaTop
2302 //______________________________________________________________________________
2303 // Returns integer top offset for flip areas
2304 GnuBook.prototype.twoPageFlipAreaTop = function() {
2305 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2308 // twoPageLeftFlipAreaLeft
2309 //______________________________________________________________________________
2310 // Left offset for left flip area
2311 GnuBook.prototype.twoPageLeftFlipAreaLeft = function() {
2312 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2315 // twoPageRightFlipAreaLeft
2316 //______________________________________________________________________________
2317 // Left offset for right flip area
2318 GnuBook.prototype.twoPageRightFlipAreaLeft = function() {
2319 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2322 // twoPagePlaceFlipAreas
2323 //______________________________________________________________________________
2324 // Readjusts position of flip areas based on current layout
2325 GnuBook.prototype.twoPagePlaceFlipAreas = function() {
2326 // We don't set top since it shouldn't change relative to view
2327 $(this.twoPage.leftFlipArea).css({
2328 left: this.twoPageLeftFlipAreaLeft() + 'px',
2329 width: this.twoPageFlipAreaWidth() + 'px'
2331 $(this.twoPage.rightFlipArea).css({
2332 left: this.twoPageRightFlipAreaLeft() + 'px',
2333 width: this.twoPageFlipAreaWidth() + 'px'
2337 // showSearchHilites2UP()
2338 //______________________________________________________________________________
2339 GnuBook.prototype.updateSearchHilites2UP = function() {
2341 for (var key in this.searchResults) {
2342 key = parseInt(key, 10);
2343 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2344 var result = this.searchResults[key];
2345 if(null == result.div) {
2346 result.div = document.createElement('div');
2347 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2348 //console.log('appending ' + key);
2351 // We calculate the reduction factor for the specific page because it can be different
2352 // for each page in the spread
2353 var height = this.getPageHeight(key);
2354 var width = this.getPageWidth(key)
2355 var reduce = this.twoPage.height/height;
2356 var scaledW = parseInt(width*reduce);
2358 var gutter = this.twoPageGutter();
2360 if ('L' == this.getPageSide(key)) {
2361 pageL = gutter-scaledW;
2365 var pageT = this.twoPageTop();
2368 width: (result.r-result.l)*reduce + 'px',
2369 height: (result.b-result.t)*reduce + 'px',
2370 left: pageL+(result.l)*reduce + 'px',
2371 top: pageT+(result.t)*reduce +'px'
2375 //console.log(key + ' not displayed');
2376 if (null != this.searchResults[key].div) {
2377 //console.log('removing ' + key);
2378 $(this.searchResults[key].div).remove();
2380 this.searchResults[key].div=null;
2385 // removeSearchHilites()
2386 //______________________________________________________________________________
2387 GnuBook.prototype.removeSearchHilites = function() {
2388 for (var key in this.searchResults) {
2389 if (null != this.searchResults[key].div) {
2390 $(this.searchResults[key].div).remove();
2391 this.searchResults[key].div=null;
2397 //______________________________________________________________________________
2398 GnuBook.prototype.printPage = function() {
2399 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2401 /* iframe implementation
2403 if (null != this.printPopup) { // check if already showing
2406 this.printPopup = document.createElement("div");
2407 $(this.printPopup).css({
2408 position: 'absolute',
2410 left: ($('#GBcontainer').width()-400)/2 + 'px',
2413 border: "3px double #999999",
2415 backgroundColor: "#fff"
2416 }).appendTo('#GnuBook');
2419 if (this.constMode1up == this.mode) {
2420 indexToPrint = this.firstIndex;
2422 indexToPrint = this.twoPage.currentIndexL;
2425 this.indexToPrint = indexToPrint;
2427 var htmlStr = '<div style="text-align: center;">';
2428 htmlStr = '<p style="text-align:center;"><b><a href="javascript:void(0);" onclick="window.frames[0].focus(); window.frames[0].print(); return false;">Click here to print this page</a></b></p>';
2429 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2430 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2431 //htmlStr += '<button class="GBicon rollover book_up" onclick="gb.updatePrintFrame(-1); return false;"></button> ';
2432 //htmlStr += '<button class="GBicon rollover book_down" onclick="gb.updatePrintFrame(1); return false;"></button>';
2433 htmlStr += '<a href="#" onclick="gb.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="gb.updatePrintFrame(1); return false;">Next</a>';
2435 htmlStr += '</div>';
2436 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2437 htmlStr += '</div>';
2439 this.printPopup.innerHTML = htmlStr;
2441 var iframe = document.createElement('iframe');
2442 iframe.id = 'printFrame';
2443 iframe.name = 'printFrame';
2444 iframe.width = '233px'; // 8.5 x 11 aspect
2445 iframe.height = '300px';
2447 var self = this; // closure
2449 $(iframe).load(function() {
2450 var doc = GnuBook.util.getIFrameDocument(this);
2451 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2454 $('#printDiv').prepend(iframe);
2458 // Get print URI from current indices and mode
2459 GnuBook.prototype.getPrintURI = function() {
2461 if (this.constMode2up == this.mode) {
2462 indexToPrint = this.twoPage.currentIndexL;
2464 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2467 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2468 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2469 + '&width=' + this.getPageWidth(indexToPrint) + '&height=' + this.getPageHeight(indexToPrint);
2471 if (this.constMode2up == this.mode) {
2472 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this.getPageWidth(this.twoPage.currentIndexR);
2473 options += '&height2=' + this.getPageHeight(this.twoPage.currentIndexR);
2474 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2476 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2479 return '/bookreader/print.php?' + options;
2482 /* iframe implementation
2483 GnuBook.prototype.getPrintFrameContent = function(index) {
2484 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2485 // 8.5x11 so we should end up not overflowing on either paper size.
2486 var paperAspect = 8.5 / 11;
2487 var imageAspect = this.getPageWidth(index) / this.getPageHeight(index);
2491 // Rotate if possible and appropriate, to get larger image size on printed page
2492 if (this.canRotatePage(index)) {
2493 if (imageAspect > 1 && imageAspect > paperAspect) {
2494 // more wide than square, and more wide than paper
2496 imageAspect = 1/imageAspect;
2501 if (imageAspect > paperAspect) {
2502 // wider than paper, fit width
2503 fitAttrs = 'width="95%"';
2505 // taller than paper, fit height
2506 fitAttrs = 'height="95%"';
2509 var imageURL = this.getPageURI(index, 1, rotate);
2510 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2511 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2512 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2513 iframeStr += '</div>';
2514 iframeStr += '</body></html>';
2519 GnuBook.prototype.updatePrintFrame = function(delta) {
2520 var newIndex = this.indexToPrint + delta;
2521 newIndex = GnuBook.util.clamp(newIndex, 0, this.numLeafs - 1);
2522 if (newIndex == this.indexToPrint) {
2525 this.indexToPrint = newIndex;
2526 var doc = GnuBook.util.getIFrameDocument($('#printFrame')[0]);
2527 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2532 //______________________________________________________________________________
2533 GnuBook.prototype.showEmbedCode = function() {
2534 if (null != this.embedPopup) { // check if already showing
2538 this.embedPopup = document.createElement("div");
2539 $(this.embedPopup).css({
2540 position: 'absolute',
2542 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2545 border: "3px double #999999",
2547 backgroundColor: "#fff"
2548 }).appendTo('#GnuBook');
2550 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2551 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>';
2552 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2553 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2555 this.embedPopup.innerHTML = htmlStr;
2556 $(this.embedPopup).find('input').bind('click', function() {
2562 //______________________________________________________________________________
2563 GnuBook.prototype.autoToggle = function() {
2565 var bComingFrom1up = false;
2566 if (2 != this.mode) {
2567 bComingFrom1up = true;
2571 // Change to autofit if book is too large
2572 if (this.reduce < this.twoPageGetAutofitReduce()) {
2577 if (null == this.autoTimer) {
2578 this.flipSpeed = 2000;
2580 // $$$ Draw events currently cause layout problems when they occur during animation.
2581 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2582 // we workaround for now by not triggering immediate animation in that case.
2583 // See https://bugs.launchpad.net/gnubook/+bug/328327
2584 if (('rl' == this.pageProgression) && bComingFrom1up) {
2585 // don't flip immediately -- wait until timer fires
2588 this.flipFwdToIndex();
2591 $('#GBtoolbar .play').hide();
2592 $('#GBtoolbar .pause').show();
2593 this.autoTimer=setInterval(function(){
2594 if (self.animating) {return;}
2596 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2597 self.flipBackToIndex(1); // $$$ really what we want?
2599 self.flipFwdToIndex();
2608 //______________________________________________________________________________
2609 // Stop autoplay mode, allowing animations to finish
2610 GnuBook.prototype.autoStop = function() {
2611 if (null != this.autoTimer) {
2612 clearInterval(this.autoTimer);
2613 this.flipSpeed = 'fast';
2614 $('#GBtoolbar .pause').hide();
2615 $('#GBtoolbar .play').show();
2616 this.autoTimer = null;
2620 // stopFlipAnimations
2621 //______________________________________________________________________________
2622 // Immediately stop flip animations. Callbacks are triggered.
2623 GnuBook.prototype.stopFlipAnimations = function() {
2625 this.autoStop(); // Clear timers
2627 // Stop animation, clear queue, trigger callbacks
2628 if (this.leafEdgeTmp) {
2629 $(this.leafEdgeTmp).stop(false, true);
2631 jQuery.each(this.prefetchedImgs, function() {
2632 $(this).stop(false, true);
2635 // And again since animations also queued in callbacks
2636 if (this.leafEdgeTmp) {
2637 $(this.leafEdgeTmp).stop(false, true);
2639 jQuery.each(this.prefetchedImgs, function() {
2640 $(this).stop(false, true);
2645 // keyboardNavigationIsDisabled(event)
2646 // - returns true if keyboard navigation should be disabled for the event
2647 //______________________________________________________________________________
2648 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2649 if (event.target.tagName == "INPUT") {
2655 // gutterOffsetForIndex
2656 //______________________________________________________________________________
2658 // Returns the gutter offset for the spread containing the given index.
2659 // This function supports RTL
2660 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2662 // To find the offset of the gutter from the middle we calculate our percentage distance
2663 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2664 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2666 // But then again for RTL it's the opposite
2667 if ('rl' == this.pageProgression) {
2675 //______________________________________________________________________________
2676 // Returns the width of the leaf edge div for the page with index given
2677 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2678 // $$$ could there be single pixel rounding errors for L vs R?
2679 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2680 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2682 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2686 // jumpIndexForLeftEdgePageX
2687 //______________________________________________________________________________
2688 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2689 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2690 if ('rl' != this.pageProgression) {
2691 // LTR - flipping backward
2692 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2694 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2695 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2699 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2700 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2705 // jumpIndexForRightEdgePageX
2706 //______________________________________________________________________________
2707 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2708 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2709 if ('rl' != this.pageProgression) {
2711 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2712 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2715 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2716 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2721 GnuBook.prototype.initToolbar = function(mode, ui) {
2723 $("#GnuBook").append("<div id='GBtoolbar'>"
2724 + "<span id='GBtoolbarbuttons' style='float: right'>"
2725 + "<button class='GBicon print rollover' /> <button class='GBicon rollover embed' />"
2726 + "<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>"
2727 + "<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>"
2728 + "<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>"
2729 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' />"
2733 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2734 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2735 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2736 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2737 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2738 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2741 + "<span id='#GBbooktitle'>"
2742 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
2746 this.updateToolbarZoom(this.reduce); // Pretty format
2748 if (ui == "embed") {
2749 $("#GnuBook a.logo").attr("target","_blank");
2752 // $$$ turn this into a member variable
2753 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2755 // We build in mode 2
2758 this.bindToolbarNavHandlers(jToolbar);
2760 // Setup tooltips -- later we could load these from a file for i18n
2761 var titles = { '.logo': 'Go to Archive.org',
2762 '.zoom_in': 'Zoom in',
2763 '.zoom_out': 'Zoom out',
2764 '.one_page_mode': 'One-page view',
2765 '.two_page_mode': 'Two-page view',
2766 '.print': 'Print this page',
2767 '.embed': 'Embed bookreader',
2768 '.book_left': 'Flip left',
2769 '.book_right': 'Flip right',
2770 '.book_up': 'Page up',
2771 '.book_down': 'Page down',
2774 '.book_top': 'First page',
2775 '.book_bottom': 'Last page'
2777 if ('rl' == this.pageProgression) {
2778 titles['.book_leftmost'] = 'Last page';
2779 titles['.book_rightmost'] = 'First page';
2781 titles['.book_leftmost'] = 'First page';
2782 titles['.book_rightmost'] = 'Last page';
2785 for (var icon in titles) {
2786 jToolbar.find(icon).attr('title', titles[icon]);
2789 // Hide mode buttons and autoplay if 2up is not available
2790 // $$$ if we end up with more than two modes we should show the applicable buttons
2791 if ( !this.canSwitchToMode(this.constMode2up) ) {
2792 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2795 // Switch to requested mode -- binds other click handlers
2796 this.switchToolbarMode(mode);
2801 // switchToolbarMode
2802 //______________________________________________________________________________
2803 // Update the toolbar for the given mode (changes navigation buttons)
2804 // $$$ we should soon split the toolbar out into its own module
2805 GnuBook.prototype.switchToolbarMode = function(mode) {
2808 $('#GBtoolbar .GBtoolbarmode2').hide();
2809 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2812 $('#GBtoolbar .GBtoolbarmode1').hide();
2813 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2817 // bindToolbarNavHandlers
2818 //______________________________________________________________________________
2819 // Binds the toolbar handlers
2820 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2822 jToolbar.find('.book_left').bind('click', function(e) {
2827 jToolbar.find('.book_right').bind('click', function(e) {
2832 jToolbar.find('.book_up').bind('click', function(e) {
2837 jToolbar.find('.book_down').bind('click', function(e) {
2842 jToolbar.find('.print').bind('click', function(e) {
2847 jToolbar.find('.embed').bind('click', function(e) {
2852 jToolbar.find('.play').bind('click', function(e) {
2857 jToolbar.find('.pause').bind('click', function(e) {
2862 jToolbar.find('.book_top').bind('click', function(e) {
2867 jToolbar.find('.book_bottom').bind('click', function(e) {
2872 jToolbar.find('.book_leftmost').bind('click', function(e) {
2877 jToolbar.find('.book_rightmost').bind('click', function(e) {
2883 // updateToolbarZoom(reduce)
2884 //______________________________________________________________________________
2885 // Update the displayed zoom factor based on reduction factor
2886 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2888 if (this.constMode2up == this.mode && this.twoPage.autofit) {
2891 value = (100 / reduce).toFixed(2);
2892 // Strip trailing zeroes and decimal if all zeroes
2893 value = value.replace(/0+$/,'');
2894 value = value.replace(/\.$/,'');
2897 $('#GBzoom').text(value);
2900 // firstDisplayableIndex
2901 //______________________________________________________________________________
2902 // Returns the index of the first visible page, dependent on the mode.
2903 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2904 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2905 GnuBook.prototype.firstDisplayableIndex = function() {
2906 if (this.mode != this.constMode2up) {
2910 if ('rl' != this.pageProgression) {
2912 if (this.getPageSide(0) == 'L') {
2919 if (this.getPageSide(0) == 'R') {
2927 // lastDisplayableIndex
2928 //______________________________________________________________________________
2929 // Returns the index of the last visible page, dependent on the mode.
2930 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2931 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2932 GnuBook.prototype.lastDisplayableIndex = function() {
2934 var lastIndex = this.numLeafs - 1;
2936 if (this.mode != this.constMode2up) {
2940 if ('rl' != this.pageProgression) {
2942 if (this.getPageSide(lastIndex) == 'R') {
2945 return lastIndex + 1;
2949 if (this.getPageSide(lastIndex) == 'L') {
2952 return lastIndex + 1;
2957 // shortTitle(maximumCharacters)
2959 // Returns a shortened version of the title with the maximum number of characters
2960 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2961 if (this.bookTitle.length < maximumCharacters) {
2962 return this.bookTitle;
2965 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2970 // Parameter related functions
2972 // updateFromParams(params)
2974 // Update ourselves from the params object.
2976 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2977 GnuBook.prototype.updateFromParams = function(params) {
2978 if ('undefined' != typeof(params.mode)) {
2979 this.switchMode(params.mode);
2983 if ('undefined' != typeof(params.searchTerm)) {
2984 if (this.searchTerm != params.searchTerm) {
2985 this.search(params.searchTerm);
2989 // $$$ process /zoom
2991 // We only respect page if index is not set
2992 if ('undefined' != typeof(params.index)) {
2993 if (params.index != this.currentIndex()) {
2994 this.jumpToIndex(params.index);
2996 } else if ('undefined' != typeof(params.page)) {
2997 // $$$ this assumes page numbers are unique
2998 if (params.page != this.getPageNum(this.currentIndex())) {
2999 this.jumpToPage(params.page);
3003 // $$$ process /region
3004 // $$$ process /highlight
3007 // paramsFromFragment(urlFragment)
3009 // Returns a object with configuration parametes from a URL fragment.
3011 // E.g paramsFromFragment(window.location.hash)
3012 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
3013 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3017 // For convenience we allow an initial # character (as from window.location.hash)
3018 // but don't require it
3019 if (urlFragment.substr(0,1) == '#') {
3020 urlFragment = urlFragment.substr(1);
3023 // Simple #nn syntax
3024 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3025 if ( !isNaN(oldStyleLeafNum) ) {
3026 params.index = oldStyleLeafNum;
3028 // Done processing if using old-style syntax
3032 // Split into key-value pairs
3033 var urlArray = urlFragment.split('/');
3035 for (var i = 0; i < urlArray.length; i += 2) {
3036 urlHash[urlArray[i]] = urlArray[i+1];
3040 if ('1up' == urlHash['mode']) {
3041 params.mode = this.constMode1up;
3042 } else if ('2up' == urlHash['mode']) {
3043 params.mode = this.constMode2up;
3047 if ('undefined' != typeof(urlHash['page'])) {
3048 // page was set -- may not be int
3049 params.page = urlHash['page'];
3052 // $$$ process /region
3053 // $$$ process /search
3055 if (urlHash['search'] != undefined) {
3056 params.searchTerm = GnuBook.util.decodeURIComponentPlus(urlHash['search']);
3059 // $$$ process /highlight
3064 // paramsFromCurrent()
3066 // Create a params object from the current parameters.
3067 GnuBook.prototype.paramsFromCurrent = function() {
3071 var index = this.currentIndex();
3072 var pageNum = this.getPageNum(index);
3073 if ((pageNum === 0) || pageNum) {
3074 params.page = pageNum;
3077 params.index = index;
3078 params.mode = this.mode;
3084 if (this.searchHighlightVisible()) {
3085 params.searchTerm = this.searchTerm;
3091 // fragmentFromParams(params)
3093 // Create a fragment string from the params object.
3094 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3095 GnuBook.prototype.fragmentFromParams = function(params) {
3096 var separator = '/';
3100 if ('undefined' != typeof(params.page)) {
3101 fragments.push('page', params.page);
3103 // Don't have page numbering -- use index instead
3104 fragments.push('page', 'n' + params.index);
3111 if ('undefined' != typeof(params.mode)) {
3112 if (params.mode == this.constMode1up) {
3113 fragments.push('mode', '1up');
3114 } else if (params.mode == this.constMode2up) {
3115 fragments.push('mode', '2up');
3117 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3122 if (params.searchTerm) {
3123 fragments.push('search', params.searchTerm);
3126 return GnuBook.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3129 // getPageIndex(pageNum)
3131 // Returns the *highest* index the given page number, or undefined
3132 GnuBook.prototype.getPageIndex = function(pageNum) {
3133 var pageIndices = this.getPageIndices(pageNum);
3135 if (pageIndices.length > 0) {
3136 return pageIndices[pageIndices.length - 1];
3142 // getPageIndices(pageNum)
3144 // Returns an array (possibly empty) of the indices with the given page number
3145 GnuBook.prototype.getPageIndices = function(pageNum) {
3148 // Check for special "nXX" page number
3149 if (pageNum.slice(0,1) == 'n') {
3151 var pageIntStr = pageNum.slice(1, pageNum.length);
3152 var pageIndex = parseInt(pageIntStr);
3153 indices.push(pageIndex);
3156 // Do nothing... will run through page names and see if one matches
3161 for (i=0; i<this.numLeafs; i++) {
3162 if (this.getPageNum(i) == pageNum) {
3170 // getPageName(index)
3172 // Returns the name of the page as it should be displayed in the user interface
3173 GnuBook.prototype.getPageName = function(index) {
3174 return 'Page ' + this.getPageNum(index);
3177 // updateLocationHash
3179 // Update the location hash from the current parameters. Call this instead of manually
3180 // using window.location.replace
3181 GnuBook.prototype.updateLocationHash = function() {
3182 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3183 window.location.replace(newHash);
3185 // This is the variable checked in the timer. Only user-generated changes
3186 // to the URL will trigger the event.
3187 this.oldLocationHash = newHash;
3190 // startLocationPolling
3192 // Starts polling of window.location to see hash fragment changes
3193 GnuBook.prototype.startLocationPolling = function() {
3194 var self = this; // remember who I am
3195 self.oldLocationHash = window.location.hash;
3197 if (this.locationPollId) {
3198 clearInterval(this.locationPollID);
3199 this.locationPollId = null;
3202 this.locationPollId = setInterval(function() {
3203 var newHash = window.location.hash;
3204 if (newHash != self.oldLocationHash) {
3205 if (newHash != self.oldUserHash) { // Only process new user hash once
3206 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3208 // Queue change if animating
3209 if (self.animating) {
3211 self.animationFinishedCallback = function() {
3212 self.updateFromParams(self.paramsFromFragment(newHash));
3214 } else { // update immediately
3215 self.updateFromParams(self.paramsFromFragment(newHash));
3217 self.oldUserHash = newHash;
3225 // Returns true if we can switch to the requested mode
3226 GnuBook.prototype.canSwitchToMode = function(mode) {
3227 if (mode == this.constMode2up) {
3228 // check there are enough pages to display
3229 // $$$ this is a workaround for the mis-feature that we can't display
3230 // short books in 2up mode
3231 if (this.numLeafs < 6) {
3239 // searchHighlightVisible
3241 // Returns true if a search highlight is currently being displayed
3242 GnuBook.prototype.searchHighlightVisible = function() {
3243 if (this.constMode2up == this.mode) {
3244 if (this.searchResults[this.twoPage.currentIndexL]
3245 || this.searchResults[this.twoPage.currentIndexR]) {
3249 if (this.searchResults[this.currentIndex()]) {
3256 // getPageBackgroundColor
3258 // Returns a CSS property string for the background color for the given page
3259 // $$$ turn into regular CSS?
3260 GnuBook.prototype.getPageBackgroundColor = function(index) {
3261 if (index >= 0 && index < this.numLeafs) {
3263 return this.pageDefaultBackgroundColor;
3269 // Library functions
3271 clamp: function(value, min, max) {
3272 return Math.min(Math.max(value, min), max);
3275 getIFrameDocument: function(iframe) {
3276 // Adapted from http://xkr.us/articles/dom/iframe-document/
3277 var outer = (iframe.contentWindow || iframe.contentDocument);
3278 return (outer.document || outer);
3281 decodeURIComponentPlus: function(value) {
3282 // Decodes a URI component and converts '+' to ' '
3283 return decodeURIComponent(value).replace(/\+/g, ' ');
3286 encodeURIComponentPlus: function(value) {
3287 // Encodes a URI component and converts ' ' to '+'
3288 return encodeURIComponent(value).replace(/%20/g, '+');
3290 // The final property here must NOT have a comma after it - IE7