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;
558 if (indexL < 0) { // off end of book
559 indexL = this.twoPage.currentIndexR;
562 var heightL = this.getPageHeight(indexL);
563 var widthL = this.getPageWidth(indexL);
565 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
566 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
567 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
568 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
569 //console.log(leafEdgeWidthL);
571 var middle = this.twoPage.middle; // $$$ getter instead?
572 var top = this.twoPageTop();
573 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
575 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
576 this.twoPage.gutter = this.twoPageGutter();
578 this.prefetchImg(indexL);
579 $(this.prefetchedImgs[indexL]).css({
580 position: 'absolute',
581 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
584 backgroundColor: 'rgb(234, 226, 205)',
585 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
586 width: this.twoPage.scaledWL + 'px',
587 borderRight: '1px solid black',
589 }).appendTo('#GBtwopageview');
591 var indexR = this.twoPage.currentIndexR;
592 var heightR = this.getPageHeight(indexR);
593 var widthR = this.getPageWidth(indexR);
595 // $$$ should use getwidth2up?
596 //var scaledWR = this.twoPage.height*widthR/heightR;
597 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
598 this.prefetchImg(indexR);
599 $(this.prefetchedImgs[indexR]).css({
600 position: 'absolute',
601 left: this.twoPage.gutter+'px',
604 backgroundColor: 'rgb(234, 226, 205)',
605 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
606 width: this.twoPage.scaledWR + 'px',
607 borderLeft: '1px solid black',
609 }).appendTo('#GBtwopageview');
612 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
613 this.setMouseHandlers2UP();
614 this.twoPageSetCursor();
616 this.updatePageNumBox2UP();
617 this.updateToolbarZoom(this.reduce);
619 // this.twoPagePlaceFlipAreas(); // No longer used
623 // updatePageNumBox2UP
624 //______________________________________________________________________________
625 GnuBook.prototype.updatePageNumBox2UP = function() {
626 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
627 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
629 $("#GBpagenum").val('');
631 this.updateLocationHash();
635 //______________________________________________________________________________
636 GnuBook.prototype.loadLeafs = function() {
640 if (null == this.timer) {
641 this.timer=setTimeout(function(){self.drawLeafs()},250);
643 clearTimeout(this.timer);
644 this.timer=setTimeout(function(){self.drawLeafs()},250);
650 // Pass 1 to zoom in, anything else to zoom out
651 //______________________________________________________________________________
652 GnuBook.prototype.zoom = function(direction) {
654 case this.constMode1up:
655 return this.zoom1up(direction);
656 case this.constMode2up:
657 return this.zoom2up(direction);
662 //______________________________________________________________________________
663 GnuBook.prototype.zoom1up = function(dir) {
664 if (2 == this.mode) { //can only zoom in 1-page mode
669 // $$$ with flexible zoom we could "snap" to /2 page reductions
670 // for better scaling
672 if (this.reduce <= 0.5) return;
673 this.reduce*=0.5; //zoom in
675 if (this.reduce >= 8) return;
676 this.reduce*=2; //zoom out
679 this.resizePageView();
681 $('#GBpageview').empty()
682 this.displayedIndices = [];
685 this.updateToolbarZoom(this.reduce);
689 //______________________________________________________________________________
690 GnuBook.prototype.resizePageView = function() {
693 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
694 var viewWidth = $('#GBcontainer').attr('clientWidth');
696 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
697 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
698 var oldPageViewHeight = $('#GBpageview').height();
699 var oldPageViewWidth = $('#GBpageview').width();
701 var oldCenterY = this.centerY1up();
702 var oldCenterX = this.centerX1up();
704 if (0 != oldPageViewHeight) {
705 var scrollRatio = oldCenterY / oldPageViewHeight;
710 for (i=0; i<this.numLeafs; i++) {
711 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
712 var width = parseInt(this.getPageWidth(i)/this.reduce);
713 if (width>viewWidth) viewWidth=width;
715 $('#GBpageview').height(viewHeight);
716 $('#GBpageview').width(viewWidth);
718 var newCenterY = scrollRatio*viewHeight;
719 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
720 $('#GBcontainer').attr('scrollTop', newTop);
722 // We use clientWidth here to avoid miscalculating due to scroll bar
723 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
724 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
725 newLeft = Math.max(newLeft, 0);
726 $('#GBcontainer').attr('scrollLeft', newLeft);
727 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
729 //this.centerPageView();
735 //______________________________________________________________________________
736 // Returns the current offset of the viewport center in scaled document coordinates.
737 GnuBook.prototype.centerX1up = function() {
739 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
740 centerX = $('#GBpageview').width();
742 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
744 centerX = Math.floor(centerX);
749 //______________________________________________________________________________
750 // Returns the current offset of the viewport center in scaled document coordinates.
751 GnuBook.prototype.centerY1up = function() {
752 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
753 return Math.floor(centerY);
757 //______________________________________________________________________________
758 GnuBook.prototype.centerPageView = function() {
760 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
761 var clientWidth = $('#GBcontainer').attr('clientWidth');
762 //console.log('sW='+scrollWidth+' cW='+clientWidth);
763 if (scrollWidth > clientWidth) {
764 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
769 // zoom2up(direction)
770 //______________________________________________________________________________
771 GnuBook.prototype.zoom2up = function(direction) {
773 // Hard stop autoplay
774 this.stopFlipAnimations();
776 // Get new zoom state
777 var newZoom = this.twoPageNextReduce(this.reduce, direction);
778 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
781 this.twoPage.autofit = newZoom.autofit;
782 this.reduce = newZoom.reduce;
784 // Preserve view center position
785 var oldCenter = this.twoPageGetViewCenter();
787 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
788 // $$$ An improvement would be to use the low res image until the larger one is loaded.
789 if (1 == direction) {
790 for (var img in this.prefetchedImgs) {
791 delete this.prefetchedImgs[img];
795 // Prepare view with new center to minimize visual glitches
796 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
800 // quantizeReduce(reduce)
801 //______________________________________________________________________________
802 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
803 GnuBook.prototype.quantizeReduce = function(reduce) {
804 var quantized = this.reductionFactors[0];
805 var distance = Math.abs(reduce - quantized);
806 for (var i = 1; i < this.reductionFactors.length; i++) {
807 newDistance = Math.abs(reduce - this.reductionFactors[i]);
808 if (newDistance < distance) {
809 distance = newDistance;
810 quantized = this.reductionFactors[i];
817 // twoPageNextReduce()
818 //______________________________________________________________________________
819 // Returns the next reduction level
820 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
822 var autofitReduce = this.twoPageGetAutofitReduce();
824 if (0 == direction) { // autofit
825 result.autofit = true;
826 result.reduce = autofitReduce;
828 } else if (1 == direction) { // zoom in
829 var newReduce = this.reductionFactors[0];
831 for (var i = 1; i < this.reductionFactors.length; i++) {
832 if (this.reductionFactors[i] < reduce) {
833 newReduce = this.reductionFactors[i];
837 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
839 result.autofit = true;
840 result.reduce = autofitReduce;
842 result.autofit = false;
843 result.reduce = newReduce;
847 var lastIndex = this.reductionFactors.length - 1;
848 var newReduce = this.reductionFactors[lastIndex];
850 for (var i = lastIndex; i >= 0; i--) {
851 if (this.reductionFactors[i] > reduce) {
852 newReduce = this.reductionFactors[i];
856 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
858 result.autofit = true;
859 result.reduce = autofitReduce;
861 result.autofit = false;
862 result.reduce = newReduce;
870 //______________________________________________________________________________
871 // Attempts to jump to page. Returns true if page could be found, false otherwise.
872 GnuBook.prototype.jumpToPage = function(pageNum) {
874 var pageIndex = this.getPageIndex(pageNum);
876 if ('undefined' != typeof(pageIndex)) {
879 this.jumpToIndex(pageIndex);
880 $('#GBcontainer').attr('scrollTop', leafTop);
889 //______________________________________________________________________________
890 GnuBook.prototype.jumpToIndex = function(index) {
892 if (2 == this.mode) {
895 // By checking against min/max we do nothing if requested index
897 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
898 this.flipBackToIndex(index);
899 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
900 this.flipFwdToIndex(index);
907 for (i=0; i<index; i++) {
908 h = parseInt(this.getPageHeight(i)/this.reduce);
909 leafTop += h + this.padding;
911 //$('#GBcontainer').attr('scrollTop', leafTop);
912 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
919 //______________________________________________________________________________
920 GnuBook.prototype.switchMode = function(mode) {
922 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
924 if (mode == this.mode) return;
926 if (!this.canSwitchToMode(mode)) {
931 this.removeSearchHilites();
935 this.switchToolbarMode(mode);
937 // $$$ TODO preserve center of view when switching between mode
938 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
941 this.reduce = this.quantizeReduce(this.reduce);
942 this.prepareOnePageView();
944 this.twoPage.autofit = false; // Take zoom level from other mode
945 this.reduce = this.quantizeReduce(this.reduce);
946 this.prepareTwoPageView();
947 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
952 //prepareOnePageView()
953 //______________________________________________________________________________
954 GnuBook.prototype.prepareOnePageView = function() {
956 // var startLeaf = this.displayedIndices[0];
957 var startLeaf = this.currentIndex();
959 $('#GBcontainer').empty();
960 $('#GBcontainer').css({
965 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
967 this.resizePageView();
969 this.jumpToIndex(startLeaf);
970 this.displayedIndices = [];
972 this.drawLeafsOnePage();
974 // Bind mouse handlers
975 // Disable mouse click to avoid selected/highlighted page images - bug 354239
976 gbPageView.bind('mousedown', function(e) {
977 // $$$ check here for right-click and don't disable. Also use jQuery style
978 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
981 // Special hack for IE7
982 gbPageView[0].onselectstart = function(e) { return false; };
985 // prepareTwoPageView()
986 //______________________________________________________________________________
987 // Some decisions about two page view:
989 // Both pages will be displayed at the same height, even if they were different physical/scanned
990 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
991 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
992 // aspect ratio to determine the height.
994 // The two page view div is resized to keep the middle of the book in the middle of the div
995 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
996 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
997 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
998 $('#GBcontainer').empty();
999 $('#GBcontainer').css('overflow', 'auto');
1001 // We want to display two facing pages. We may be missing
1002 // one side of the spread because it is the first/last leaf,
1003 // foldouts, missing pages, etc
1005 //var targetLeaf = this.displayedIndices[0];
1006 var targetLeaf = this.firstIndex;
1008 if (targetLeaf < this.firstDisplayableIndex()) {
1009 targetLeaf = this.firstDisplayableIndex();
1012 if (targetLeaf > this.lastDisplayableIndex()) {
1013 targetLeaf = this.lastDisplayableIndex();
1016 //this.twoPage.currentIndexL = null;
1017 //this.twoPage.currentIndexR = null;
1018 //this.pruneUnusedImgs();
1020 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1021 this.twoPage.currentIndexL = currentSpreadIndices[0];
1022 this.twoPage.currentIndexR = currentSpreadIndices[1];
1023 this.firstIndex = this.twoPage.currentIndexL;
1025 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1027 this.pruneUnusedImgs();
1028 this.prefetch(); // Preload images or reload if scaling has changed
1030 //console.dir(this.twoPage);
1032 // Add the two page view
1033 // $$$ Can we get everything set up and then append?
1034 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
1036 // $$$ calculate first then set
1037 $('#GBtwopageview').css( {
1038 height: this.twoPage.totalHeight + 'px',
1039 width: this.twoPage.totalWidth + 'px',
1040 position: 'absolute'
1043 // If there will not be scrollbars (e.g. when zooming out) we center the book
1044 // since otherwise the book will be stuck off-center
1045 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
1046 centerPercentageX = 0.5;
1048 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
1049 centerPercentageY = 0.5;
1052 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1054 this.twoPage.coverDiv = document.createElement('div');
1055 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
1056 border: '1px solid rgb(68, 25, 17)',
1057 width: this.twoPage.bookCoverDivWidth + 'px',
1058 height: this.twoPage.bookCoverDivHeight+'px',
1059 visibility: 'visible',
1060 position: 'absolute',
1061 backgroundColor: '#663929',
1062 left: this.twoPage.bookCoverDivLeft + 'px',
1063 top: this.twoPage.bookCoverDivTop+'px',
1064 MozBorderRadiusTopleft: '7px',
1065 MozBorderRadiusTopright: '7px',
1066 MozBorderRadiusBottomright: '7px',
1067 MozBorderRadiusBottomleft: '7px'
1068 }).appendTo('#GBtwopageview');
1070 this.leafEdgeR = document.createElement('div');
1071 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1072 $(this.leafEdgeR).css({
1073 borderStyle: 'solid solid solid none',
1074 borderColor: 'rgb(51, 51, 34)',
1075 borderWidth: '1px 1px 1px 0px',
1076 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1077 width: this.twoPage.leafEdgeWidthR + 'px',
1078 height: this.twoPage.height-1 + 'px',
1080 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1081 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1082 position: 'absolute'
1083 }).appendTo('#GBtwopageview');
1085 this.leafEdgeL = document.createElement('div');
1086 this.leafEdgeL.className = 'leafEdgeL';
1087 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1088 borderStyle: 'solid none solid solid',
1089 borderColor: 'rgb(51, 51, 34)',
1090 borderWidth: '1px 0px 1px 1px',
1091 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1092 width: this.twoPage.leafEdgeWidthL + 'px',
1093 height: this.twoPage.height-1 + 'px',
1094 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1095 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1096 position: 'absolute'
1097 }).appendTo('#GBtwopageview');
1099 div = document.createElement('div');
1100 $(div).attr('id', 'GBbookspine').css({
1101 border: '1px solid rgb(68, 25, 17)',
1102 width: this.twoPage.bookSpineDivWidth+'px',
1103 height: this.twoPage.bookSpineDivHeight+'px',
1104 position: 'absolute',
1105 backgroundColor: 'rgb(68, 25, 17)',
1106 left: this.twoPage.bookSpineDivLeft+'px',
1107 top: this.twoPage.bookSpineDivTop+'px'
1108 }).appendTo('#GBtwopageview');
1110 var self = this; // for closure
1112 /* Flip areas no longer used
1113 this.twoPage.leftFlipArea = document.createElement('div');
1114 this.twoPage.leftFlipArea.className = 'GBfliparea';
1115 $(this.twoPage.leftFlipArea).attr('id', 'GBleftflip').css({
1117 width: this.twoPageFlipAreaWidth() + 'px',
1118 height: this.twoPageFlipAreaHeight() + 'px',
1119 position: 'absolute',
1120 left: this.twoPageLeftFlipAreaLeft() + 'px',
1121 top: this.twoPageFlipAreaTop() + 'px',
1124 }).bind('click', function(e) {
1126 }).bind('mousedown', function(e) {
1128 }).appendTo('#GBtwopageview');
1130 this.twoPage.rightFlipArea = document.createElement('div');
1131 this.twoPage.rightFlipArea.className = 'GBfliparea';
1132 $(this.twoPage.rightFlipArea).attr('id', 'GBrightflip').css({
1134 width: this.twoPageFlipAreaWidth() + 'px',
1135 height: this.twoPageFlipAreaHeight() + 'px',
1136 position: 'absolute',
1137 left: this.twoPageRightFlipAreaLeft() + 'px',
1138 top: this.twoPageFlipAreaTop() + 'px',
1141 }).bind('click', function(e) {
1143 }).bind('mousedown', function(e) {
1145 }).appendTo('#GBtwopageview');
1148 this.prepareTwoPagePopUp();
1150 this.displayedIndices = [];
1152 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1153 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1155 this.drawLeafsTwoPage();
1156 this.updateSearchHilites2UP();
1157 this.updateToolbarZoom(this.reduce);
1162 // prepareTwoPagePopUp()
1164 // This function prepares the "View Page n" popup that shows while the mouse is
1165 // over the left/right "stack of sheets" edges. It also binds the mouse
1166 // events for these divs.
1167 //______________________________________________________________________________
1168 GnuBook.prototype.prepareTwoPagePopUp = function() {
1170 this.twoPagePopUp = document.createElement('div');
1171 $(this.twoPagePopUp).css({
1172 border: '1px solid black',
1174 position: 'absolute',
1175 fontFamily: 'sans-serif',
1178 backgroundColor: 'rgb(255, 255, 238)',
1180 }).appendTo('#GBcontainer');
1181 $(this.twoPagePopUp).hide();
1183 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1184 $(e.data.twoPagePopUp).show();
1187 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1188 $(e.data.twoPagePopUp).hide();
1191 $(this.leafEdgeL).bind('click', this, function(e) {
1193 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1194 e.data.jumpToIndex(jumpIndex);
1197 $(this.leafEdgeR).bind('click', this, function(e) {
1199 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1200 e.data.jumpToIndex(jumpIndex);
1203 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1205 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1206 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1208 // $$$ TODO: Make sure popup is positioned so that it is in view
1209 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1210 $(e.data.twoPagePopUp).css({
1211 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1212 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1216 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1218 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1219 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1221 // $$$ TODO: Make sure popup is positioned so that it is in view
1222 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1223 $(e.data.twoPagePopUp).css({
1224 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1225 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1230 // calculateSpreadSize()
1231 //______________________________________________________________________________
1232 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1233 // this.twoPage.currentIndexR
1234 // This function sets this.twoPage.height, twoPage.width
1236 GnuBook.prototype.calculateSpreadSize = function() {
1238 var firstIndex = this.twoPage.currentIndexL;
1239 var secondIndex = this.twoPage.currentIndexR;
1240 //console.log('first page is ' + firstIndex);
1242 // Calculate page sizes and total leaf width
1244 if ( this.twoPage.autofit) {
1245 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1247 // set based on reduction factor
1248 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1251 // Both pages together
1252 this.twoPage.height = spreadSize.height;
1253 this.twoPage.width = spreadSize.width;
1256 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1257 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1260 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1261 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1262 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1266 // The width of the book cover div. The combined width of both pages, twice the width
1267 // of the book cover internal padding (2*10) and the page edges
1268 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1269 // The height of the book cover div
1270 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1273 // We calculate the total width and height for the div so that we can make the book
1275 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1276 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1277 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1278 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1279 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1280 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1282 // We want to minimize the unused space in two-up mode (maximize the amount of page
1283 // shown). We give width to the leaf edges and these widths change (though the sum
1284 // of the two remains constant) as we flip through the book. With the book
1285 // cover centered and fixed in the GBcontainer div the page images will meet
1286 // at the "gutter" which is generally offset from the center.
1287 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1288 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1290 // The left edge of the book cover moves depending on the width of the pages
1291 // $$$ change to getter
1292 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1293 // The top edge of the book cover stays a fixed distance from the top
1294 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1297 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1298 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1299 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1302 this.reduce = spreadSize.reduce; // $$$ really set this here?
1305 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1308 // We check which page is closest to a "normal" page and use that to set the height
1309 // for both pages. This means that foldouts and other odd size pages will be displayed
1310 // smaller than the nominal zoom amount.
1311 var canon5Dratio = 1.5;
1314 height: this.getPageHeight(firstIndex),
1315 width: this.getPageWidth(firstIndex)
1319 height: this.getPageHeight(secondIndex),
1320 width: this.getPageWidth(secondIndex)
1323 var firstIndexRatio = first.height / first.width;
1324 var secondIndexRatio = second.height / second.width;
1325 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1328 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1329 ratio = firstIndexRatio;
1330 //console.log('using firstIndexRatio ' + ratio);
1332 ratio = secondIndexRatio;
1333 //console.log('using secondIndexRatio ' + ratio);
1336 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1337 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1338 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1340 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1341 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1343 ideal.width = ($('#GBcontainer').width() - widthOutsidePages) >> 1;
1344 ideal.width -= 10; // $$$ fudge factor
1345 ideal.height = $('#GBcontainer').height() - heightOutsidePages;
1346 ideal.height -= 20; // fudge factor
1347 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1349 if (ideal.height/ratio <= ideal.width) {
1351 ideal.width = parseInt(ideal.height/ratio);
1354 ideal.height = parseInt(ideal.width*ratio);
1357 // $$$ check this logic with large spreads
1358 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1363 // getSpreadSizeFromReduce()
1364 //______________________________________________________________________________
1365 // Returns the spread size calculated from the reduction factor for the given pages
1366 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1367 var spreadSize = {};
1368 // $$$ Scale this based on reduce?
1369 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1370 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1371 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1373 // $$$ Possibly incorrect -- we should make height "dominant"
1374 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1375 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1376 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1377 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1378 spreadSize.reduce = reduce;
1383 // twoPageGetAutofitReduce()
1384 //______________________________________________________________________________
1385 // Returns the current ideal reduction factor
1386 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1387 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1388 return spreadSize.reduce;
1391 // twoPageSetCursor()
1392 //______________________________________________________________________________
1393 // Set the cursor for two page view
1394 GnuBook.prototype.twoPageSetCursor = function() {
1395 // console.log('setting cursor');
1396 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1397 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1398 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1399 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1401 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1402 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1407 //______________________________________________________________________________
1408 // Returns the currently active index.
1409 GnuBook.prototype.currentIndex = function() {
1410 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1411 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1412 return this.firstIndex;
1414 throw 'currentIndex called for unimplemented mode ' + this.mode;
1419 //______________________________________________________________________________
1420 // Flip the right page over onto the left
1421 GnuBook.prototype.right = function() {
1422 if ('rl' != this.pageProgression) {
1432 //______________________________________________________________________________
1433 // Flip to the rightmost page
1434 GnuBook.prototype.rightmost = function() {
1435 if ('rl' != this.pageProgression) {
1443 //______________________________________________________________________________
1444 // Flip the left page over onto the right.
1445 GnuBook.prototype.left = function() {
1446 if ('rl' != this.pageProgression) {
1456 //______________________________________________________________________________
1457 // Flip to the leftmost page
1458 GnuBook.prototype.leftmost = function() {
1459 if ('rl' != this.pageProgression) {
1467 //______________________________________________________________________________
1468 GnuBook.prototype.next = function() {
1469 if (2 == this.mode) {
1471 this.flipFwdToIndex(null);
1473 if (this.firstIndex < this.lastDisplayableIndex()) {
1474 this.jumpToIndex(this.firstIndex+1);
1480 //______________________________________________________________________________
1481 GnuBook.prototype.prev = function() {
1482 if (2 == this.mode) {
1484 this.flipBackToIndex(null);
1486 if (this.firstIndex >= 1) {
1487 this.jumpToIndex(this.firstIndex-1);
1492 GnuBook.prototype.first = function() {
1494 this.jumpToIndex(this.firstDisplayableIndex());
1498 if (2 == this.mode) {
1499 this.jumpToIndex(2);
1502 this.jumpToIndex(0);
1506 GnuBook.prototype.last = function() {
1508 this.jumpToIndex(this.lastDisplayableIndex());
1512 if (2 == this.mode) {
1513 this.jumpToIndex(this.lastDisplayableIndex());
1516 this.jumpToIndex(this.lastDisplayableIndex());
1520 // flipBackToIndex()
1521 //______________________________________________________________________________
1522 // to flip back one spread, pass index=null
1523 GnuBook.prototype.flipBackToIndex = function(index) {
1525 console.log('flipBackToIndex ' + index);
1527 if (1 == this.mode) return;
1529 var leftIndex = this.twoPage.currentIndexL;
1531 // $$$ Need to change this to be able to see first spread.
1532 // See https://bugs.launchpad.net/gnubook/+bug/296788
1533 //if (leftIndex <= self.firstDisplayableIndex()) return; // XXX
1534 if (this.animating) return;
1536 if (null != this.leafEdgeTmp) {
1537 alert('error: leafEdgeTmp should be null!');
1541 if (null == index) {
1542 index = leftIndex-2;
1544 //if (index<0) return;
1546 var previousIndices = this.getSpreadIndices(index);
1548 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1553 console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1555 this.animating = true;
1557 if ('rl' != this.pageProgression) {
1558 // Assume LTR and we are going backward
1559 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1560 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1562 // RTL and going backward
1563 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1564 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1568 // flipLeftToRight()
1569 //______________________________________________________________________________
1570 // Flips the page on the left towards the page on the right
1571 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1573 var leftLeaf = this.twoPage.currentIndexL;
1575 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1576 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1577 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1579 var currWidthL = this.getPageWidth2UP(leftLeaf);
1580 var newWidthL = this.getPageWidth2UP(newIndexL);
1581 var newWidthR = this.getPageWidth2UP(newIndexR);
1583 var top = this.twoPageTop();
1584 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1586 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1587 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1589 //animation strategy:
1590 // 0. remove search highlight, if any.
1591 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1592 // of the left leaf and where the user clicked in the leaf edge.
1593 // Note that if this function was triggered by left() and not a
1594 // mouse click, the width of leafEdgeTmp is very small (zero px).
1595 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1596 // leftLeaf to width=0.
1597 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1598 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1599 // its new full width.
1600 // 4. After step 3 is finished, do the following:
1601 // - remove leafEdgeTmp from the dom.
1602 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1603 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1604 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1605 // and width=newLeafEdgeWidthL.
1606 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1607 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1608 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1609 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1610 // - prefetch new adjacent leafs.
1611 // - set up click handlers for both new left and right leafs.
1612 // - redraw the search highlight.
1613 // - update the pagenum box and the url.
1616 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1618 this.leafEdgeTmp = document.createElement('div');
1619 $(this.leafEdgeTmp).css({
1620 borderStyle: 'solid none solid solid',
1621 borderColor: 'rgb(51, 51, 34)',
1622 borderWidth: '1px 0px 1px 1px',
1623 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1624 width: leafEdgeTmpW + 'px',
1625 height: this.twoPage.height-1 + 'px',
1626 left: leftEdgeTmpLeft + 'px',
1628 position: 'absolute',
1630 }).appendTo('#GBtwopageview');
1632 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1633 $(this.leafEdgeL).css({
1634 width: newLeafEdgeWidthL+'px',
1635 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1638 // Left gets the offset of the current left leaf from the document
1639 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1640 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1641 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1643 // We change the left leaf to right positioning
1644 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1645 $(this.prefetchedImgs[leftLeaf]).css({
1650 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1651 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1655 this.removeSearchHilites();
1657 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1658 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1660 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1661 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1663 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1664 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1665 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1667 $(self.leafEdgeR).css({
1668 // Moves the right leaf edge
1669 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1670 left: gutter+newWidthR+'px'
1673 $(self.leafEdgeL).css({
1674 // Moves and resizes the left leaf edge
1675 width: newLeafEdgeWidthL+'px',
1676 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1679 // Resizes the brown border div
1680 $(self.twoPage.coverDiv).css({
1681 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1682 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1685 $(self.leafEdgeTmp).remove();
1686 self.leafEdgeTmp = null;
1688 // $$$ TODO refactor with opposite direction flip
1690 self.twoPage.currentIndexL = newIndexL;
1691 self.twoPage.currentIndexR = newIndexR;
1692 self.twoPage.scaledWL = newWidthL;
1693 self.twoPage.scaledWR = newWidthR;
1694 self.twoPage.gutter = gutter;
1696 self.firstIndex = self.twoPage.currentIndexL;
1697 self.displayedIndices = [newIndexL, newIndexR];
1698 self.pruneUnusedImgs();
1700 self.animating = false;
1702 self.updateSearchHilites2UP();
1703 self.updatePageNumBox2UP();
1705 // self.twoPagePlaceFlipAreas(); // No longer used
1706 self.setMouseHandlers2UP();
1707 self.twoPageSetCursor();
1709 if (self.animationFinishedCallback) {
1710 self.animationFinishedCallback();
1711 self.animationFinishedCallback = null;
1719 //______________________________________________________________________________
1720 // Whether we flip left or right is dependent on the page progression
1721 // to flip forward one spread, pass index=null
1722 GnuBook.prototype.flipFwdToIndex = function(index) {
1724 if (this.animating) return;
1726 if (null != this.leafEdgeTmp) {
1727 alert('error: leafEdgeTmp should be null!');
1731 if (null == index) {
1732 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1734 if (index > this.lastDisplayableIndex()) return;
1736 this.animating = true;
1738 var nextIndices = this.getSpreadIndices(index);
1740 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1742 if ('rl' != this.pageProgression) {
1743 // We did not specify RTL
1744 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1745 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1748 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1749 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1753 // flipRightToLeft(nextL, nextR, gutter)
1754 // $$$ better not to have to pass gutter in
1755 //______________________________________________________________________________
1756 // Flip from left to right and show the nextL and nextR indices on those sides
1757 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1758 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1759 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1760 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1761 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1763 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1765 var top = this.twoPageTop();
1766 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1768 var middle = this.twoPage.middle;
1769 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1771 this.leafEdgeTmp = document.createElement('div');
1772 $(this.leafEdgeTmp).css({
1773 borderStyle: 'solid none solid solid',
1774 borderColor: 'rgb(51, 51, 34)',
1775 borderWidth: '1px 0px 1px 1px',
1776 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1777 width: leafEdgeTmpW + 'px',
1778 height: this.twoPage.height-1 + 'px',
1779 left: gutter+scaledW+'px',
1781 position: 'absolute',
1783 }).appendTo('#GBtwopageview');
1785 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1786 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1788 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1789 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1790 var newWidthL = this.getPageWidth2UP(newIndexL);
1791 var newWidthR = this.getPageWidth2UP(newIndexR);
1793 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1795 var self = this; // closure-tastic!
1797 var speed = this.flipSpeed;
1799 this.removeSearchHilites();
1801 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1802 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1803 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1804 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1805 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1807 $(self.leafEdgeL).css({
1808 width: newLeafEdgeWidthL+'px',
1809 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1812 // Resizes the book cover
1813 $(self.twoPage.coverDiv).css({
1814 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1815 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1818 $(self.leafEdgeTmp).remove();
1819 self.leafEdgeTmp = null;
1821 self.twoPage.currentIndexL = newIndexL;
1822 self.twoPage.currentIndexR = newIndexR;
1823 self.twoPage.scaledWL = newWidthL;
1824 self.twoPage.scaledWR = newWidthR;
1825 self.twoPage.gutter = gutter;
1827 self.firstIndex = self.twoPage.currentIndexL;
1828 self.displayedIndices = [newIndexL, newIndexR];
1829 self.pruneUnusedImgs();
1831 self.animating = false;
1834 self.updateSearchHilites2UP();
1835 self.updatePageNumBox2UP();
1837 // self.twoPagePlaceFlipAreas(); // No longer used
1838 self.setMouseHandlers2UP();
1839 self.twoPageSetCursor();
1841 if (self.animationFinishedCallback) {
1842 self.animationFinishedCallback();
1843 self.animationFinishedCallback = null;
1849 // setMouseHandlers2UP
1850 //______________________________________________________________________________
1851 GnuBook.prototype.setMouseHandlers2UP = function() {
1853 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1858 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1865 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
1866 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
1873 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
1874 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
1877 e.data.self.right();
1883 //______________________________________________________________________________
1884 GnuBook.prototype.prefetchImg = function(index) {
1885 var pageURI = this.getPageURI(index);
1887 // Load image if not loaded or URI has changed (e.g. due to scaling)
1888 var loadImage = false;
1889 if (undefined == this.prefetchedImgs[index]) {
1890 //console.log('no image for ' + index);
1892 } else if (pageURI != this.prefetchedImgs[index].uri) {
1893 //console.log('uri changed for ' + index);
1898 //console.log('prefetching ' + index);
1899 var img = document.createElement("img");
1901 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
1902 this.prefetchedImgs[index] = img;
1907 // prepareFlipLeftToRight()
1909 //______________________________________________________________________________
1911 // Prepare to flip the left page towards the right. This corresponds to moving
1912 // backward when the page progression is left to right.
1913 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1915 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1918 this.prefetchImg(prevL);
1919 this.prefetchImg(prevR);
1921 var height = this.getPageHeight(prevL);
1922 var width = this.getPageWidth(prevL);
1923 var middle = this.twoPage.middle;
1924 var top = this.twoPageTop();
1925 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1927 // The gutter is the dividing line between the left and right pages.
1928 // It is offset from the middle to create the illusion of thickness to the pages
1929 var gutter = middle + this.gutterOffsetForIndex(prevL);
1931 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1932 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1933 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1936 position: 'absolute',
1937 left: gutter-scaledW+'px',
1938 right: '', // clear right property
1940 height: this.twoPage.height,
1941 width: scaledW+'px',
1942 backgroundColor: this.getPageBackgroundColor(prevL),
1943 borderRight: '1px solid black',
1947 $(this.prefetchedImgs[prevL]).css(leftCSS);
1949 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1951 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1954 position: 'absolute',
1958 height: this.twoPage.height,
1960 backgroundColor: this.getPageBackgroundColor(prevR),
1961 borderLeft: '1px solid black',
1965 $(this.prefetchedImgs[prevR]).css(rightCSS);
1967 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1971 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1972 // prepareFlipRightToLeft()
1973 //______________________________________________________________________________
1974 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1976 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1979 this.prefetchImg(nextL);
1980 this.prefetchImg(nextR);
1982 var height = this.getPageHeight(nextR);
1983 var width = this.getPageWidth(nextR);
1984 var middle = this.twoPage.middle;
1985 var top = this.twoPageTop();
1986 var scaledW = this.twoPage.height*width/height;
1988 var gutter = middle + this.gutterOffsetForIndex(nextL);
1990 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1991 $(this.prefetchedImgs[nextR]).css({
1992 position: 'absolute',
1995 backgroundColor: this.getPageBackgroundColor(nextR),
1996 height: this.twoPage.height,
1997 width: scaledW+'px',
1998 borderLeft: '1px solid black',
2002 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
2004 height = this.getPageHeight(nextL);
2005 width = this.getPageWidth(nextL);
2006 scaledW = this.twoPage.height*width/height;
2008 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
2009 $(this.prefetchedImgs[nextL]).css({
2010 position: 'absolute',
2011 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
2013 backgroundColor: this.getPageBackgroundColor(nextL),
2014 height: this.twoPage.height,
2015 width: 0+'px', // Start at 0 width, then grow to the left
2016 borderRight: '1px solid black',
2020 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
2024 // getNextLeafs() -- NOT RTL AWARE
2025 //______________________________________________________________________________
2026 // GnuBook.prototype.getNextLeafs = function(o) {
2027 // //TODO: we might have two left or two right leafs in a row (damaged book)
2028 // //For now, assume that leafs are contiguous.
2030 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2031 // o.L = this.twoPage.currentIndexL+2;
2032 // o.R = this.twoPage.currentIndexL+3;
2035 // getprevLeafs() -- NOT RTL AWARE
2036 //______________________________________________________________________________
2037 // GnuBook.prototype.getPrevLeafs = function(o) {
2038 // //TODO: we might have two left or two right leafs in a row (damaged book)
2039 // //For now, assume that leafs are contiguous.
2041 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2042 // o.L = this.twoPage.currentIndexL-2;
2043 // o.R = this.twoPage.currentIndexL-1;
2046 // pruneUnusedImgs()
2047 //______________________________________________________________________________
2048 GnuBook.prototype.pruneUnusedImgs = function() {
2049 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2050 for (var key in this.prefetchedImgs) {
2051 //console.log('key is ' + key);
2052 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2053 //console.log('removing key '+ key);
2054 $(this.prefetchedImgs[key]).remove();
2056 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2057 //console.log('deleting key '+ key);
2058 delete this.prefetchedImgs[key];
2064 //______________________________________________________________________________
2065 GnuBook.prototype.prefetch = function() {
2067 // prefetch visible pages first
2068 this.prefetchImg(this.twoPage.currentIndexL);
2069 this.prefetchImg(this.twoPage.currentIndexR);
2071 var adjacentPagesToLoad = 3;
2073 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2074 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2076 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2077 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2079 // Load images spreading out from current
2080 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2081 var goingDown = lowCurrent - i;
2082 if (goingDown >= start) {
2083 this.prefetchImg(goingDown);
2085 var goingUp = highCurrent + i;
2086 if (goingUp <= end) {
2087 this.prefetchImg(goingUp);
2092 var lim = this.twoPage.currentIndexL-4;
2094 lim = Math.max(lim, 0);
2095 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2096 this.prefetchImg(i);
2099 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2100 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2101 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2102 this.prefetchImg(i);
2108 // getPageWidth2UP()
2109 //______________________________________________________________________________
2110 GnuBook.prototype.getPageWidth2UP = function(index) {
2111 // We return the width based on the dominant height
2112 var height = this.getPageHeight(index);
2113 var width = this.getPageWidth(index);
2114 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2118 //______________________________________________________________________________
2119 GnuBook.prototype.search = function(term) {
2120 term = term.replace(/\//g, ' '); // strip slashes
2121 this.searchTerm = term;
2122 $('#GnuBookSearchScript').remove();
2123 var script = document.createElement("script");
2124 script.setAttribute('id', 'GnuBookSearchScript');
2125 script.setAttribute("type", "text/javascript");
2126 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
2127 document.getElementsByTagName('head')[0].appendChild(script);
2128 $('#GnuBookSearchBox').val(term);
2129 $('#GnuBookSearchResults').html('Searching...');
2132 // GBSearchCallback()
2133 //______________________________________________________________________________
2134 GnuBook.prototype.GBSearchCallback = function(txt) {
2136 if (jQuery.browser.msie) {
2137 var dom=new ActiveXObject("Microsoft.XMLDOM");
2141 var parser = new DOMParser();
2142 var dom = parser.parseFromString(txt, "text/xml");
2145 $('#GnuBookSearchResults').empty();
2146 $('#GnuBookSearchResults').append('<ul>');
2148 for (var key in this.searchResults) {
2149 if (null != this.searchResults[key].div) {
2150 $(this.searchResults[key].div).remove();
2152 delete this.searchResults[key];
2155 var pages = dom.getElementsByTagName('PAGE');
2157 if (0 == pages.length) {
2158 // $$$ it would be nice to echo the (sanitized) search result here
2159 $('#GnuBookSearchResults').append('<li>No search results found</li>');
2161 for (var i = 0; i < pages.length; i++){
2162 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2165 var re = new RegExp (/_(\d{4})/);
2166 var reMatch = re.exec(pages[i].getAttribute('file'));
2167 var index = parseInt(reMatch[1], 10);
2168 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2170 var children = pages[i].childNodes;
2172 for (var j=0; j<children.length; j++) {
2173 //console.log(j + ' - ' + children[j].nodeName);
2174 //console.log(children[j].firstChild.nodeValue);
2175 if ('CONTEXT' == children[j].nodeName) {
2176 context += children[j].firstChild.nodeValue;
2177 } else if ('WORD' == children[j].nodeName) {
2178 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2180 var index = this.leafNumToIndex(index);
2181 if (null != index) {
2182 //coordinates are [left, bottom, right, top, [baseline]]
2183 //we'll skip baseline for now...
2184 var coords = children[j].getAttribute('coords').split(',',4);
2185 if (4 == coords.length) {
2186 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
2191 var pageName = this.getPageName(index);
2192 //TODO: remove hardcoded instance name
2193 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
2196 $('#GnuBookSearchResults').append('</ul>');
2198 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2199 $('#GnuBookSearchBox').val(this.searchTerm);
2201 this.updateSearchHilites();
2204 // updateSearchHilites()
2205 //______________________________________________________________________________
2206 GnuBook.prototype.updateSearchHilites = function() {
2207 if (2 == this.mode) {
2208 this.updateSearchHilites2UP();
2210 this.updateSearchHilites1UP();
2214 // showSearchHilites1UP()
2215 //______________________________________________________________________________
2216 GnuBook.prototype.updateSearchHilites1UP = function() {
2218 for (var key in this.searchResults) {
2220 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2221 var result = this.searchResults[key];
2222 if(null == result.div) {
2223 result.div = document.createElement('div');
2224 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
2225 //console.log('appending ' + key);
2228 width: (result.r-result.l)/this.reduce + 'px',
2229 height: (result.b-result.t)/this.reduce + 'px',
2230 left: (result.l)/this.reduce + 'px',
2231 top: (result.t)/this.reduce +'px'
2235 //console.log(key + ' not displayed');
2236 this.searchResults[key].div=null;
2242 //______________________________________________________________________________
2243 // Returns the position of the gutter (line between the page images)
2244 GnuBook.prototype.twoPageGutter = function() {
2245 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2249 //______________________________________________________________________________
2250 // Returns the offset for the top of the page images
2251 GnuBook.prototype.twoPageTop = function() {
2252 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2255 // twoPageCoverWidth()
2256 //______________________________________________________________________________
2257 // Returns the width of the cover div given the total page width
2258 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2259 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2262 // twoPageGetViewCenter()
2263 //______________________________________________________________________________
2264 // Returns the percentage offset into twopageview div at the center of container div
2265 // { percentageX: float, percentageY: float }
2266 GnuBook.prototype.twoPageGetViewCenter = function() {
2269 var containerOffset = $('#GBcontainer').offset();
2270 var viewOffset = $('#GBtwopageview').offset();
2271 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2272 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2277 // twoPageCenterView(percentageX, percentageY)
2278 //______________________________________________________________________________
2279 // Centers the point given by percentage from left,top of twopageview
2280 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2281 if ('undefined' == typeof(percentageX)) {
2284 if ('undefined' == typeof(percentageY)) {
2288 var viewWidth = $('#GBtwopageview').width();
2289 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2290 var intoViewX = percentageX * viewWidth;
2292 var viewHeight = $('#GBtwopageview').height();
2293 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2294 var intoViewY = percentageY * viewHeight;
2296 if (viewWidth < containerClientWidth) {
2297 // Can fit width without scrollbars - center by adjusting offset
2298 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2300 // Need to scroll to center
2301 $('#GBtwopageview').css('left', 0);
2302 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2305 if (viewHeight < containerClientHeight) {
2306 // Fits with scrollbars - add offset
2307 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2309 $('#GBtwopageview').css('top', 0);
2310 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2314 // twoPageFlipAreaHeight
2315 //______________________________________________________________________________
2316 // Returns the integer height of the click-to-flip areas at the edges of the book
2317 GnuBook.prototype.twoPageFlipAreaHeight = function() {
2318 return parseInt(this.twoPage.height);
2321 // twoPageFlipAreaWidth
2322 //______________________________________________________________________________
2323 // Returns the integer width of the flip areas
2324 GnuBook.prototype.twoPageFlipAreaWidth = function() {
2325 var max = 100; // $$$ TODO base on view width?
2328 var width = this.twoPage.width * 0.15;
2329 return parseInt(GnuBook.util.clamp(width, min, max));
2332 // twoPageFlipAreaTop
2333 //______________________________________________________________________________
2334 // Returns integer top offset for flip areas
2335 GnuBook.prototype.twoPageFlipAreaTop = function() {
2336 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2339 // twoPageLeftFlipAreaLeft
2340 //______________________________________________________________________________
2341 // Left offset for left flip area
2342 GnuBook.prototype.twoPageLeftFlipAreaLeft = function() {
2343 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2346 // twoPageRightFlipAreaLeft
2347 //______________________________________________________________________________
2348 // Left offset for right flip area
2349 GnuBook.prototype.twoPageRightFlipAreaLeft = function() {
2350 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2353 // twoPagePlaceFlipAreas
2354 //______________________________________________________________________________
2355 // Readjusts position of flip areas based on current layout
2356 GnuBook.prototype.twoPagePlaceFlipAreas = function() {
2357 // We don't set top since it shouldn't change relative to view
2358 $(this.twoPage.leftFlipArea).css({
2359 left: this.twoPageLeftFlipAreaLeft() + 'px',
2360 width: this.twoPageFlipAreaWidth() + 'px'
2362 $(this.twoPage.rightFlipArea).css({
2363 left: this.twoPageRightFlipAreaLeft() + 'px',
2364 width: this.twoPageFlipAreaWidth() + 'px'
2368 // showSearchHilites2UP()
2369 //______________________________________________________________________________
2370 GnuBook.prototype.updateSearchHilites2UP = function() {
2372 for (var key in this.searchResults) {
2373 key = parseInt(key, 10);
2374 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2375 var result = this.searchResults[key];
2376 if(null == result.div) {
2377 result.div = document.createElement('div');
2378 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2379 //console.log('appending ' + key);
2382 // We calculate the reduction factor for the specific page because it can be different
2383 // for each page in the spread
2384 var height = this.getPageHeight(key);
2385 var width = this.getPageWidth(key)
2386 var reduce = this.twoPage.height/height;
2387 var scaledW = parseInt(width*reduce);
2389 var gutter = this.twoPageGutter();
2391 if ('L' == this.getPageSide(key)) {
2392 pageL = gutter-scaledW;
2396 var pageT = this.twoPageTop();
2399 width: (result.r-result.l)*reduce + 'px',
2400 height: (result.b-result.t)*reduce + 'px',
2401 left: pageL+(result.l)*reduce + 'px',
2402 top: pageT+(result.t)*reduce +'px'
2406 //console.log(key + ' not displayed');
2407 if (null != this.searchResults[key].div) {
2408 //console.log('removing ' + key);
2409 $(this.searchResults[key].div).remove();
2411 this.searchResults[key].div=null;
2416 // removeSearchHilites()
2417 //______________________________________________________________________________
2418 GnuBook.prototype.removeSearchHilites = function() {
2419 for (var key in this.searchResults) {
2420 if (null != this.searchResults[key].div) {
2421 $(this.searchResults[key].div).remove();
2422 this.searchResults[key].div=null;
2428 //______________________________________________________________________________
2429 GnuBook.prototype.printPage = function() {
2430 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2432 /* iframe implementation
2434 if (null != this.printPopup) { // check if already showing
2437 this.printPopup = document.createElement("div");
2438 $(this.printPopup).css({
2439 position: 'absolute',
2441 left: ($('#GBcontainer').width()-400)/2 + 'px',
2444 border: "3px double #999999",
2446 backgroundColor: "#fff"
2447 }).appendTo('#GnuBook');
2450 if (this.constMode1up == this.mode) {
2451 indexToPrint = this.firstIndex;
2453 indexToPrint = this.twoPage.currentIndexL;
2456 this.indexToPrint = indexToPrint;
2458 var htmlStr = '<div style="text-align: center;">';
2459 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>';
2460 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2461 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2462 //htmlStr += '<button class="GBicon rollover book_up" onclick="gb.updatePrintFrame(-1); return false;"></button> ';
2463 //htmlStr += '<button class="GBicon rollover book_down" onclick="gb.updatePrintFrame(1); return false;"></button>';
2464 htmlStr += '<a href="#" onclick="gb.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="gb.updatePrintFrame(1); return false;">Next</a>';
2466 htmlStr += '</div>';
2467 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2468 htmlStr += '</div>';
2470 this.printPopup.innerHTML = htmlStr;
2472 var iframe = document.createElement('iframe');
2473 iframe.id = 'printFrame';
2474 iframe.name = 'printFrame';
2475 iframe.width = '233px'; // 8.5 x 11 aspect
2476 iframe.height = '300px';
2478 var self = this; // closure
2480 $(iframe).load(function() {
2481 var doc = GnuBook.util.getIFrameDocument(this);
2482 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2485 $('#printDiv').prepend(iframe);
2489 // Get print URI from current indices and mode
2490 GnuBook.prototype.getPrintURI = function() {
2492 if (this.constMode2up == this.mode) {
2493 indexToPrint = this.twoPage.currentIndexL;
2495 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2498 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2499 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2500 + '&width=' + this.getPageWidth(indexToPrint) + '&height=' + this.getPageHeight(indexToPrint);
2502 if (this.constMode2up == this.mode) {
2503 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this.getPageWidth(this.twoPage.currentIndexR);
2504 options += '&height2=' + this.getPageHeight(this.twoPage.currentIndexR);
2505 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2507 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2510 return '/bookreader/print.php?' + options;
2513 /* iframe implementation
2514 GnuBook.prototype.getPrintFrameContent = function(index) {
2515 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2516 // 8.5x11 so we should end up not overflowing on either paper size.
2517 var paperAspect = 8.5 / 11;
2518 var imageAspect = this.getPageWidth(index) / this.getPageHeight(index);
2522 // Rotate if possible and appropriate, to get larger image size on printed page
2523 if (this.canRotatePage(index)) {
2524 if (imageAspect > 1 && imageAspect > paperAspect) {
2525 // more wide than square, and more wide than paper
2527 imageAspect = 1/imageAspect;
2532 if (imageAspect > paperAspect) {
2533 // wider than paper, fit width
2534 fitAttrs = 'width="95%"';
2536 // taller than paper, fit height
2537 fitAttrs = 'height="95%"';
2540 var imageURL = this.getPageURI(index, 1, rotate);
2541 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2542 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2543 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2544 iframeStr += '</div>';
2545 iframeStr += '</body></html>';
2550 GnuBook.prototype.updatePrintFrame = function(delta) {
2551 var newIndex = this.indexToPrint + delta;
2552 newIndex = GnuBook.util.clamp(newIndex, 0, this.numLeafs - 1);
2553 if (newIndex == this.indexToPrint) {
2556 this.indexToPrint = newIndex;
2557 var doc = GnuBook.util.getIFrameDocument($('#printFrame')[0]);
2558 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2563 //______________________________________________________________________________
2564 GnuBook.prototype.showEmbedCode = function() {
2565 if (null != this.embedPopup) { // check if already showing
2569 this.embedPopup = document.createElement("div");
2570 $(this.embedPopup).css({
2571 position: 'absolute',
2573 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2576 border: "3px double #999999",
2578 backgroundColor: "#fff"
2579 }).appendTo('#GnuBook');
2581 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2582 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>';
2583 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2584 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2586 this.embedPopup.innerHTML = htmlStr;
2587 $(this.embedPopup).find('input').bind('click', function() {
2593 //______________________________________________________________________________
2594 GnuBook.prototype.autoToggle = function() {
2596 var bComingFrom1up = false;
2597 if (2 != this.mode) {
2598 bComingFrom1up = true;
2602 // Change to autofit if book is too large
2603 if (this.reduce < this.twoPageGetAutofitReduce()) {
2608 if (null == this.autoTimer) {
2609 this.flipSpeed = 2000;
2611 // $$$ Draw events currently cause layout problems when they occur during animation.
2612 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2613 // we workaround for now by not triggering immediate animation in that case.
2614 // See https://bugs.launchpad.net/gnubook/+bug/328327
2615 if (('rl' == this.pageProgression) && bComingFrom1up) {
2616 // don't flip immediately -- wait until timer fires
2619 this.flipFwdToIndex();
2622 $('#GBtoolbar .play').hide();
2623 $('#GBtoolbar .pause').show();
2624 this.autoTimer=setInterval(function(){
2625 if (self.animating) {return;}
2627 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2628 self.flipBackToIndex(1); // $$$ really what we want?
2630 self.flipFwdToIndex();
2639 //______________________________________________________________________________
2640 // Stop autoplay mode, allowing animations to finish
2641 GnuBook.prototype.autoStop = function() {
2642 if (null != this.autoTimer) {
2643 clearInterval(this.autoTimer);
2644 this.flipSpeed = 'fast';
2645 $('#GBtoolbar .pause').hide();
2646 $('#GBtoolbar .play').show();
2647 this.autoTimer = null;
2651 // stopFlipAnimations
2652 //______________________________________________________________________________
2653 // Immediately stop flip animations. Callbacks are triggered.
2654 GnuBook.prototype.stopFlipAnimations = function() {
2656 this.autoStop(); // Clear timers
2658 // Stop animation, clear queue, trigger callbacks
2659 if (this.leafEdgeTmp) {
2660 $(this.leafEdgeTmp).stop(false, true);
2662 jQuery.each(this.prefetchedImgs, function() {
2663 $(this).stop(false, true);
2666 // And again since animations also queued in callbacks
2667 if (this.leafEdgeTmp) {
2668 $(this.leafEdgeTmp).stop(false, true);
2670 jQuery.each(this.prefetchedImgs, function() {
2671 $(this).stop(false, true);
2676 // keyboardNavigationIsDisabled(event)
2677 // - returns true if keyboard navigation should be disabled for the event
2678 //______________________________________________________________________________
2679 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2680 if (event.target.tagName == "INPUT") {
2686 // gutterOffsetForIndex
2687 //______________________________________________________________________________
2689 // Returns the gutter offset for the spread containing the given index.
2690 // This function supports RTL
2691 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2693 // To find the offset of the gutter from the middle we calculate our percentage distance
2694 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2695 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2697 // But then again for RTL it's the opposite
2698 if ('rl' == this.pageProgression) {
2706 //______________________________________________________________________________
2707 // Returns the width of the leaf edge div for the page with index given
2708 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2709 // $$$ could there be single pixel rounding errors for L vs R?
2710 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2711 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2713 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2717 // jumpIndexForLeftEdgePageX
2718 //______________________________________________________________________________
2719 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2720 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2721 if ('rl' != this.pageProgression) {
2722 // LTR - flipping backward
2723 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2725 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2726 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2730 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2731 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2736 // jumpIndexForRightEdgePageX
2737 //______________________________________________________________________________
2738 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2739 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2740 if ('rl' != this.pageProgression) {
2742 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2743 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2746 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2747 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2752 GnuBook.prototype.initToolbar = function(mode, ui) {
2754 $("#GnuBook").append("<div id='GBtoolbar'>"
2755 + "<span id='GBtoolbarbuttons' style='float: right'>"
2756 + "<button class='GBicon print rollover' /> <button class='GBicon rollover embed' />"
2757 + "<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>"
2758 + "<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>"
2759 + "<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>"
2760 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' />"
2764 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2765 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2766 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2767 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2768 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2769 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2772 + "<span id='#GBbooktitle'>"
2773 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
2777 this.updateToolbarZoom(this.reduce); // Pretty format
2779 if (ui == "embed") {
2780 $("#GnuBook a.logo").attr("target","_blank");
2783 // $$$ turn this into a member variable
2784 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2786 // We build in mode 2
2789 this.bindToolbarNavHandlers(jToolbar);
2791 // Setup tooltips -- later we could load these from a file for i18n
2792 var titles = { '.logo': 'Go to Archive.org',
2793 '.zoom_in': 'Zoom in',
2794 '.zoom_out': 'Zoom out',
2795 '.one_page_mode': 'One-page view',
2796 '.two_page_mode': 'Two-page view',
2797 '.print': 'Print this page',
2798 '.embed': 'Embed bookreader',
2799 '.book_left': 'Flip left',
2800 '.book_right': 'Flip right',
2801 '.book_up': 'Page up',
2802 '.book_down': 'Page down',
2805 '.book_top': 'First page',
2806 '.book_bottom': 'Last page'
2808 if ('rl' == this.pageProgression) {
2809 titles['.book_leftmost'] = 'Last page';
2810 titles['.book_rightmost'] = 'First page';
2812 titles['.book_leftmost'] = 'First page';
2813 titles['.book_rightmost'] = 'Last page';
2816 for (var icon in titles) {
2817 jToolbar.find(icon).attr('title', titles[icon]);
2820 // Hide mode buttons and autoplay if 2up is not available
2821 // $$$ if we end up with more than two modes we should show the applicable buttons
2822 if ( !this.canSwitchToMode(this.constMode2up) ) {
2823 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2826 // Switch to requested mode -- binds other click handlers
2827 this.switchToolbarMode(mode);
2832 // switchToolbarMode
2833 //______________________________________________________________________________
2834 // Update the toolbar for the given mode (changes navigation buttons)
2835 // $$$ we should soon split the toolbar out into its own module
2836 GnuBook.prototype.switchToolbarMode = function(mode) {
2839 $('#GBtoolbar .GBtoolbarmode2').hide();
2840 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2843 $('#GBtoolbar .GBtoolbarmode1').hide();
2844 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2848 // bindToolbarNavHandlers
2849 //______________________________________________________________________________
2850 // Binds the toolbar handlers
2851 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2853 jToolbar.find('.book_left').bind('click', function(e) {
2858 jToolbar.find('.book_right').bind('click', function(e) {
2863 jToolbar.find('.book_up').bind('click', function(e) {
2868 jToolbar.find('.book_down').bind('click', function(e) {
2873 jToolbar.find('.print').bind('click', function(e) {
2878 jToolbar.find('.embed').bind('click', function(e) {
2883 jToolbar.find('.play').bind('click', function(e) {
2888 jToolbar.find('.pause').bind('click', function(e) {
2893 jToolbar.find('.book_top').bind('click', function(e) {
2898 jToolbar.find('.book_bottom').bind('click', function(e) {
2903 jToolbar.find('.book_leftmost').bind('click', function(e) {
2908 jToolbar.find('.book_rightmost').bind('click', function(e) {
2914 // updateToolbarZoom(reduce)
2915 //______________________________________________________________________________
2916 // Update the displayed zoom factor based on reduction factor
2917 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2919 if (this.constMode2up == this.mode && this.twoPage.autofit) {
2922 value = (100 / reduce).toFixed(2);
2923 // Strip trailing zeroes and decimal if all zeroes
2924 value = value.replace(/0+$/,'');
2925 value = value.replace(/\.$/,'');
2928 $('#GBzoom').text(value);
2931 // firstDisplayableIndex
2932 //______________________________________________________________________________
2933 // Returns the index of the first visible page, dependent on the mode.
2934 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2935 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2936 GnuBook.prototype.firstDisplayableIndex = function() {
2937 if (this.mode == 0) {
2940 if ('rl' != this.pageProgression) {
2942 if (this.getPageSide(0) == 'L') {
2949 if (this.getPageSide(0) == 'R') {
2958 // lastDisplayableIndex
2959 //______________________________________________________________________________
2960 // Returns the index of the last visible page, dependent on the mode.
2961 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2962 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2963 GnuBook.prototype.lastDisplayableIndex = function() {
2965 var lastIndex = this.numLeafs - 1;
2967 if ('rl' != this.pageProgression) {
2969 if (this.getPageSide(lastIndex) == 'R') {
2972 return lastIndex + 1;
2976 if (this.getPageSide(lastIndex) == 'L') {
2979 return lastIndex + 1;
2984 // shortTitle(maximumCharacters)
2986 // Returns a shortened version of the title with the maximum number of characters
2987 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2988 if (this.bookTitle.length < maximumCharacters) {
2989 return this.bookTitle;
2992 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2997 // Parameter related functions
2999 // updateFromParams(params)
3001 // Update ourselves from the params object.
3003 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3004 GnuBook.prototype.updateFromParams = function(params) {
3005 if ('undefined' != typeof(params.mode)) {
3006 this.switchMode(params.mode);
3010 if ('undefined' != typeof(params.searchTerm)) {
3011 if (this.searchTerm != params.searchTerm) {
3012 this.search(params.searchTerm);
3016 // $$$ process /zoom
3018 // We only respect page if index is not set
3019 if ('undefined' != typeof(params.index)) {
3020 if (params.index != this.currentIndex()) {
3021 this.jumpToIndex(params.index);
3023 } else if ('undefined' != typeof(params.page)) {
3024 // $$$ this assumes page numbers are unique
3025 if (params.page != this.getPageNum(this.currentIndex())) {
3026 this.jumpToPage(params.page);
3030 // $$$ process /region
3031 // $$$ process /highlight
3034 // paramsFromFragment(urlFragment)
3036 // Returns a object with configuration parametes from a URL fragment.
3038 // E.g paramsFromFragment(window.location.hash)
3039 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
3040 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3044 // For convenience we allow an initial # character (as from window.location.hash)
3045 // but don't require it
3046 if (urlFragment.substr(0,1) == '#') {
3047 urlFragment = urlFragment.substr(1);
3050 // Simple #nn syntax
3051 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3052 if ( !isNaN(oldStyleLeafNum) ) {
3053 params.index = oldStyleLeafNum;
3055 // Done processing if using old-style syntax
3059 // Split into key-value pairs
3060 var urlArray = urlFragment.split('/');
3062 for (var i = 0; i < urlArray.length; i += 2) {
3063 urlHash[urlArray[i]] = urlArray[i+1];
3067 if ('1up' == urlHash['mode']) {
3068 params.mode = this.constMode1up;
3069 } else if ('2up' == urlHash['mode']) {
3070 params.mode = this.constMode2up;
3074 if ('undefined' != typeof(urlHash['page'])) {
3075 // page was set -- may not be int
3076 params.page = urlHash['page'];
3079 // $$$ process /region
3080 // $$$ process /search
3082 if (urlHash['search'] != undefined) {
3083 params.searchTerm = GnuBook.util.decodeURIComponentPlus(urlHash['search']);
3086 // $$$ process /highlight
3091 // paramsFromCurrent()
3093 // Create a params object from the current parameters.
3094 GnuBook.prototype.paramsFromCurrent = function() {
3098 var index = GnuBook.util.clamp(this.currentIndex(), 0, this.numLeafs - 1);
3100 var pageNum = this.getPageNum(index);
3101 if ((pageNum === 0) || pageNum) {
3102 params.page = pageNum;
3105 params.index = index;
3106 params.mode = this.mode;
3112 if (this.searchHighlightVisible()) {
3113 params.searchTerm = this.searchTerm;
3119 // fragmentFromParams(params)
3121 // Create a fragment string from the params object.
3122 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3123 GnuBook.prototype.fragmentFromParams = function(params) {
3124 var separator = '/';
3128 if ('undefined' != typeof(params.page)) {
3129 fragments.push('page', params.page);
3131 // Don't have page numbering -- use index instead
3132 fragments.push('page', 'n' + params.index);
3139 if ('undefined' != typeof(params.mode)) {
3140 if (params.mode == this.constMode1up) {
3141 fragments.push('mode', '1up');
3142 } else if (params.mode == this.constMode2up) {
3143 fragments.push('mode', '2up');
3145 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3150 if (params.searchTerm) {
3151 fragments.push('search', params.searchTerm);
3154 return GnuBook.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3157 // getPageIndex(pageNum)
3159 // Returns the *highest* index the given page number, or undefined
3160 GnuBook.prototype.getPageIndex = function(pageNum) {
3161 var pageIndices = this.getPageIndices(pageNum);
3163 if (pageIndices.length > 0) {
3164 return pageIndices[pageIndices.length - 1];
3170 // getPageIndices(pageNum)
3172 // Returns an array (possibly empty) of the indices with the given page number
3173 GnuBook.prototype.getPageIndices = function(pageNum) {
3176 // Check for special "nXX" page number
3177 if (pageNum.slice(0,1) == 'n') {
3179 var pageIntStr = pageNum.slice(1, pageNum.length);
3180 var pageIndex = parseInt(pageIntStr);
3181 indices.push(pageIndex);
3184 // Do nothing... will run through page names and see if one matches
3189 for (i=0; i<this.numLeafs; i++) {
3190 if (this.getPageNum(i) == pageNum) {
3198 // getPageName(index)
3200 // Returns the name of the page as it should be displayed in the user interface
3201 GnuBook.prototype.getPageName = function(index) {
3202 return 'Page ' + this.getPageNum(index);
3205 // updateLocationHash
3207 // Update the location hash from the current parameters. Call this instead of manually
3208 // using window.location.replace
3209 GnuBook.prototype.updateLocationHash = function() {
3210 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3211 window.location.replace(newHash);
3213 // This is the variable checked in the timer. Only user-generated changes
3214 // to the URL will trigger the event.
3215 this.oldLocationHash = newHash;
3218 // startLocationPolling
3220 // Starts polling of window.location to see hash fragment changes
3221 GnuBook.prototype.startLocationPolling = function() {
3222 var self = this; // remember who I am
3223 self.oldLocationHash = window.location.hash;
3225 if (this.locationPollId) {
3226 clearInterval(this.locationPollID);
3227 this.locationPollId = null;
3230 this.locationPollId = setInterval(function() {
3231 var newHash = window.location.hash;
3232 if (newHash != self.oldLocationHash) {
3233 if (newHash != self.oldUserHash) { // Only process new user hash once
3234 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3236 // Queue change if animating
3237 if (self.animating) {
3239 self.animationFinishedCallback = function() {
3240 self.updateFromParams(self.paramsFromFragment(newHash));
3242 } else { // update immediately
3243 self.updateFromParams(self.paramsFromFragment(newHash));
3245 self.oldUserHash = newHash;
3253 // Returns true if we can switch to the requested mode
3254 GnuBook.prototype.canSwitchToMode = function(mode) {
3255 if (mode == this.constMode2up) {
3256 // check there are enough pages to display
3257 // $$$ this is a workaround for the mis-feature that we can't display
3258 // short books in 2up mode
3259 if (this.numLeafs < 6) {
3267 // searchHighlightVisible
3269 // Returns true if a search highlight is currently being displayed
3270 GnuBook.prototype.searchHighlightVisible = function() {
3271 if (this.constMode2up == this.mode) {
3272 if (this.searchResults[this.twoPage.currentIndexL]
3273 || this.searchResults[this.twoPage.currentIndexR]) {
3277 if (this.searchResults[this.currentIndex()]) {
3284 // getPageBackgroundColor
3286 // Returns a CSS property string for the background color for the given page
3287 // $$$ turn into regular CSS?
3288 GnuBook.prototype.getPageBackgroundColor = function(index) {
3289 if (index >= 0 && index < this.numLeafs) {
3291 return this.pageDefaultBackgroundColor;
3297 // Library functions
3299 clamp: function(value, min, max) {
3300 return Math.min(Math.max(value, min), max);
3303 getIFrameDocument: function(iframe) {
3304 // Adapted from http://xkr.us/articles/dom/iframe-document/
3305 var outer = (iframe.contentWindow || iframe.contentDocument);
3306 return (outer.document || outer);
3309 decodeURIComponentPlus: function(value) {
3310 // Decodes a URI component and converts '+' to ' '
3311 return decodeURIComponent(value).replace(/\+/g, ' ');
3314 encodeURIComponentPlus: function(value) {
3315 // Encodes a URI component and converts ' ' to '+'
3316 return encodeURIComponent(value).replace(/%20/g, '+');
3318 // The final property here must NOT have a comma after it - IE7