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