Allow mouseup to propagate, for consistency
[bookreader.git] / GnuBook / GnuBook.js
1 /*
2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
3
4 This file is part of GnuBook.
5
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.
10
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.
15
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/>.
18     
19     The GnuBook source is hosted at http://github.com/openlibrary/bookreader/
20
21     archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
22 */
23
24 // GnuBook()
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init():
28 //  - getPageWidth()
29 //  - getPageHeight()
30 //  - getPageURI()
31 // You must also add a numLeafs property before calling init().
32
33 function GnuBook() {
34     this.reduce  = 4;
35     this.padding = 10;
36     this.mode    = 1; //1 or 2
37     this.ui = 'full'; // UI mode
38     
39     this.displayedIndices = []; 
40     //this.indicesToDisplay = [];
41     this.imgs = {};
42     this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
43     
44     this.timer     = null;
45     this.animating = false;
46     this.auto      = false;
47     this.autoTimer = null;
48     this.flipSpeed = 'fast';
49
50     this.twoPagePopUp = null;
51     this.leafEdgeTmp  = null;
52     this.embedPopup = null;
53     
54     this.searchResults = {};
55     
56     this.firstIndex = null;
57     
58     this.lastDisplayableIndex2up = null;
59     
60     // We link to index.php to avoid redirect which breaks back button
61     this.logoURL = 'http://www.archive.org/index.php';
62     
63     // Base URL for images
64     this.imagesBaseURL = '/bookreader/images/';
65     
66     // Mode constants
67     this.constMode1up = 1;
68     this.constMode2up = 2;
69     
70     // Zoom levels
71     this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
72
73     // Object to hold parameters related to 2up mode
74     this.twoPage = {
75         coverInternalPadding: 10, // Width of cover
76         coverExternalPadding: 10, // Padding outside of cover
77         bookSpineDivWidth: 30,    // Width of book spine  $$$ consider sizing based on book length
78         autofit: true
79     };
80 };
81
82 // init()
83 //______________________________________________________________________________
84 GnuBook.prototype.init = function() {
85
86     var startIndex = undefined;
87     
88     // Find start index and mode if set in location hash
89     var params = this.paramsFromFragment(window.location.hash);
90         
91     if ('undefined' != typeof(params.index)) {
92         startIndex = params.index;
93     } else if ('undefined' != typeof(params.page)) {
94         startIndex = this.getPageIndex(params.page);
95     }
96     
97     if ('undefined' == typeof(startIndex)) {
98         if ('undefined' != typeof(this.titleLeaf)) {
99             startIndex = this.leafNumToIndex(this.titleLeaf);
100         }
101     }
102     
103     if ('undefined' == typeof(startIndex)) {
104         startIndex = 0;
105     }
106     
107     if ('undefined' != typeof(params.mode)) {
108         this.mode = params.mode;
109     }
110     
111     // Set document title -- may have already been set in enclosing html for
112     // search engine visibility
113     document.title = this.shortTitle(50);
114     
115     // Sanitize parameters
116     if ( !this.canSwitchToMode( this.mode ) ) {
117         this.mode = this.constMode1up;
118     }
119     
120     $("#GnuBook").empty();
121     this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
122     $("#GnuBook").append("<div id='GBcontainer'></div>");
123     $("#GBcontainer").append("<div id='GBpageview'></div>");
124
125     $("#GBcontainer").bind('scroll', this, function(e) {
126         e.data.loadLeafs();
127     });
128
129     this.setupKeyListeners();
130     this.startLocationPolling();
131
132     $(window).bind('resize', this, function(e) {
133         //console.log('resize!');
134         if (1 == e.data.mode) {
135             //console.log('centering 1page view');
136             e.data.centerPageView();
137             $('#GBpageview').empty()
138             e.data.displayedIndices = [];
139             e.data.updateSearchHilites(); //deletes hilights but does not call remove()            
140             e.data.loadLeafs();
141         } else {
142             //console.log('drawing 2 page view');
143             
144             // We only need to prepare again in autofit (size of spread changes)
145             if (e.data.twoPage.autofit) {
146                 e.data.prepareTwoPageView();
147             } else {
148                 // Re-center if the scrollbars have disappeared
149                 var center = e.data.twoPageGetViewCenter();
150                 var doRecenter = false;
151                 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
152                     center.percentageX = 0.5;
153                     doRecenter = true;
154                 }
155                 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
156                     center.percentageY = 0.5;
157                     doRecenter = true;
158                 }
159                 if (doRecenter) {
160                     e.data.twoPageCenterView(center.percentageX, center.percentageY);
161                 }
162             }
163         }
164     });
165     
166     $('.GBpagediv1up').bind('mousedown', this, function(e) {
167         // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
168         //     but this also interferes with right-click.  See https://bugs.edge.launchpad.net/gnubook/+bug/362626
169     });
170
171     if (1 == this.mode) {
172         this.resizePageView();
173         this.firstIndex = startIndex;
174         this.jumpToIndex(startIndex);
175     } else {
176         //this.resizePageView();
177         
178         this.displayedIndices=[0];
179         this.firstIndex = startIndex;
180         this.displayedIndices = [this.firstIndex];
181         //console.log('titleLeaf: %d', this.titleLeaf);
182         //console.log('displayedIndices: %s', this.displayedIndices);
183         this.prepareTwoPageView();
184     }
185         
186     // Enact other parts of initial params
187     this.updateFromParams(params);
188 }
189
190 GnuBook.prototype.setupKeyListeners = function() {
191     var self = this;
192
193     var KEY_PGUP = 33;
194     var KEY_PGDOWN = 34;
195     var KEY_END = 35;
196     var KEY_HOME = 36;
197
198     var KEY_LEFT = 37;
199     var KEY_UP = 38;
200     var KEY_RIGHT = 39;
201     var KEY_DOWN = 40;
202
203     // We use document here instead of window to avoid a bug in jQuery on IE7
204     $(document).keydown(function(e) {
205         
206         // Keyboard navigation        
207         switch(e.keyCode) {
208             case KEY_PGUP:
209             case KEY_UP:            
210                 // In 1up mode page scrolling is handled by browser
211                 if (2 == self.mode) {
212                     self.prev();
213                 }
214                 break;
215             case KEY_DOWN:
216             case KEY_PGDOWN:
217                 if (2 == self.mode) {
218                     self.next();
219                 }
220                 break;
221             case KEY_END:
222                 self.last();
223                 break;
224             case KEY_HOME:
225                 self.first();
226                 break;
227             case KEY_LEFT:
228                 if (self.keyboardNavigationIsDisabled(e)) {
229                     break;
230                 }
231                 if (2 == self.mode) {
232                     self.left();
233                 }
234                 break;
235             case KEY_RIGHT:
236                 if (self.keyboardNavigationIsDisabled(e)) {
237                     break;
238                 }
239                 if (2 == self.mode) {
240                     self.right();
241                 }
242                 break;
243         }
244     });
245 }
246
247 // drawLeafs()
248 //______________________________________________________________________________
249 GnuBook.prototype.drawLeafs = function() {
250     if (1 == this.mode) {
251         this.drawLeafsOnePage();
252     } else {
253         this.drawLeafsTwoPage();
254     }
255 }
256
257 // setDragHandler()
258 //______________________________________________________________________________
259 GnuBook.prototype.setDragHandler = function(div) {
260     div.dragging = false;
261
262     $(div).unbind('mousedown').bind('mousedown', function(e) {
263         e.preventDefault();
264         
265         //console.log('mousedown at ' + e.pageY);
266
267         this.dragging = true;
268         this.prevMouseX = e.pageX;
269         this.prevMouseY = e.pageY;
270     
271         var startX    = e.pageX;
272         var startY    = e.pageY;
273         var startTop  = $('#GBcontainer').attr('scrollTop');
274         var startLeft =  $('#GBcontainer').attr('scrollLeft');
275
276     });
277         
278     $(div).unbind('mousemove').bind('mousemove', function(ee) {
279         ee.preventDefault();
280
281         //console.log('mousemove ' + startY);
282         
283         var offsetX = ee.pageX - this.prevMouseX;
284         var offsetY = ee.pageY - this.prevMouseY;
285         
286         if (this.dragging) {
287             $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
288             $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
289         }
290         
291         this.prevMouseX = ee.pageX;
292         this.prevMouseY = ee.pageY;
293         
294     });
295     
296     $(div).unbind('mouseup').bind('mouseup', function(ee) {
297         ee.preventDefault();
298         //console.log('mouseup');
299
300         this.dragging = false;
301     });
302     
303     $(div).unbind('mouseleave').bind('mouseleave', function(e) {
304         e.preventDefault();
305         //console.log('mouseleave');
306
307         this.dragging = false;        
308     });
309     
310     $(div).unbind('mouseenter').bind('mouseenter', function(e) {
311         e.preventDefault();
312         //console.log('mouseenter');
313         
314         this.dragging = false;
315     });
316 }
317
318 // drawLeafsOnePage()
319 //______________________________________________________________________________
320 GnuBook.prototype.drawLeafsOnePage = function() {
321     //alert('drawing leafs!');
322     this.timer = null;
323
324
325     var scrollTop = $('#GBcontainer').attr('scrollTop');
326     var scrollBottom = scrollTop + $('#GBcontainer').height();
327     //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
328     
329     var indicesToDisplay = [];
330     
331     var i;
332     var leafTop = 0;
333     var leafBottom = 0;
334     for (i=0; i<this.numLeafs; i++) {
335         var height  = parseInt(this.getPageHeight(i)/this.reduce); 
336     
337         leafBottom += height;
338         //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
339         var topInView    = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
340         var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
341         var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
342         if (topInView | bottomInView | middleInView) {
343             //console.log('displayed: ' + this.displayedIndices);
344             //console.log('to display: ' + i);
345             indicesToDisplay.push(i);
346         }
347         leafTop += height +10;      
348         leafBottom += 10;
349     }
350
351     var firstIndexToDraw  = indicesToDisplay[0];
352     this.firstIndex      = firstIndexToDraw;
353     
354     // Update hash, but only if we're currently displaying a leaf
355     // Hack that fixes #365790
356     if (this.displayedIndices.length > 0) {
357         this.updateLocationHash();
358     }
359
360     if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
361         firstIndexToDraw--;
362         indicesToDisplay.unshift(firstIndexToDraw);
363     }
364     
365     var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
366     if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
367         indicesToDisplay.push(lastIndexToDraw+1);
368     }
369     
370     leafTop = 0;
371     var i;
372     for (i=0; i<firstIndexToDraw; i++) {
373         leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
374     }
375
376     //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
377     var viewWidth = $('#GBcontainer').attr('scrollWidth');
378
379
380     for (i=0; i<indicesToDisplay.length; i++) {
381         var index = indicesToDisplay[i];    
382         var height  = parseInt(this.getPageHeight(index)/this.reduce); 
383
384         if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {            
385             var width   = parseInt(this.getPageWidth(index)/this.reduce); 
386             //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
387             var div = document.createElement("div");
388             div.className = 'GBpagediv1up';
389             div.id = 'pagediv'+index;
390             div.style.position = "absolute";
391             $(div).css('top', leafTop + 'px');
392             var left = (viewWidth-width)>>1;
393             if (left<0) left = 0;
394             $(div).css('left', left+'px');
395             $(div).css('width', width+'px');
396             $(div).css('height', height+'px');
397             //$(div).text('loading...');
398             
399             this.setDragHandler(div);
400             
401             $('#GBpageview').append(div);
402
403             var img = document.createElement("img");
404             img.src = this.getPageURI(index);
405             $(img).css('width', width+'px');
406             $(img).css('height', height+'px');
407             $(div).append(img);
408
409         } else {
410             //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));            
411         }
412
413         leafTop += height +10;
414
415     }
416     
417     for (i=0; i<this.displayedIndices.length; i++) {
418         if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
419             var index = this.displayedIndices[i];
420             //console.log('Removing leaf ' + index);
421             //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
422             $('#pagediv'+index).remove();
423         } else {
424             //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
425         }
426     }
427     
428     this.displayedIndices = indicesToDisplay.slice();
429     this.updateSearchHilites();
430     
431     if (null != this.getPageNum(firstIndexToDraw))  {
432         $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
433     } else {
434         $("#GBpagenum").val('');
435     }
436             
437     this.updateToolbarZoom(this.reduce);
438     
439 }
440
441 // drawLeafsTwoPage()
442 //______________________________________________________________________________
443 GnuBook.prototype.drawLeafsTwoPage = function() {
444     var scrollTop = $('#GBtwopageview').attr('scrollTop');
445     var scrollBottom = scrollTop + $('#GBtwopageview').height();
446     
447     // $$$ we should use calculated values in this.twoPage (recalc if necessary)
448     
449     var indexL = this.twoPage.currentIndexL;
450     var heightL  = this.getPageHeight(indexL); 
451     var widthL   = this.getPageWidth(indexL);
452
453     var leafEdgeWidthL = this.leafEdgeWidth(indexL);
454     var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
455     //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
456     var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
457     //console.log(leafEdgeWidthL);
458
459     var middle = this.twoPage.middle; // $$$ getter instead?
460     var top = this.twoPageTop();
461     var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
462
463     var scaledWL = this.getPageWidth2UP(indexL);
464     var gutter = this.twoPageGutter();
465     
466     this.prefetchImg(indexL);
467     $(this.prefetchedImgs[indexL]).css({
468         position: 'absolute',
469         left: gutter-scaledWL+'px',
470         right: '',
471         top:    top+'px',
472         backgroundColor: 'rgb(234, 226, 205)',
473         height: this.twoPage.height +'px', // $$$ height forced the same for both pages
474         width:  scaledWL + 'px',
475         borderRight: '1px solid black',
476         zIndex: 2
477     }).appendTo('#GBtwopageview');
478
479
480     var indexR = this.twoPage.currentIndexR;
481     var heightR  = this.getPageHeight(indexR); 
482     var widthR   = this.getPageWidth(indexR);
483
484     // $$$ should use getwidth2up?
485     //var scaledWR = this.twoPage.height*widthR/heightR;
486     var scaledWR = this.getPageWidth2UP(indexR);
487     this.prefetchImg(indexR);
488     $(this.prefetchedImgs[indexR]).css({
489         position: 'absolute',
490         left:   gutter+'px',
491         right: '',
492         top:    top+'px',
493         backgroundColor: 'rgb(234, 226, 205)',
494         height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
495         width:  scaledWR + 'px',
496         borderLeft: '1px solid black',
497         zIndex: 2
498     }).appendTo('#GBtwopageview');
499         
500
501     this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
502     this.setClickHandlers();
503     this.twoPageSetCursor();
504
505     this.updatePageNumBox2UP();
506     this.updateToolbarZoom(this.reduce);
507 }
508
509 // updatePageNumBox2UP
510 //______________________________________________________________________________
511 GnuBook.prototype.updatePageNumBox2UP = function() {
512     if (null != this.getPageNum(this.twoPage.currentIndexL))  {
513         $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
514     } else {
515         $("#GBpagenum").val('');
516     }
517     this.updateLocationHash();
518 }
519
520 // loadLeafs()
521 //______________________________________________________________________________
522 GnuBook.prototype.loadLeafs = function() {
523
524
525     var self = this;
526     if (null == this.timer) {
527         this.timer=setTimeout(function(){self.drawLeafs()},250);
528     } else {
529         clearTimeout(this.timer);
530         this.timer=setTimeout(function(){self.drawLeafs()},250);    
531     }
532 }
533
534 // zoom(direction)
535 //
536 // Pass 1 to zoom in, anything else to zoom out
537 //______________________________________________________________________________
538 GnuBook.prototype.zoom = function(direction) {
539     switch (this.mode) {
540         case this.constMode1up:
541             return this.zoom1up(direction);
542         case this.constMode2up:
543             return this.zoom2up(direction);
544     }
545 }
546
547 // zoom1up(dir)
548 //______________________________________________________________________________
549 GnuBook.prototype.zoom1up = function(dir) {
550     if (2 == this.mode) {     //can only zoom in 1-page mode
551         this.switchMode(1);
552         return;
553     }
554     
555     // $$$ with flexible zoom we could "snap" to /2 page reductions
556     //     for better scaling
557     if (1 == dir) {
558         if (this.reduce <= 0.5) return;
559         this.reduce*=0.5;           //zoom in
560     } else {
561         if (this.reduce >= 8) return;
562         this.reduce*=2;             //zoom out
563     }
564     
565     this.resizePageView();
566
567     $('#GBpageview').empty()
568     this.displayedIndices = [];
569     this.loadLeafs();
570     
571     this.updateToolbarZoom(this.reduce);
572 }
573
574 // resizePageView()
575 //______________________________________________________________________________
576 GnuBook.prototype.resizePageView = function() {
577     var i;
578     var viewHeight = 0;
579     //var viewWidth  = $('#GBcontainer').width(); //includes scrollBar
580     var viewWidth  = $('#GBcontainer').attr('clientWidth');   
581
582     var oldScrollTop  = $('#GBcontainer').attr('scrollTop');
583     var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
584     var oldPageViewHeight = $('#GBpageview').height();
585     var oldPageViewWidth = $('#GBpageview').width();
586     
587     var oldCenterY = this.centerY1up();
588     var oldCenterX = this.centerX1up();
589     
590     if (0 != oldPageViewHeight) {
591         var scrollRatio = oldCenterY / oldPageViewHeight;
592     } else {
593         var scrollRatio = 0;
594     }
595     
596     for (i=0; i<this.numLeafs; i++) {
597         viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding; 
598         var width = parseInt(this.getPageWidth(i)/this.reduce);
599         if (width>viewWidth) viewWidth=width;
600     }
601     $('#GBpageview').height(viewHeight);
602     $('#GBpageview').width(viewWidth);    
603
604     var newCenterY = scrollRatio*viewHeight;
605     var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
606     $('#GBcontainer').attr('scrollTop', newTop);
607     
608     // We use clientWidth here to avoid miscalculating due to scroll bar
609     var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
610     var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
611     newLeft = Math.max(newLeft, 0);
612     $('#GBcontainer').attr('scrollLeft', newLeft);
613     //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
614     
615     //this.centerPageView();
616     this.loadLeafs();
617     
618 }
619
620 // centerX1up()
621 //______________________________________________________________________________
622 // Returns the current offset of the viewport center in scaled document coordinates.
623 GnuBook.prototype.centerX1up = function() {
624     var centerX;
625     if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
626         centerX = $('#GBpageview').width();
627     } else {
628         centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
629     }
630     centerX = Math.floor(centerX);
631     return centerX;
632 }
633
634 // centerY1up()
635 //______________________________________________________________________________
636 // Returns the current offset of the viewport center in scaled document coordinates.
637 GnuBook.prototype.centerY1up = function() {
638     var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
639     return Math.floor(centerY);
640 }
641
642 // centerPageView()
643 //______________________________________________________________________________
644 GnuBook.prototype.centerPageView = function() {
645
646     var scrollWidth  = $('#GBcontainer').attr('scrollWidth');
647     var clientWidth  =  $('#GBcontainer').attr('clientWidth');
648     //console.log('sW='+scrollWidth+' cW='+clientWidth);
649     if (scrollWidth > clientWidth) {
650         $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
651     }
652
653 }
654
655 // zoom2up(direction)
656 //______________________________________________________________________________
657 GnuBook.prototype.zoom2up = function(direction) {
658
659     // Hard stop autoplay
660     this.stopFlipAnimations();
661     
662     // Get new zoom state    
663     var newZoom = this.twoPageNextReduce(this.reduce, direction);
664     if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
665         return;
666     }
667     this.twoPage.autofit = newZoom.autofit;
668     this.reduce = newZoom.reduce;
669
670     // Preserve view center position
671     var oldCenter = this.twoPageGetViewCenter();
672     
673     // Prepare view with new center to minimize visual glitches
674     this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
675 }
676
677
678 // quantizeReduce(reduce)
679 //______________________________________________________________________________
680 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
681 GnuBook.prototype.quantizeReduce = function(reduce) {
682     var quantized = this.reductionFactors[0];
683     var distance = Math.abs(reduce - quantized);
684     for (var i = 1; i < this.reductionFactors.length; i++) {
685         newDistance = Math.abs(reduce - this.reductionFactors[i]);
686         if (newDistance < distance) {
687             distance = newDistance;
688             quantized = this.reductionFactors[i];
689         }
690     }
691     
692     return quantized;
693 }
694
695 // twoPageNextReduce()
696 //______________________________________________________________________________
697 // Returns the next reduction level
698 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
699     var result = {};
700     var autofitReduce = this.twoPageGetAutofitReduce();
701
702     if (0 == direction) { // autofit
703         result.autofit = true;
704         result.reduce = autofitReduce;
705         
706     } else if (1 == direction) { // zoom in
707         var newReduce = this.reductionFactors[0];
708     
709         for (var i = 1; i < this.reductionFactors.length; i++) {
710             if (this.reductionFactors[i] < reduce) {
711                 newReduce = this.reductionFactors[i];
712             }
713         }
714         
715         if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
716             // use autofit
717             result.autofit = true;
718             result.reduce = autofitReduce;
719         } else {        
720             result.autofit = false;
721             result.reduce = newReduce;
722         }
723         
724     } else { // zoom out
725         var lastIndex = this.reductionFactors.length - 1;
726         var newReduce = this.reductionFactors[lastIndex];
727         
728         for (var i = lastIndex; i >= 0; i--) {
729             if (this.reductionFactors[i] > reduce) {
730                 newReduce = this.reductionFactors[i];
731             }
732         }
733          
734         if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
735             // use autofit
736             result.autofit = true;
737             result.reduce = autofitReduce;
738         } else {
739             result.autofit = false;
740             result.reduce = newReduce;
741         }
742     }
743     
744     return result;
745 }
746
747 // jumpToPage()
748 //______________________________________________________________________________
749 // Attempts to jump to page.  Returns true if page could be found, false otherwise.
750 GnuBook.prototype.jumpToPage = function(pageNum) {
751
752     var pageIndex = this.getPageIndex(pageNum);
753
754     if ('undefined' != typeof(pageIndex)) {
755         var leafTop = 0;
756         var h;
757         this.jumpToIndex(pageIndex);
758         $('#GBcontainer').attr('scrollTop', leafTop);
759         return true;
760     }
761     
762     // Page not found
763     return false;
764 }
765
766 // jumpToIndex()
767 //______________________________________________________________________________
768 GnuBook.prototype.jumpToIndex = function(index) {
769
770     if (2 == this.mode) {
771         this.autoStop();
772         
773         // By checking against min/max we do nothing if requested index
774         // is current
775         if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
776             this.flipBackToIndex(index);
777         } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
778             this.flipFwdToIndex(index);
779         }
780
781     } else {        
782         var i;
783         var leafTop = 0;
784         var h;
785         for (i=0; i<index; i++) {
786             h = parseInt(this.getPageHeight(i)/this.reduce); 
787             leafTop += h + this.padding;
788         }
789         //$('#GBcontainer').attr('scrollTop', leafTop);
790         $('#GBcontainer').animate({scrollTop: leafTop },'fast');
791     }
792 }
793
794
795
796 // switchMode()
797 //______________________________________________________________________________
798 GnuBook.prototype.switchMode = function(mode) {
799
800     //console.log('  asked to switch to mode ' + mode + ' from ' + this.mode);
801     
802     if (mode == this.mode) return;
803     
804     if (!this.canSwitchToMode(mode)) {
805         return;
806     }
807
808     this.autoStop();
809     this.removeSearchHilites();
810
811     this.mode = mode;
812     
813     this.switchToolbarMode(mode);
814     
815     // $$$ TODO preserve center of view when switching between mode
816     //     See https://bugs.edge.launchpad.net/gnubook/+bug/416682
817     
818     if (1 == mode) {
819         this.reduce = this.quantizeReduce(this.reduce);
820         this.prepareOnePageView();
821     } else {
822         this.twoPage.autofit = false; // Take zoom level from other mode
823         this.reduce = this.quantizeReduce(this.reduce);
824         this.prepareTwoPageView();
825         this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
826     }
827
828 }
829
830 //prepareOnePageView()
831 //______________________________________________________________________________
832 GnuBook.prototype.prepareOnePageView = function() {
833
834     // var startLeaf = this.displayedIndices[0];
835     var startLeaf = this.currentIndex();
836     
837     $('#GBcontainer').empty();
838     $('#GBcontainer').css({
839         overflowY: 'scroll',
840         overflowX: 'auto'
841     });
842     
843     var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
844     
845     this.resizePageView();
846     
847     this.jumpToIndex(startLeaf);
848     this.displayedIndices = [];
849     
850     this.drawLeafsOnePage();
851         
852     // Bind mouse handlers
853     // Disable mouse click to avoid selected/highlighted page images - bug 354239
854     gbPageView.bind('mousedown', function(e) {
855         // $$$ check here for right-click and don't disable.  Also use jQuery style
856         //     for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
857         return false;
858     })
859     // Special hack for IE7
860     gbPageView[0].onselectstart = function(e) { return false; };
861 }
862
863 // prepareTwoPageView()
864 //______________________________________________________________________________
865 // Some decisions about two page view:
866 //
867 // Both pages will be displayed at the same height, even if they were different physical/scanned
868 // sizes.  This simplifies the animation (from a design as well as technical standpoint).  We
869 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
870 // aspect ratio to determine the height.
871 //
872 // The two page view div is resized to keep the middle of the book in the middle of the div
873 // even as the page sizes change.  To e.g. keep the middle of the book in the middle of the GBcontent
874 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
875 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
876     $('#GBcontainer').empty();
877     $('#GBcontainer').css('overflow', 'auto');
878         
879     // We want to display two facing pages.  We may be missing
880     // one side of the spread because it is the first/last leaf,
881     // foldouts, missing pages, etc
882
883     //var targetLeaf = this.displayedIndices[0];
884     var targetLeaf = this.firstIndex;
885
886     if (targetLeaf < this.firstDisplayableIndex()) {
887         targetLeaf = this.firstDisplayableIndex();
888     }
889     
890     if (targetLeaf > this.lastDisplayableIndex()) {
891         targetLeaf = this.lastDisplayableIndex();
892     }
893     
894     this.twoPage.currentIndexL = null;
895     this.twoPage.currentIndexR = null;
896     this.pruneUnusedImgs();
897     
898     var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
899     this.twoPage.currentIndexL = currentSpreadIndices[0];
900     this.twoPage.currentIndexR = currentSpreadIndices[1];
901     this.firstIndex = this.twoPage.currentIndexL;
902     
903     this.calculateSpreadSize(); //sets twoPage.width, twoPage.height
904         
905     //console.dir(this.twoPage);
906     
907     // Add the two page view
908     // $$$ Can we get everything set up and then append?
909     $('#GBcontainer').append('<div id="GBtwopageview"></div>');
910
911     // $$$ calculate first then set
912     $('#GBtwopageview').css( {
913         height: this.twoPage.totalHeight + 'px',
914         width: this.twoPage.totalWidth + 'px',
915         position: 'absolute'
916         });
917         
918     // If there will not be scrollbars (e.g. when zooming out) we center the book
919     // since otherwise the book will be stuck off-center
920     if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
921         centerPercentageX = 0.5;
922     }
923     if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
924         centerPercentageY = 0.5;
925     }
926         
927     this.twoPageCenterView(centerPercentageX, centerPercentageY);
928     
929     this.twoPage.coverDiv = document.createElement('div');
930     $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
931         border: '1px solid rgb(68, 25, 17)',
932         width:  this.twoPage.bookCoverDivWidth + 'px',
933         height: this.twoPage.bookCoverDivHeight+'px',
934         visibility: 'visible',
935         position: 'absolute',
936         backgroundColor: '#663929',
937         left: this.twoPage.bookCoverDivLeft + 'px',
938         top: this.twoPage.bookCoverDivTop+'px',
939         MozBorderRadiusTopleft: '7px',
940         MozBorderRadiusTopright: '7px',
941         MozBorderRadiusBottomright: '7px',
942         MozBorderRadiusBottomleft: '7px'
943     }).appendTo('#GBtwopageview');
944     
945     this.leafEdgeR = document.createElement('div');
946     this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
947     $(this.leafEdgeR).css({
948         borderStyle: 'solid solid solid none',
949         borderColor: 'rgb(51, 51, 34)',
950         borderWidth: '1px 1px 1px 0px',
951         background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
952         width: this.twoPage.leafEdgeWidthR + 'px',
953         height: this.twoPage.height-1 + 'px',
954         /*right: '10px',*/
955         left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
956         top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
957         position: 'absolute'
958     }).appendTo('#GBtwopageview');
959     
960     this.leafEdgeL = document.createElement('div');
961     this.leafEdgeL.className = 'leafEdgeL';
962     $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
963         borderStyle: 'solid none solid solid',
964         borderColor: 'rgb(51, 51, 34)',
965         borderWidth: '1px 0px 1px 1px',
966         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
967         width: this.twoPage.leafEdgeWidthL + 'px',
968         height: this.twoPage.height-1 + 'px',
969         left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
970         top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',    
971         position: 'absolute'
972     }).appendTo('#GBtwopageview');
973
974     div = document.createElement('div');
975     $(div).attr('id', 'GBbookspine').css({
976         border:          '1px solid rgb(68, 25, 17)',
977         width:           this.twoPage.bookSpineDivWidth+'px',
978         height:          this.twoPage.bookSpineDivHeight+'px',
979         position:        'absolute',
980         backgroundColor: 'rgb(68, 25, 17)',
981         left:            this.twoPage.bookSpineDivLeft+'px',
982         top:             this.twoPage.bookSpineDivTop+'px'
983     }).appendTo('#GBtwopageview');
984
985     this.prepareTwoPagePopUp();
986
987     this.displayedIndices = [];
988     
989     //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
990     //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
991     
992     this.drawLeafsTwoPage();
993     this.updateSearchHilites2UP();
994     this.updateToolbarZoom(this.reduce);
995     
996     this.prefetch();
997 }
998
999 // prepareTwoPagePopUp()
1000 //
1001 // This function prepares the "View Page n" popup that shows while the mouse is
1002 // over the left/right "stack of sheets" edges.  It also binds the mouse
1003 // events for these divs.
1004 //______________________________________________________________________________
1005 GnuBook.prototype.prepareTwoPagePopUp = function() {
1006
1007     this.twoPagePopUp = document.createElement('div');
1008     $(this.twoPagePopUp).css({
1009         border: '1px solid black',
1010         padding: '2px 6px',
1011         position: 'absolute',
1012         fontFamily: 'sans-serif',
1013         fontSize: '14px',
1014         zIndex: '1000',
1015         backgroundColor: 'rgb(255, 255, 238)',
1016         opacity: 0.85
1017     }).appendTo('#GBcontainer');
1018     $(this.twoPagePopUp).hide();
1019     
1020     $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1021         $(e.data.twoPagePopUp).show();
1022     });
1023
1024     $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1025         $(e.data.twoPagePopUp).hide();
1026     });
1027
1028     $(this.leafEdgeL).bind('click', this, function(e) { 
1029         e.data.autoStop();
1030         var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1031         e.data.jumpToIndex(jumpIndex);
1032     });
1033
1034     $(this.leafEdgeR).bind('click', this, function(e) { 
1035         e.data.autoStop();
1036         var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1037         e.data.jumpToIndex(jumpIndex);    
1038     });
1039
1040     $(this.leafEdgeR).bind('mousemove', this, function(e) {
1041
1042         var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1043         $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1044         
1045         // $$$ TODO: Make sure popup is positioned so that it is in view
1046         // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)        
1047         $(e.data.twoPagePopUp).css({
1048             left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1049             top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1050         });
1051     });
1052
1053     $(this.leafEdgeL).bind('mousemove', this, function(e) {
1054     
1055         var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1056         $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1057
1058         // $$$ TODO: Make sure popup is positioned so that it is in view
1059         //           (https://bugs.edge.launchpad.net/gnubook/+bug/327456)        
1060         $(e.data.twoPagePopUp).css({
1061             left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1062             top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1063         });
1064     });
1065 }
1066
1067 // calculateSpreadSize()
1068 //______________________________________________________________________________
1069 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1070 // this.twoPage.currentIndexR
1071 // This function sets this.twoPage.height, twoPage.width
1072
1073 GnuBook.prototype.calculateSpreadSize = function() {
1074
1075     var firstIndex  = this.twoPage.currentIndexL;
1076     var secondIndex = this.twoPage.currentIndexR;
1077     //console.log('first page is ' + firstIndex);
1078
1079     // Calculate page sizes and total leaf width
1080     var spreadSize;
1081     if ( this.twoPage.autofit) {    
1082         spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1083     } else {
1084         // set based on reduction factor
1085         spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1086     }
1087     
1088     // Both pages together
1089     this.twoPage.height = spreadSize.height;
1090     this.twoPage.width = spreadSize.width;
1091     
1092     // Individual pages
1093     this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1094     this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1095     
1096     // Leaf edges
1097     this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1098     this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1099     this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1100     
1101     
1102     // Book cover
1103     // The width of the book cover div.  The combined width of both pages, twice the width
1104     // of the book cover internal padding (2*10) and the page edges
1105     this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1106     // The height of the book cover div
1107     this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1108     
1109     
1110     // We calculate the total width and height for the div so that we can make the book
1111     // spine centered
1112     var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1113     var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1114     var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1115     var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1116     this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1117     this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1118         
1119     // We want to minimize the unused space in two-up mode (maximize the amount of page
1120     // shown).  We give width to the leaf edges and these widths change (though the sum
1121     // of the two remains constant) as we flip through the book.  With the book
1122     // cover centered and fixed in the GBcontainer div the page images will meet
1123     // at the "gutter" which is generally offset from the center.
1124     this.twoPage.middle = this.twoPage.totalWidth >> 1;
1125     this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1126     
1127     // The left edge of the book cover moves depending on the width of the pages
1128     // $$$ change to getter
1129     this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1130     // The top edge of the book cover stays a fixed distance from the top
1131     this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1132
1133     // Book spine
1134     this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1135     this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1136     this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1137
1138
1139     this.reduce = spreadSize.reduce; // $$$ really set this here?
1140 }
1141
1142 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1143     var ideal = {};
1144
1145     // We check which page is closest to a "normal" page and use that to set the height
1146     // for both pages.  This means that foldouts and other odd size pages will be displayed
1147     // smaller than the nominal zoom amount.
1148     var canon5Dratio = 1.5;
1149     
1150     var first = {
1151         height: this.getPageHeight(firstIndex),
1152         width: this.getPageWidth(firstIndex)
1153     }
1154     
1155     var second = {
1156         height: this.getPageHeight(secondIndex),
1157         width: this.getPageWidth(secondIndex)
1158     }
1159     
1160     var firstIndexRatio  = first.height / first.width;
1161     var secondIndexRatio = second.height / second.width;
1162     //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1163
1164     var ratio;
1165     if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1166         ratio = firstIndexRatio;
1167         //console.log('using firstIndexRatio ' + ratio);
1168     } else {
1169         ratio = secondIndexRatio;
1170         //console.log('using secondIndexRatio ' + ratio);
1171     }
1172
1173     var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1174     var maxLeafEdgeWidth   = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1175     ideal.totalLeafEdgeWidth     = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1176     
1177     var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1178     var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1179     
1180     ideal.width = ($('#GBcontainer').attr('clientWidth') - widthOutsidePages) >> 1;
1181     ideal.width -= 10; // $$$ fudge factor
1182     ideal.height = $('#GBcontainer').attr('clientHeight') - heightOutsidePages;
1183     ideal.height -= 20; // fudge factor
1184     //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1185
1186     if (ideal.height/ratio <= ideal.width) {
1187         //use height
1188         ideal.width = parseInt(ideal.height/ratio);
1189     } else {
1190         //use width
1191         ideal.height = parseInt(ideal.width*ratio);
1192     }
1193     
1194     // $$$ check this logic with large spreads
1195     ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1196     
1197     return ideal;
1198 }
1199
1200 // getSpreadSizeFromReduce()
1201 //______________________________________________________________________________
1202 // Returns the spread size calculated from the reduction factor for the given pages
1203 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1204     var spreadSize = {};
1205     // $$$ Scale this based on reduce?
1206     var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1207     var maxLeafEdgeWidth   = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1208     spreadSize.totalLeafEdgeWidth     = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1209
1210     // $$$ Possibly incorrect -- we should make height "dominant"
1211     var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1212     var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1213     spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1214     spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1215     spreadSize.reduce = reduce;
1216     
1217     return spreadSize;
1218 }
1219
1220 // twoPageGetAutofitReduce()
1221 //______________________________________________________________________________
1222 // Returns the current ideal reduction factor
1223 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1224     var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1225     return spreadSize.reduce;
1226 }
1227
1228 // twoPageSetCursor()
1229 //______________________________________________________________________________
1230 // Set the cursor for two page view
1231 GnuBook.prototype.twoPageSetCursor = function() {
1232     // console.log('setting cursor');
1233     if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1234          ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1235         $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1236         $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1237     } else {
1238         $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1239         $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1240     }
1241 }
1242
1243 // currentIndex()
1244 //______________________________________________________________________________
1245 // Returns the currently active index.
1246 GnuBook.prototype.currentIndex = function() {
1247     // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1248     if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1249         return this.firstIndex;
1250     } else {
1251         throw 'currentIndex called for unimplemented mode ' + this.mode;
1252     }
1253 }
1254
1255 // right()
1256 //______________________________________________________________________________
1257 // Flip the right page over onto the left
1258 GnuBook.prototype.right = function() {
1259     if ('rl' != this.pageProgression) {
1260         // LTR
1261         gb.next();
1262     } else {
1263         // RTL
1264         gb.prev();
1265     }
1266 }
1267
1268 // rightmost()
1269 //______________________________________________________________________________
1270 // Flip to the rightmost page
1271 GnuBook.prototype.rightmost = function() {
1272     if ('rl' != this.pageProgression) {
1273         gb.last();
1274     } else {
1275         gb.first();
1276     }
1277 }
1278
1279 // left()
1280 //______________________________________________________________________________
1281 // Flip the left page over onto the right.
1282 GnuBook.prototype.left = function() {
1283     if ('rl' != this.pageProgression) {
1284         // LTR
1285         gb.prev();
1286     } else {
1287         // RTL
1288         gb.next();
1289     }
1290 }
1291
1292 // leftmost()
1293 //______________________________________________________________________________
1294 // Flip to the leftmost page
1295 GnuBook.prototype.leftmost = function() {
1296     if ('rl' != this.pageProgression) {
1297         gb.first();
1298     } else {
1299         gb.last();
1300     }
1301 }
1302
1303 // next()
1304 //______________________________________________________________________________
1305 GnuBook.prototype.next = function() {
1306     if (2 == this.mode) {
1307         this.autoStop();
1308         this.flipFwdToIndex(null);
1309     } else {
1310         if (this.firstIndex < this.lastDisplayableIndex()) {
1311             this.jumpToIndex(this.firstIndex+1);
1312         }
1313     }
1314 }
1315
1316 // prev()
1317 //______________________________________________________________________________
1318 GnuBook.prototype.prev = function() {
1319     if (2 == this.mode) {
1320         this.autoStop();
1321         this.flipBackToIndex(null);
1322     } else {
1323         if (this.firstIndex >= 1) {
1324             this.jumpToIndex(this.firstIndex-1);
1325         }    
1326     }
1327 }
1328
1329 GnuBook.prototype.first = function() {
1330     if (2 == this.mode) {
1331         this.jumpToIndex(2);
1332     }
1333     else {
1334         this.jumpToIndex(0);
1335     }
1336 }
1337
1338 GnuBook.prototype.last = function() {
1339     if (2 == this.mode) {
1340         this.jumpToIndex(this.lastDisplayableIndex());
1341     }
1342     else {
1343         this.jumpToIndex(this.lastDisplayableIndex());
1344     }
1345 }
1346
1347 // flipBackToIndex()
1348 //______________________________________________________________________________
1349 // to flip back one spread, pass index=null
1350 GnuBook.prototype.flipBackToIndex = function(index) {
1351     if (1 == this.mode) return;
1352
1353     var leftIndex = this.twoPage.currentIndexL;
1354     
1355     // $$$ Need to change this to be able to see first spread.
1356     //     See https://bugs.launchpad.net/gnubook/+bug/296788
1357     if (leftIndex <= 2) return;
1358     if (this.animating) return;
1359
1360     if (null != this.leafEdgeTmp) {
1361         alert('error: leafEdgeTmp should be null!');
1362         return;
1363     }
1364     
1365     if (null == index) {
1366         index = leftIndex-2;
1367     }
1368     //if (index<0) return;
1369     
1370     var previousIndices = this.getSpreadIndices(index);
1371     
1372     if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1373         return;
1374     }
1375     
1376     //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1377
1378     this.animating = true;
1379     
1380     if ('rl' != this.pageProgression) {
1381         // Assume LTR and we are going backward    
1382         this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);        
1383         this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1384     } else {
1385         // RTL and going backward
1386         var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1387         this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1388     }
1389 }
1390
1391 // flipLeftToRight()
1392 //______________________________________________________________________________
1393 // Flips the page on the left towards the page on the right
1394 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1395
1396     var leftLeaf = this.twoPage.currentIndexL;
1397     
1398     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1399     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);    
1400     var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1401     
1402     var currWidthL   = this.getPageWidth2UP(leftLeaf);
1403     var newWidthL    = this.getPageWidth2UP(newIndexL);
1404     var newWidthR    = this.getPageWidth2UP(newIndexR);
1405
1406     var top  = this.twoPageTop();
1407     var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1408     
1409     //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1410     //console.log('  gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1411     
1412     //animation strategy:
1413     // 0. remove search highlight, if any.
1414     // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge 
1415     //    of the left leaf and where the user clicked in the leaf edge.
1416     //    Note that if this function was triggered by left() and not a
1417     //    mouse click, the width of leafEdgeTmp is very small (zero px).
1418     // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1419     //    leftLeaf to width=0.
1420     // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1421     //    (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1422     //    its new full width.
1423     // 4. After step 3 is finished, do the following:
1424     //      - remove leafEdgeTmp from the dom.
1425     //      - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1426     //          and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1427     //      - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1428     //          and width=newLeafEdgeWidthL.
1429     //      - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1430     //          and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1431     //      - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1432     //      - remove old left and right leafs from the dom [pruneUnusedImgs()].
1433     //      - prefetch new adjacent leafs.
1434     //      - set up click handlers for both new left and right leafs.
1435     //      - redraw the search highlight.
1436     //      - update the pagenum box and the url.
1437     
1438     
1439     var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1440
1441     this.leafEdgeTmp = document.createElement('div');
1442     $(this.leafEdgeTmp).css({
1443         borderStyle: 'solid none solid solid',
1444         borderColor: 'rgb(51, 51, 34)',
1445         borderWidth: '1px 0px 1px 1px',
1446         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1447         width: leafEdgeTmpW + 'px',
1448         height: this.twoPage.height-1 + 'px',
1449         left: leftEdgeTmpLeft + 'px',
1450         top: top+'px',    
1451         position: 'absolute',
1452         zIndex:1000
1453     }).appendTo('#GBtwopageview');
1454     
1455     //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1456     $(this.leafEdgeL).css({
1457         width: newLeafEdgeWidthL+'px', 
1458         left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1459     });   
1460
1461     // Left gets the offset of the current left leaf from the document
1462     var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1463     // $$$ This seems very similar to the gutter.  May be able to consolidate the logic.
1464     var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1465     
1466     // We change the left leaf to right positioning
1467     // $$$ This causes animation glitches during resize.  See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1468     $(this.prefetchedImgs[leftLeaf]).css({
1469         right: right,
1470         left: ''
1471     });
1472
1473     $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');    
1474     //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1475     
1476     var self = this;
1477
1478     this.removeSearchHilites();
1479
1480     //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1481     $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1482     
1483         //console.log('     and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1484         $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1485
1486         //console.log('  animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1487         $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1488             $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1489             
1490             $(self.leafEdgeR).css({
1491                 // Moves the right leaf edge
1492                 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1493                 left:  gutter+newWidthR+'px'
1494             });
1495
1496             $(self.leafEdgeL).css({
1497                 // Moves and resizes the left leaf edge
1498                 width: newLeafEdgeWidthL+'px',
1499                 left:  gutter-newWidthL-newLeafEdgeWidthL+'px'
1500             });
1501
1502             // Resizes the brown border div
1503             $(self.twoPage.coverDiv).css({
1504                 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1505                 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1506             });
1507             
1508             $(self.leafEdgeTmp).remove();
1509             self.leafEdgeTmp = null;
1510             
1511             self.twoPage.currentIndexL = newIndexL;
1512             self.twoPage.currentIndexR = newIndexR;
1513             self.firstIndex = self.twoPage.currentIndexL;
1514             self.displayedIndices = [newIndexL, newIndexR];
1515             self.setClickHandlers();
1516             self.twoPageSetCursor();
1517             self.pruneUnusedImgs();
1518             self.prefetch();            
1519             self.animating = false;
1520             
1521             self.updateSearchHilites2UP();
1522             self.updatePageNumBox2UP();
1523             
1524             if (self.animationFinishedCallback) {
1525                 self.animationFinishedCallback();
1526                 self.animationFinishedCallback = null;
1527             }
1528         });
1529     });        
1530     
1531 }
1532
1533 // flipFwdToIndex()
1534 //______________________________________________________________________________
1535 // Whether we flip left or right is dependent on the page progression
1536 // to flip forward one spread, pass index=null
1537 GnuBook.prototype.flipFwdToIndex = function(index) {
1538
1539     if (this.animating) return;
1540
1541     if (null != this.leafEdgeTmp) {
1542         alert('error: leafEdgeTmp should be null!');
1543         return;
1544     }
1545
1546     if (null == index) {
1547         index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1548     }
1549     if (index > this.lastDisplayableIndex()) return;
1550
1551     this.animating = true;
1552     
1553     var nextIndices = this.getSpreadIndices(index);
1554     
1555     //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1556
1557     if ('rl' != this.pageProgression) {
1558         // We did not specify RTL
1559         var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1560         this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1561     } else {
1562         // RTL
1563         var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1564         this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1565     }
1566 }
1567
1568 // flipRightToLeft(nextL, nextR, gutter)
1569 // $$$ better not to have to pass gutter in
1570 //______________________________________________________________________________
1571 // Flip from left to right and show the nextL and nextR indices on those sides
1572 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1573     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1574     var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1575     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);  
1576     var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1577
1578     var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1579
1580     var top = this.twoPageTop();
1581     var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1582
1583     var middle = this.twoPage.middle;
1584     var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1585     
1586     this.leafEdgeTmp = document.createElement('div');
1587     $(this.leafEdgeTmp).css({
1588         borderStyle: 'solid none solid solid',
1589         borderColor: 'rgb(51, 51, 34)',
1590         borderWidth: '1px 0px 1px 1px',
1591         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1592         width: leafEdgeTmpW + 'px',
1593         height: this.twoPage.height-1 + 'px',
1594         left: gutter+scaledW+'px',
1595         top: top+'px',    
1596         position: 'absolute',
1597         zIndex:1000
1598     }).appendTo('#GBtwopageview');
1599
1600     //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1601     //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1602     
1603     var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1604     var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1605     var newWidthL = this.getPageWidth2UP(newIndexL);
1606     var newWidthR = this.getPageWidth2UP(newIndexR);
1607     
1608     $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1609
1610     var self = this; // closure-tastic!
1611
1612     var speed = this.flipSpeed;
1613
1614     this.removeSearchHilites();
1615     
1616     $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');    
1617     $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1618         $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');    
1619         $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1620             $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1621             
1622             $(self.leafEdgeL).css({
1623                 width: newLeafEdgeWidthL+'px', 
1624                 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1625             });
1626             
1627             // Resizes the book cover
1628             $(self.twoPage.coverDiv).css({
1629                 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1630                 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1631             });
1632             
1633             $(self.leafEdgeTmp).remove();
1634             self.leafEdgeTmp = null;
1635             
1636             self.twoPage.currentIndexL = newIndexL;
1637             self.twoPage.currentIndexR = newIndexR;
1638             self.firstIndex = self.twoPage.currentIndexL;
1639             self.displayedIndices = [newIndexL, newIndexR];
1640             self.setClickHandlers();     
1641             self.twoPageSetCursor();
1642             self.pruneUnusedImgs();
1643             self.prefetch();
1644             self.animating = false;
1645
1646
1647             self.updateSearchHilites2UP();
1648             self.updatePageNumBox2UP();
1649             
1650             if (self.animationFinishedCallback) {
1651                 self.animationFinishedCallback();
1652                 self.animationFinishedCallback = null;
1653             }
1654         });
1655     });    
1656 }
1657
1658 // setClickHandlers
1659 //______________________________________________________________________________
1660 GnuBook.prototype.setClickHandlers = function() {
1661     var self = this;
1662     // $$$ TODO don't set again if already set
1663     $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1664         //self.prevPage();
1665         self.autoStop();
1666         self.left();
1667     });
1668     $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1669         //self.nextPage();'
1670         self.autoStop();
1671         self.right();        
1672     });
1673     
1674     this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexL]) );
1675     this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexR]) );
1676 }
1677
1678 // prefetchImg()
1679 //______________________________________________________________________________
1680 GnuBook.prototype.prefetchImg = function(index) {
1681     if (undefined == this.prefetchedImgs[index]) {    
1682         //console.log('prefetching ' + index);
1683         var img = document.createElement("img");
1684         img.src = this.getPageURI(index);
1685         this.prefetchedImgs[index] = img;
1686     }
1687 }
1688
1689
1690 // prepareFlipLeftToRight()
1691 //
1692 //______________________________________________________________________________
1693 //
1694 // Prepare to flip the left page towards the right.  This corresponds to moving
1695 // backward when the page progression is left to right.
1696 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1697
1698     //console.log('  preparing left->right for ' + prevL + ',' + prevR);
1699
1700     this.prefetchImg(prevL);
1701     this.prefetchImg(prevR);
1702     
1703     var height  = this.getPageHeight(prevL); 
1704     var width   = this.getPageWidth(prevL);    
1705     var middle = this.twoPage.middle;
1706     var top  = this.twoPageTop();                
1707     var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1708
1709     // The gutter is the dividing line between the left and right pages.
1710     // It is offset from the middle to create the illusion of thickness to the pages
1711     var gutter = middle + this.gutterOffsetForIndex(prevL);
1712     
1713     //console.log('    gutter for ' + prevL + ' is ' + gutter);
1714     //console.log('    prevL.left: ' + (gutter - scaledW) + 'px');
1715     //console.log('    changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1716     
1717     $(this.prefetchedImgs[prevL]).css({
1718         position: 'absolute',
1719         left: gutter-scaledW+'px',
1720         right: '', // clear right property
1721         top:    top+'px',
1722         backgroundColor: 'rgb(234, 226, 205)',
1723         height: this.twoPage.height,
1724         width:  scaledW+'px',
1725         borderRight: '1px solid black',
1726         zIndex: 1
1727     });
1728
1729     $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1730
1731     //console.log('    changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1732
1733     $(this.prefetchedImgs[prevR]).css({
1734         position: 'absolute',
1735         left:   gutter+'px',
1736         right: '',
1737         top:    top+'px',
1738         backgroundColor: 'rgb(234, 226, 205)',
1739         height: this.twoPage.height,
1740         width:  '0px',
1741         borderLeft: '1px solid black',
1742         zIndex: 2
1743     });
1744
1745     $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1746             
1747 }
1748
1749 // $$$ mang we're adding an extra pixel in the middle.  See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1750 // prepareFlipRightToLeft()
1751 //______________________________________________________________________________
1752 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1753
1754     //console.log('  preparing left<-right for ' + nextL + ',' + nextR);
1755
1756     // Prefetch images
1757     this.prefetchImg(nextL);
1758     this.prefetchImg(nextR);
1759
1760     var height  = this.getPageHeight(nextR); 
1761     var width   = this.getPageWidth(nextR);    
1762     var middle = this.twoPage.middle;
1763     var top  = this.twoPageTop();               
1764     var scaledW = this.twoPage.height*width/height;
1765
1766     var gutter = middle + this.gutterOffsetForIndex(nextL);
1767         
1768     //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1769     $(this.prefetchedImgs[nextR]).css({
1770         position: 'absolute',
1771         left:   gutter+'px',
1772         top:    top+'px',
1773         backgroundColor: 'rgb(234, 226, 205)',
1774         height: this.twoPage.height,
1775         width:  scaledW+'px',
1776         borderLeft: '1px solid black',
1777         zIndex: 1
1778     });
1779
1780     $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1781
1782     height  = this.getPageHeight(nextL); 
1783     width   = this.getPageWidth(nextL);      
1784     scaledW = this.twoPage.height*width/height;
1785
1786     //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1787     $(this.prefetchedImgs[nextL]).css({
1788         position: 'absolute',
1789         right:   $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1790         top:    top+'px',
1791         backgroundColor: 'rgb(234, 226, 205)',
1792         height: this.twoPage.height,
1793         width:  0+'px', // Start at 0 width, then grow to the left
1794         borderRight: '1px solid black',
1795         zIndex: 2
1796     });
1797
1798     $('#GBtwopageview').append(this.prefetchedImgs[nextL]);    
1799             
1800 }
1801
1802 // getNextLeafs() -- NOT RTL AWARE
1803 //______________________________________________________________________________
1804 // GnuBook.prototype.getNextLeafs = function(o) {
1805 //     //TODO: we might have two left or two right leafs in a row (damaged book)
1806 //     //For now, assume that leafs are contiguous.
1807 //     
1808 //     //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1809 //     o.L = this.twoPage.currentIndexL+2;
1810 //     o.R = this.twoPage.currentIndexL+3;
1811 // }
1812
1813 // getprevLeafs() -- NOT RTL AWARE
1814 //______________________________________________________________________________
1815 // GnuBook.prototype.getPrevLeafs = function(o) {
1816 //     //TODO: we might have two left or two right leafs in a row (damaged book)
1817 //     //For now, assume that leafs are contiguous.
1818 //     
1819 //     //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1820 //     o.L = this.twoPage.currentIndexL-2;
1821 //     o.R = this.twoPage.currentIndexL-1;
1822 // }
1823
1824 // pruneUnusedImgs()
1825 //______________________________________________________________________________
1826 GnuBook.prototype.pruneUnusedImgs = function() {
1827     //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1828     for (var key in this.prefetchedImgs) {
1829         //console.log('key is ' + key);
1830         if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1831             //console.log('removing key '+ key);
1832             $(this.prefetchedImgs[key]).remove();
1833         }
1834         if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1835             //console.log('deleting key '+ key);
1836             delete this.prefetchedImgs[key];
1837         }
1838     }
1839 }
1840
1841 // prefetch()
1842 //______________________________________________________________________________
1843 GnuBook.prototype.prefetch = function() {
1844
1845     var lim = this.twoPage.currentIndexL-4;
1846     var i;
1847     lim = Math.max(lim, 0);
1848     for (i = lim; i < this.twoPage.currentIndexL; i++) {
1849         this.prefetchImg(i);
1850     }
1851     
1852     if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1853         lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1854         for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1855             this.prefetchImg(i);
1856         }
1857     }
1858 }
1859
1860 // getPageWidth2UP()
1861 //______________________________________________________________________________
1862 GnuBook.prototype.getPageWidth2UP = function(index) {
1863     // We return the width based on the dominant height
1864     var height  = this.getPageHeight(index); 
1865     var width   = this.getPageWidth(index);    
1866     return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
1867 }    
1868
1869 // search()
1870 //______________________________________________________________________________
1871 GnuBook.prototype.search = function(term) {
1872     $('#GnuBookSearchScript').remove();
1873         var script  = document.createElement("script");
1874         script.setAttribute('id', 'GnuBookSearchScript');
1875         script.setAttribute("type", "text/javascript");
1876         script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1877         document.getElementsByTagName('head')[0].appendChild(script);
1878         $('#GnuBookSearchResults').html('Searching...');
1879 }
1880
1881 // GBSearchCallback()
1882 //______________________________________________________________________________
1883 GnuBook.prototype.GBSearchCallback = function(txt) {
1884     //alert(txt);
1885     if (jQuery.browser.msie) {
1886         var dom=new ActiveXObject("Microsoft.XMLDOM");
1887         dom.async="false";
1888         dom.loadXML(txt);    
1889     } else {
1890         var parser = new DOMParser();
1891         var dom = parser.parseFromString(txt, "text/xml");    
1892     }
1893     
1894     $('#GnuBookSearchResults').empty();    
1895     $('#GnuBookSearchResults').append('<ul>');
1896     
1897     for (var key in this.searchResults) {
1898         if (null != this.searchResults[key].div) {
1899             $(this.searchResults[key].div).remove();
1900         }
1901         delete this.searchResults[key];
1902     }
1903     
1904     var pages = dom.getElementsByTagName('PAGE');
1905     
1906     if (0 == pages.length) {
1907         // $$$ it would be nice to echo the (sanitized) search result here
1908         $('#GnuBookSearchResults').append('<li>No search results found</li>');
1909     } else {    
1910         for (var i = 0; i < pages.length; i++){
1911             //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1912     
1913             
1914             var re = new RegExp (/_(\d{4})/);
1915             var reMatch = re.exec(pages[i].getAttribute('file'));
1916             var index = parseInt(reMatch[1], 10);
1917             //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1918             
1919             var children = pages[i].childNodes;
1920             var context = '';
1921             for (var j=0; j<children.length; j++) {
1922                 //console.log(j + ' - ' + children[j].nodeName);
1923                 //console.log(children[j].firstChild.nodeValue);
1924                 if ('CONTEXT' == children[j].nodeName) {
1925                     context += children[j].firstChild.nodeValue;
1926                 } else if ('WORD' == children[j].nodeName) {
1927                     context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1928                     
1929                     var index = this.leafNumToIndex(index);
1930                     if (null != index) {
1931                         //coordinates are [left, bottom, right, top, [baseline]]
1932                         //we'll skip baseline for now...
1933                         var coords = children[j].getAttribute('coords').split(',',4);
1934                         if (4 == coords.length) {
1935                             this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1936                         }
1937                     }
1938                 }
1939             }
1940             var pageName = this.getPageName(index);
1941             //TODO: remove hardcoded instance name
1942             $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1943         }
1944     }
1945     $('#GnuBookSearchResults').append('</ul>');
1946
1947     this.updateSearchHilites();
1948 }
1949
1950 // updateSearchHilites()
1951 //______________________________________________________________________________
1952 GnuBook.prototype.updateSearchHilites = function() {
1953     if (2 == this.mode) {
1954         this.updateSearchHilites2UP();
1955     } else {
1956         this.updateSearchHilites1UP();
1957     }
1958 }
1959
1960 // showSearchHilites1UP()
1961 //______________________________________________________________________________
1962 GnuBook.prototype.updateSearchHilites1UP = function() {
1963
1964     for (var key in this.searchResults) {
1965         
1966         if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1967             var result = this.searchResults[key];
1968             if(null == result.div) {
1969                 result.div = document.createElement('div');
1970                 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1971                 //console.log('appending ' + key);
1972             }    
1973             $(result.div).css({
1974                 width:  (result.r-result.l)/this.reduce + 'px',
1975                 height: (result.b-result.t)/this.reduce + 'px',
1976                 left:   (result.l)/this.reduce + 'px',
1977                 top:    (result.t)/this.reduce +'px'
1978             });
1979
1980         } else {
1981             //console.log(key + ' not displayed');
1982             this.searchResults[key].div=null;
1983         }
1984     }
1985 }
1986
1987 // twoPageGutter()
1988 //______________________________________________________________________________
1989 // Returns the position of the gutter (line between the page images)
1990 GnuBook.prototype.twoPageGutter = function() {
1991     return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1992 }
1993
1994 // twoPageTop()
1995 //______________________________________________________________________________
1996 // Returns the offset for the top of the page images
1997 GnuBook.prototype.twoPageTop = function() {
1998     return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
1999 }
2000
2001 // twoPageCoverWidth()
2002 //______________________________________________________________________________
2003 // Returns the width of the cover div given the total page width
2004 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2005     return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2006 }
2007
2008 // twoPageGetViewCenter()
2009 //______________________________________________________________________________
2010 // Returns the percentage offset into twopageview div at the center of container div
2011 // { percentageX: float, percentageY: float }
2012 GnuBook.prototype.twoPageGetViewCenter = function() {
2013     var center = {};
2014
2015     var containerOffset = $('#GBcontainer').offset();
2016     var viewOffset = $('#GBtwopageview').offset();
2017     center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2018     center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2019     
2020     return center;
2021 }
2022
2023 // twoPageCenterView(percentageX, percentageY)
2024 //______________________________________________________________________________
2025 // Centers the point given by percentage from left,top of twopageview
2026 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2027     if ('undefined' == typeof(percentageX)) {
2028         percentageX = 0.5;
2029     }
2030     if ('undefined' == typeof(percentageY)) {
2031         percentageY = 0.5;
2032     }
2033
2034     var viewWidth = $('#GBtwopageview').width();
2035     var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2036     var intoViewX = percentageX * viewWidth;
2037     
2038     var viewHeight = $('#GBtwopageview').height();
2039     var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2040     var intoViewY = percentageY * viewHeight;
2041     
2042     if (viewWidth < containerClientWidth) {
2043         // Can fit width without scrollbars - center by adjusting offset
2044         $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');    
2045     } else {
2046         // Need to scroll to center
2047         $('#GBtwopageview').css('left', 0);
2048         $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2049     }
2050     
2051     if (viewHeight < containerClientHeight) {
2052         // Fits with scrollbars - add offset
2053         $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2054     } else {
2055         $('#GBtwopageview').css('top', 0);
2056         $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2057     }
2058 }
2059     
2060 // showSearchHilites2UP()
2061 //______________________________________________________________________________
2062 GnuBook.prototype.updateSearchHilites2UP = function() {
2063
2064     for (var key in this.searchResults) {
2065         key = parseInt(key, 10);
2066         if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2067             var result = this.searchResults[key];
2068             if(null == result.div) {
2069                 result.div = document.createElement('div');
2070                 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2071                 //console.log('appending ' + key);
2072             }
2073
2074             // We calculate the reduction factor for the specific page because it can be different
2075             // for each page in the spread
2076             var height = this.getPageHeight(key);
2077             var width  = this.getPageWidth(key)
2078             var reduce = this.twoPage.height/height;
2079             var scaledW = parseInt(width*reduce);
2080             
2081             var gutter = this.twoPageGutter();
2082             var pageL;
2083             if ('L' == this.getPageSide(key)) {
2084                 pageL = gutter-scaledW;
2085             } else {
2086                 pageL = gutter;
2087             }
2088             var pageT  = this.twoPageTop();
2089             
2090             $(result.div).css({
2091                 width:  (result.r-result.l)*reduce + 'px',
2092                 height: (result.b-result.t)*reduce + 'px',
2093                 left:   pageL+(result.l)*reduce + 'px',
2094                 top:    pageT+(result.t)*reduce +'px'
2095             });
2096
2097         } else {
2098             //console.log(key + ' not displayed');
2099             if (null != this.searchResults[key].div) {
2100                 //console.log('removing ' + key);
2101                 $(this.searchResults[key].div).remove();
2102             }
2103             this.searchResults[key].div=null;
2104         }
2105     }
2106 }
2107
2108 // removeSearchHilites()
2109 //______________________________________________________________________________
2110 GnuBook.prototype.removeSearchHilites = function() {
2111     for (var key in this.searchResults) {
2112         if (null != this.searchResults[key].div) {
2113             $(this.searchResults[key].div).remove();
2114             this.searchResults[key].div=null;
2115         }        
2116     }
2117 }
2118
2119 // showEmbedCode()
2120 //______________________________________________________________________________
2121 GnuBook.prototype.showEmbedCode = function() {
2122     if (null != this.embedPopup) { // check if already showing
2123         return;
2124     }
2125     this.autoStop();
2126     this.embedPopup = document.createElement("div");
2127     $(this.embedPopup).css({
2128         position: 'absolute',
2129         top:      '20px',
2130         left:     ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2131         width:    '400px',
2132         padding:  "20px",
2133         border:   "3px double #999999",
2134         zIndex:   3,
2135         backgroundColor: "#fff"
2136     }).appendTo('#GnuBook');
2137
2138     htmlStr =  '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2139     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>';
2140     htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2141     htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';    
2142
2143     this.embedPopup.innerHTML = htmlStr;
2144     $(this.embedPopup).find('input').bind('click', function() {
2145         this.select();
2146     })
2147 }
2148
2149 // autoToggle()
2150 //______________________________________________________________________________
2151 GnuBook.prototype.autoToggle = function() {
2152
2153     var bComingFrom1up = false;
2154     if (2 != this.mode) {
2155         bComingFrom1up = true;
2156         this.switchMode(2);
2157     }
2158     
2159     // Change to autofit if book is too large
2160     if (this.reduce < this.twoPageGetAutofitReduce()) {
2161         this.zoom2up(0);
2162     }
2163
2164     var self = this;
2165     if (null == this.autoTimer) {
2166         this.flipSpeed = 2000;
2167         
2168         // $$$ Draw events currently cause layout problems when they occur during animation.
2169         //     There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2170         //     we workaround for now by not triggering immediate animation in that case.
2171         //     See https://bugs.launchpad.net/gnubook/+bug/328327
2172         if (('rl' == this.pageProgression) && bComingFrom1up) {
2173             // don't flip immediately -- wait until timer fires
2174         } else {
2175             // flip immediately
2176             this.flipFwdToIndex();        
2177         }
2178
2179         $('#GBtoolbar .play').hide();
2180         $('#GBtoolbar .pause').show();
2181         this.autoTimer=setInterval(function(){
2182             if (self.animating) {return;}
2183             
2184             if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2185                 self.flipBackToIndex(1); // $$$ really what we want?
2186             } else {            
2187                 self.flipFwdToIndex();
2188             }
2189         },5000);
2190     } else {
2191         this.autoStop();
2192     }
2193 }
2194
2195 // autoStop()
2196 //______________________________________________________________________________
2197 // Stop autoplay mode, allowing animations to finish
2198 GnuBook.prototype.autoStop = function() {
2199     if (null != this.autoTimer) {
2200         clearInterval(this.autoTimer);
2201         this.flipSpeed = 'fast';
2202         $('#GBtoolbar .pause').hide();
2203         $('#GBtoolbar .play').show();
2204         this.autoTimer = null;
2205     }
2206 }
2207
2208 // stopFlipAnimations
2209 //______________________________________________________________________________
2210 // Immediately stop flip animations.  Callbacks are triggered.
2211 GnuBook.prototype.stopFlipAnimations = function() {
2212
2213     this.autoStop(); // Clear timers
2214
2215     // Stop animation, clear queue, trigger callbacks
2216     if (this.leafEdgeTmp) {
2217         $(this.leafEdgeTmp).stop(false, true);
2218     }
2219     jQuery.each(this.prefetchedImgs, function() {
2220         $(this).stop(false, true);
2221         });
2222
2223     // And again since animations also queued in callbacks
2224     if (this.leafEdgeTmp) {
2225         $(this.leafEdgeTmp).stop(false, true);
2226     }
2227     jQuery.each(this.prefetchedImgs, function() {
2228         $(this).stop(false, true);
2229         });
2230    
2231 }
2232
2233 // keyboardNavigationIsDisabled(event)
2234 //   - returns true if keyboard navigation should be disabled for the event
2235 //______________________________________________________________________________
2236 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2237     if (event.target.tagName == "INPUT") {
2238         return true;
2239     }   
2240     return false;
2241 }
2242
2243 // gutterOffsetForIndex
2244 //______________________________________________________________________________
2245 //
2246 // Returns the gutter offset for the spread containing the given index.
2247 // This function supports RTL
2248 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2249
2250     // To find the offset of the gutter from the middle we calculate our percentage distance
2251     // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2252     var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2253     
2254     // But then again for RTL it's the opposite
2255     if ('rl' == this.pageProgression) {
2256         offset = -offset;
2257     }
2258     
2259     return offset;
2260 }
2261
2262 // leafEdgeWidth
2263 //______________________________________________________________________________
2264 // Returns the width of the leaf edge div for the page with index given
2265 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2266     // $$$ could there be single pixel rounding errors for L vs R?
2267     if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2268         return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2269     } else {
2270         return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2271     }
2272 }
2273
2274 // jumpIndexForLeftEdgePageX
2275 //______________________________________________________________________________
2276 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2277 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2278     if ('rl' != this.pageProgression) {
2279         // LTR - flipping backward
2280         var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2281
2282         // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570        
2283         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2284         return jumpIndex;
2285
2286     } else {
2287         var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2288         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2289         return jumpIndex;
2290     }
2291 }
2292
2293 // jumpIndexForRightEdgePageX
2294 //______________________________________________________________________________
2295 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2296 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2297     if ('rl' != this.pageProgression) {
2298         // LTR
2299         var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2300         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2301         return jumpIndex;
2302     } else {
2303         var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2304         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2305         return jumpIndex;
2306     }
2307 }
2308
2309 GnuBook.prototype.initToolbar = function(mode, ui) {
2310
2311     $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2312         + "<a class='GBicon logo rollover' href='" + this.logoURL + "'>&nbsp;</a>"
2313         + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>" 
2314         + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2315         + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2316         + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2317         + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2318         + "&nbsp;&nbsp;<a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2319         + "</span></div>");
2320     
2321     this.updateToolbarZoom(this.reduce); // Pretty format
2322         
2323     if (ui == "embed") {
2324         $("#GnuBook a.logo").attr("target","_blank");
2325     }
2326
2327     // $$$ turn this into a member variable
2328     var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2329     
2330     // We build in mode 2
2331     jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2332         + "<button class='GBicon rollover embed' />"
2333         + "<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>"
2334         + "<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>"
2335         + "<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>"
2336         + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2337
2338     this.bindToolbarNavHandlers(jToolbar);
2339     
2340     // Setup tooltips -- later we could load these from a file for i18n
2341     var titles = { '.logo': 'Go to Archive.org',
2342                    '.zoom_in': 'Zoom in',
2343                    '.zoom_out': 'Zoom out',
2344                    '.one_page_mode': 'One-page view',
2345                    '.two_page_mode': 'Two-page view',
2346                    '.embed': 'Embed bookreader',
2347                    '.book_left': 'Flip left',
2348                    '.book_right': 'Flip right',
2349                    '.book_up': 'Page up',
2350                    '.book_down': 'Page down',
2351                    '.play': 'Play',
2352                    '.pause': 'Pause',
2353                    '.book_top': 'First page',
2354                    '.book_bottom': 'Last page'
2355                   };
2356     if ('rl' == this.pageProgression) {
2357         titles['.book_leftmost'] = 'Last page';
2358         titles['.book_rightmost'] = 'First page';
2359     } else { // LTR
2360         titles['.book_leftmost'] = 'First page';
2361         titles['.book_rightmost'] = 'Last page';
2362     }
2363                   
2364     for (var icon in titles) {
2365         jToolbar.find(icon).attr('title', titles[icon]);
2366     }
2367     
2368     // Hide mode buttons and autoplay if 2up is not available
2369     // $$$ if we end up with more than two modes we should show the applicable buttons
2370     if ( !this.canSwitchToMode(this.constMode2up) ) {
2371         jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2372     }
2373
2374     // Switch to requested mode -- binds other click handlers
2375     this.switchToolbarMode(mode);
2376
2377 }
2378
2379
2380 // switchToolbarMode
2381 //______________________________________________________________________________
2382 // Update the toolbar for the given mode (changes navigation buttons)
2383 // $$$ we should soon split the toolbar out into its own module
2384 GnuBook.prototype.switchToolbarMode = function(mode) {
2385     if (1 == mode) {
2386         // 1-up     
2387         $('#GBtoolbar .GBtoolbarmode2').hide();
2388         $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2389     } else {
2390         // 2-up
2391         $('#GBtoolbar .GBtoolbarmode1').hide();
2392         $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2393     }
2394 }
2395
2396 // bindToolbarNavHandlers
2397 //______________________________________________________________________________
2398 // Binds the toolbar handlers
2399 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2400
2401     jToolbar.find('.book_left').bind('click', function(e) {
2402         gb.left();
2403         return false;
2404     });
2405          
2406     jToolbar.find('.book_right').bind('click', function(e) {
2407         gb.right();
2408         return false;
2409     });
2410         
2411     jToolbar.find('.book_up').bind('click', function(e) {
2412         gb.prev();
2413         return false;
2414     });        
2415         
2416     jToolbar.find('.book_down').bind('click', function(e) {
2417         gb.next();
2418         return false;
2419     });
2420         
2421     jToolbar.find('.embed').bind('click', function(e) {
2422         gb.showEmbedCode();
2423         return false;
2424     });
2425
2426     jToolbar.find('.play').bind('click', function(e) {
2427         gb.autoToggle();
2428         return false;
2429     });
2430
2431     jToolbar.find('.pause').bind('click', function(e) {
2432         gb.autoToggle();
2433         return false;
2434     });
2435     
2436     jToolbar.find('.book_top').bind('click', function(e) {
2437         gb.first();
2438         return false;
2439     });
2440
2441     jToolbar.find('.book_bottom').bind('click', function(e) {
2442         gb.last();
2443         return false;
2444     });
2445     
2446     jToolbar.find('.book_leftmost').bind('click', function(e) {
2447         gb.leftmost();
2448         return false;
2449     });
2450   
2451     jToolbar.find('.book_rightmost').bind('click', function(e) {
2452         gb.rightmost();
2453         return false;
2454     });
2455 }
2456
2457 // updateToolbarZoom(reduce)
2458 //______________________________________________________________________________
2459 // Update the displayed zoom factor based on reduction factor
2460 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2461     var value;
2462     if (this.constMode2up == this.mode && this.twoPage.autofit) {
2463         value = 'Auto';
2464     } else {
2465         value = (100 / reduce).toFixed(2);
2466         // Strip trailing zeroes and decimal if all zeroes
2467         value = value.replace(/0+$/,'');
2468         value = value.replace(/\.$/,'');
2469         value += '%';
2470     }
2471     $('#GBzoom').text(value);
2472 }
2473
2474 // firstDisplayableIndex
2475 //______________________________________________________________________________
2476 // Returns the index of the first visible page, dependent on the mode.
2477 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2478 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2479 GnuBook.prototype.firstDisplayableIndex = function() {
2480     if (this.mode == 0) {
2481         return 0;
2482     } else {
2483         return 1; // $$$ we assume there are enough pages... we need logic for very short books
2484     }
2485 }
2486
2487 // lastDisplayableIndex
2488 //______________________________________________________________________________
2489 // Returns the index of the last visible page, dependent on the mode.
2490 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2491 // this function when we can as pa  rt of https://bugs.launchpad.net/gnubook/+bug/296788
2492 GnuBook.prototype.lastDisplayableIndex = function() {
2493     if (this.mode == 2) {
2494         if (this.lastDisplayableIndex2up === null) {
2495             // Calculate and cache
2496             var candidate = this.numLeafs - 1;
2497             for ( ; candidate >= 0; candidate--) {
2498                 var spreadIndices = this.getSpreadIndices(candidate);
2499                 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2500                     break;
2501                 }
2502             }
2503             this.lastDisplayableIndex2up = candidate;
2504         }
2505         return this.lastDisplayableIndex2up;
2506     } else {
2507         return this.numLeafs - 1;
2508     }
2509 }
2510
2511 // shortTitle(maximumCharacters)
2512 //________
2513 // Returns a shortened version of the title with the maximum number of characters
2514 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2515     if (this.bookTitle.length < maximumCharacters) {
2516         return this.bookTitle;
2517     }
2518     
2519     var title = this.bookTitle.substr(0, maximumCharacters - 3);
2520     title += '...';
2521     return title;
2522 }
2523
2524
2525
2526 // Parameter related functions
2527
2528 // updateFromParams(params)
2529 //________
2530 // Update ourselves from the params object.
2531 //
2532 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2533 GnuBook.prototype.updateFromParams = function(params) {
2534     if ('undefined' != typeof(params.mode)) {
2535         this.switchMode(params.mode);
2536     }
2537
2538     // $$$ process /search
2539     // $$$ process /zoom
2540     
2541     // We only respect page if index is not set
2542     if ('undefined' != typeof(params.index)) {
2543         if (params.index != this.currentIndex()) {
2544             this.jumpToIndex(params.index);
2545         }
2546     } else if ('undefined' != typeof(params.page)) {
2547         // $$$ this assumes page numbers are unique
2548         if (params.page != this.getPageNum(this.currentIndex())) {
2549             this.jumpToPage(params.page);
2550         }
2551     }
2552     
2553     // $$$ process /region
2554     // $$$ process /highlight
2555 }
2556
2557 // paramsFromFragment(urlFragment)
2558 //________
2559 // Returns a object with configuration parametes from a URL fragment.
2560 //
2561 // E.g paramsFromFragment(window.location.hash)
2562 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2563     // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2564     
2565     var params = {};
2566     
2567     // For convenience we allow an initial # character (as from window.location.hash)
2568     // but don't require it
2569     if (urlFragment.substr(0,1) == '#') {
2570         urlFragment = urlFragment.substr(1);
2571     }
2572     
2573     // Simple #nn syntax
2574     var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2575     if ( !isNaN(oldStyleLeafNum) ) {
2576         params.index = oldStyleLeafNum;
2577         
2578         // Done processing if using old-style syntax
2579         return params;
2580     }
2581     
2582     // Split into key-value pairs
2583     var urlArray = urlFragment.split('/');
2584     var urlHash = {};
2585     for (var i = 0; i < urlArray.length; i += 2) {
2586         urlHash[urlArray[i]] = urlArray[i+1];
2587     }
2588     
2589     // Mode
2590     if ('1up' == urlHash['mode']) {
2591         params.mode = this.constMode1up;
2592     } else if ('2up' == urlHash['mode']) {
2593         params.mode = this.constMode2up;
2594     }
2595     
2596     // Index and page
2597     if ('undefined' != typeof(urlHash['page'])) {
2598         // page was set -- may not be int
2599         params.page = urlHash['page'];
2600     }
2601     
2602     // $$$ process /region
2603     // $$$ process /search
2604     // $$$ process /highlight
2605         
2606     return params;
2607 }
2608
2609 // paramsFromCurrent()
2610 //________
2611 // Create a params object from the current parameters.
2612 GnuBook.prototype.paramsFromCurrent = function() {
2613
2614     var params = {};
2615
2616     var pageNum = this.getPageNum(this.currentIndex());
2617     if ((pageNum === 0) || pageNum) {
2618         params.page = pageNum;
2619     }
2620     
2621     params.index = this.currentIndex();
2622     params.mode = this.mode;
2623     
2624     // $$$ highlight
2625     // $$$ region
2626     // $$$ search
2627     
2628     return params;
2629 }
2630
2631 // fragmentFromParams(params)
2632 //________
2633 // Create a fragment string from the params object.
2634 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2635 GnuBook.prototype.fragmentFromParams = function(params) {
2636     var separator = '/';
2637     
2638     var fragments = [];
2639     
2640     if ('undefined' != typeof(params.page)) {
2641         fragments.push('page', params.page);
2642     } else {
2643         // Don't have page numbering -- use index instead
2644         fragments.push('page', 'n' + params.index);
2645     }
2646     
2647     // $$$ highlight
2648     // $$$ region
2649     // $$$ search
2650     
2651     // mode
2652     if ('undefined' != typeof(params.mode)) {    
2653         if (params.mode == this.constMode1up) {
2654             fragments.push('mode', '1up');
2655         } else if (params.mode == this.constMode2up) {
2656             fragments.push('mode', '2up');
2657         } else {
2658             throw 'fragmentFromParams called with unknown mode ' + params.mode;
2659         }
2660     }
2661     
2662     return fragments.join(separator);
2663 }
2664
2665 // getPageIndex(pageNum)
2666 //________
2667 // Returns the *highest* index the given page number, or undefined
2668 GnuBook.prototype.getPageIndex = function(pageNum) {
2669     var pageIndices = this.getPageIndices(pageNum);
2670     
2671     if (pageIndices.length > 0) {
2672         return pageIndices[pageIndices.length - 1];
2673     }
2674
2675     return undefined;
2676 }
2677
2678 // getPageIndices(pageNum)
2679 //________
2680 // Returns an array (possibly empty) of the indices with the given page number
2681 GnuBook.prototype.getPageIndices = function(pageNum) {
2682     var indices = [];
2683
2684     // Check for special "nXX" page number
2685     if (pageNum.slice(0,1) == 'n') {
2686         try {
2687             var pageIntStr = pageNum.slice(1, pageNum.length);
2688             var pageIndex = parseInt(pageIntStr);
2689             indices.append(pageIndex);
2690             return indices;
2691         } catch(err) {
2692             // Do nothing... will run through page names and see if one matches
2693         }
2694     }
2695
2696     var i;
2697     for (i=0; i<this.numLeafs; i++) {
2698         if (this.getPageNum(i) == pageNum) {
2699             indices.push(i);
2700         }
2701     }
2702     
2703     return indices;
2704 }
2705
2706 // getPageName(index)
2707 //________
2708 // Returns the name of the page as it should be displayed in the user interface
2709 GnuBook.prototype.getPageName = function(index) {
2710     return 'Page ' + this.getPageNum(index);
2711 }
2712
2713 // updateLocationHash
2714 //________
2715 // Update the location hash from the current parameters.  Call this instead of manually
2716 // using window.location.replace
2717 GnuBook.prototype.updateLocationHash = function() {
2718     var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2719     window.location.replace(newHash);
2720     
2721     // This is the variable checked in the timer.  Only user-generated changes
2722     // to the URL will trigger the event.
2723     this.oldLocationHash = newHash;
2724 }
2725
2726 // startLocationPolling
2727 //________
2728 // Starts polling of window.location to see hash fragment changes
2729 GnuBook.prototype.startLocationPolling = function() {
2730     var self = this; // remember who I am
2731     self.oldLocationHash = window.location.hash;
2732     
2733     if (this.locationPollId) {
2734         clearInterval(this.locationPollID);
2735         this.locationPollId = null;
2736     }
2737     
2738     this.locationPollId = setInterval(function() {
2739         var newHash = window.location.hash;
2740         if (newHash != self.oldLocationHash) {
2741             if (newHash != self.oldUserHash) { // Only process new user hash once
2742                 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2743                 
2744                 // Queue change if animating
2745                 if (self.animating) {
2746                     self.autoStop();
2747                     self.animationFinishedCallback = function() {
2748                         self.updateFromParams(self.paramsFromFragment(newHash));
2749                     }                        
2750                 } else { // update immediately
2751                     self.updateFromParams(self.paramsFromFragment(newHash));
2752                 }
2753                 self.oldUserHash = newHash;
2754             }
2755         }
2756     }, 500);
2757 }
2758
2759 // getEmbedURL
2760 //________
2761 // Returns a URL for an embedded version of the current book
2762 GnuBook.prototype.getEmbedURL = function() {
2763     // We could generate a URL hash fragment here but for now we just leave at defaults
2764     return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2765 }
2766
2767 // getEmbedCode
2768 //________
2769 // Returns the embed code HTML fragment suitable for copy and paste
2770 GnuBook.prototype.getEmbedCode = function() {
2771     return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2772 }
2773
2774 // canSwitchToMode
2775 //________
2776 // Returns true if we can switch to the requested mode
2777 GnuBook.prototype.canSwitchToMode = function(mode) {
2778     if (mode == this.constMode2up) {
2779         // check there are enough pages to display
2780         // $$$ this is a workaround for the mis-feature that we can't display
2781         //     short books in 2up mode
2782         if (this.numLeafs < 6) {
2783             return false;
2784         }
2785     }
2786     
2787     return true;
2788 }
2789
2790 // Library functions
2791 GnuBook.util = {
2792     clamp: function(value, min, max) {
2793         return Math.min(Math.max(value, min), max);
2794     }
2795 }