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