Fix for icons being cut off in embed version.
[bookreader.git] / GnuBook / GnuBook.js
1 /*
2 Copyright(c)2008 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.69 $ $Date: 2009-04-01 22:00: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     
38     this.displayedLeafs = [];   
39     //this.leafsToDisplay = [];
40     this.imgs = {};
41     this.prefetchedImgs = {}; //an object with numeric keys cooresponding to leafNum
42     
43     this.timer     = null;
44     this.animating = false;
45     this.auto      = false;
46     this.autoTimer = null;
47     this.flipSpeed = 'fast';
48
49     this.twoPagePopUp = null;
50     this.leafEdgeTmp  = null;
51     this.embedPopup = null;
52     
53     this.searchResults = {};
54     
55     this.firstIndex = null;
56     
57     this.lastDisplayableIndex2up = null;
58     
59     // We link to index.php to avoid redirect which breaks back button
60     this.logoURL = 'http://www.archive.org/index.php';
61     
62 };
63
64 // init()
65 //______________________________________________________________________________
66 GnuBook.prototype.init = function() {
67     var startLeaf = window.location.hash;
68     //console.log("startLeaf from location.hash: %s", startLeaf);
69     if ('' == startLeaf) {
70         if (this.titleLeaf) {
71             startLeaf = "#" + this.leafNumToIndex(this.titleLeaf);
72         }
73     }
74     
75     // Ideally this would be set in the HTML/PHP for better search engine visibility but
76     // it takes some time to locate the item and retrieve the metadata
77     document.title = this.shortTitle(50);
78     
79     $("#GnuBook").empty();
80     this.initToolbar(this.mode); // Build inside of toolbar div
81     $("#GnuBook").append("<div id='GBcontainer'></div>");
82     $("#GBcontainer").append("<div id='GBpageview'></div>");
83
84     $("#GBcontainer").bind('scroll', this, function(e) {
85         e.data.loadLeafs();
86     });
87
88     this.setupKeyListeners();
89
90     $(window).bind('resize', this, function(e) {
91         //console.log('resize!');
92         if (1 == e.data.mode) {
93             //console.log('centering 1page view');
94             e.data.centerPageView();
95             $('#GBpageview').empty()
96             e.data.displayedLeafs = [];
97             e.data.updateSearchHilites(); //deletes hilights but does not call remove()            
98             e.data.loadLeafs();
99         } else {
100             //console.log('drawing 2 page view');
101             e.data.prepareTwoPageView();
102         }
103     });
104     
105     $('.GBpagediv1up').bind('mousedown', this, function(e) {
106         //console.log('mousedown!');
107     });
108
109     if (1 == this.mode) {
110         this.resizePageView();
111     
112         if ('' != startLeaf) { // Jump to the leaf specified in the URL
113             this.jumpToIndex(parseInt(startLeaf.substr(1)));
114             //console.log('jump to ' + parseInt(startLeaf.substr(1)));
115         }
116     } else {
117         //this.resizePageView();
118         
119         this.displayedLeafs=[0];
120         if ('' != startLeaf) {
121             this.displayedLeafs = [parseInt(startLeaf.substr(1))];
122         }
123         //console.log('titleLeaf: %d', this.titleLeaf);
124         //console.log('displayedLeafs: %s', this.displayedLeafs);
125         this.prepareTwoPageView();
126         //if (this.auto) this.nextPage();
127     }
128 }
129
130 GnuBook.prototype.setupKeyListeners = function() {
131     var self = this;
132
133     var KEY_PGUP = 33;
134     var KEY_PGDOWN = 34;
135     var KEY_END = 35;
136     var KEY_HOME = 36;
137
138     var KEY_LEFT = 37;
139     var KEY_UP = 38;
140     var KEY_RIGHT = 39;
141     var KEY_DOWN = 40;
142
143     // We use document here instead of window to avoid a bug in jQuery on IE7
144     $(document).keydown(function(e) {
145         
146         // Keyboard navigation        
147         switch(e.keyCode) {
148             case KEY_PGUP:
149             case KEY_UP:            
150                 // In 1up mode page scrolling is handled by browser
151                 if (2 == self.mode) {
152                     self.prev();
153                 }
154                 break;
155             case KEY_DOWN:
156             case KEY_PGDOWN:
157                 if (2 == self.mode) {
158                     self.next();
159                 }
160                 break;
161             case KEY_END:
162                 self.end();
163                 break;
164             case KEY_HOME:
165                 self.home();
166                 break;
167             case KEY_LEFT:
168                 if (self.keyboardNavigationIsDisabled(e)) {
169                     break;
170                 }
171                 if (2 == self.mode) {
172                     self.left();
173                 }
174                 break;
175             case KEY_RIGHT:
176                 if (self.keyboardNavigationIsDisabled(e)) {
177                     break;
178                 }
179                 if (2 == self.mode) {
180                     self.right();
181                 }
182                 break;
183         }
184     });
185 }
186
187 // drawLeafs()
188 //______________________________________________________________________________
189 GnuBook.prototype.drawLeafs = function() {
190     if (1 == this.mode) {
191         this.drawLeafsOnePage();
192     } else {
193         this.drawLeafsTwoPage();
194     }
195 }
196
197 // setDragHandler1up()
198 //______________________________________________________________________________
199 GnuBook.prototype.setDragHandler1up = function(div) {
200     div.dragging = false;
201
202     $(div).bind('mousedown', function(e) {
203         //console.log('mousedown at ' + e.pageY);
204
205         this.dragging = true;
206         this.prevMouseX = e.pageX;
207         this.prevMouseY = e.pageY;
208     
209         var startX    = e.pageX;
210         var startY    = e.pageY;
211         var startTop  = $('#GBcontainer').attr('scrollTop');
212         var startLeft =  $('#GBcontainer').attr('scrollLeft');
213
214         return false;
215     });
216         
217     $(div).bind('mousemove', function(ee) {
218         //console.log('mousemove ' + startY);
219         
220         var offsetX = ee.pageX - this.prevMouseX;
221         var offsetY = ee.pageY - this.prevMouseY;
222         
223         if (this.dragging) {
224             $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
225             $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
226         }
227         
228         this.prevMouseX = ee.pageX;
229         this.prevMouseY = ee.pageY;
230         
231         return false;
232     });
233     
234     $(div).bind('mouseup', function(ee) {
235         //console.log('mouseup');
236
237         this.dragging = false;
238         return false;
239     });
240     
241     $(div).bind('mouseleave', function(e) {
242         //console.log('mouseleave');
243
244         //$(this).unbind('mousemove mouseup');
245         this.dragging = false;
246         
247     });
248 }
249
250 // drawLeafsOnePage()
251 //______________________________________________________________________________
252 GnuBook.prototype.drawLeafsOnePage = function() {
253     //alert('drawing leafs!');
254     this.timer = null;
255
256
257     var scrollTop = $('#GBcontainer').attr('scrollTop');
258     var scrollBottom = scrollTop + $('#GBcontainer').height();
259     //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
260     
261     var leafsToDisplay = [];
262     
263     var i;
264     var leafTop = 0;
265     var leafBottom = 0;
266     for (i=0; i<this.numLeafs; i++) {
267         var height  = parseInt(this.getPageHeight(i)/this.reduce); 
268     
269         leafBottom += height;
270         //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
271         var topInView    = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
272         var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
273         var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
274         if (topInView | bottomInView | middleInView) {
275             //console.log('to display: ' + i);
276             leafsToDisplay.push(i);
277         }
278         leafTop += height +10;      
279         leafBottom += 10;
280     }
281
282     var firstLeafToDraw  = leafsToDisplay[0];
283     window.location.replace('#' + firstLeafToDraw);
284     this.firstIndex      = firstLeafToDraw;
285
286     if ((0 != firstLeafToDraw) && (1 < this.reduce)) {
287         firstLeafToDraw--;
288         leafsToDisplay.unshift(firstLeafToDraw);
289     }
290     
291     var lastLeafToDraw = leafsToDisplay[leafsToDisplay.length-1];
292     if ( ((this.numLeafs-1) != lastLeafToDraw) && (1 < this.reduce) ) {
293         leafsToDisplay.push(lastLeafToDraw+1);
294     }
295     
296     leafTop = 0;
297     var i;
298     for (i=0; i<firstLeafToDraw; i++) {
299         leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
300     }
301
302     //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
303     var viewWidth = $('#GBcontainer').attr('scrollWidth');
304
305
306     for (i=0; i<leafsToDisplay.length; i++) {
307         var leafNum = leafsToDisplay[i];    
308         var height  = parseInt(this.getPageHeight(leafNum)/this.reduce); 
309
310         if(-1 == jQuery.inArray(leafsToDisplay[i], this.displayedLeafs)) {            
311             var width   = parseInt(this.getPageWidth(leafNum)/this.reduce); 
312             //console.log("displaying leaf " + leafsToDisplay[i] + ' leafTop=' +leafTop);
313             var div = document.createElement("div");
314             div.className = 'GBpagediv1up';
315             div.id = 'pagediv'+leafNum;
316             div.style.position = "absolute";
317             $(div).css('top', leafTop + 'px');
318             var left = (viewWidth-width)>>1;
319             if (left<0) left = 0;
320             $(div).css('left', left+'px');
321             $(div).css('width', width+'px');
322             $(div).css('height', height+'px');
323             //$(div).text('loading...');
324             
325             this.setDragHandler1up(div);
326             
327             $('#GBpageview').append(div);
328
329             var img = document.createElement("img");
330             img.src = this.getPageURI(leafNum);
331             $(img).css('width', width+'px');
332             $(img).css('height', height+'px');
333             $(div).append(img);
334
335         } else {
336             //console.log("not displaying " + leafsToDisplay[i] + ' score=' + jQuery.inArray(leafsToDisplay[i], this.displayedLeafs));            
337         }
338
339         leafTop += height +10;
340
341     }
342     
343     for (i=0; i<this.displayedLeafs.length; i++) {
344         if (-1 == jQuery.inArray(this.displayedLeafs[i], leafsToDisplay)) {
345             var leafNum = this.displayedLeafs[i];
346             //console.log('Removing leaf ' + leafNum);
347             //console.log('id='+'#pagediv'+leafNum+ ' top = ' +$('#pagediv'+leafNum).css('top'));
348             $('#pagediv'+leafNum).remove();
349         } else {
350             //console.log('NOT Removing leaf ' + this.displayedLeafs[i]);
351         }
352     }
353     
354     this.displayedLeafs = leafsToDisplay.slice();
355     this.updateSearchHilites();
356     
357     if (null != this.getPageNum(firstLeafToDraw))  {
358         $("#GBpagenum").val(this.getPageNum(firstLeafToDraw));
359     } else {
360         $("#GBpagenum").val('');
361     }
362 }
363
364 // drawLeafsTwoPage()
365 //______________________________________________________________________________
366 GnuBook.prototype.drawLeafsTwoPage = function() {
367     //alert('drawing two leafs!');
368
369     var scrollTop = $('#GBcontainer').attr('scrollTop');
370     var scrollBottom = scrollTop + $('#GBcontainer').height();
371     
372     //console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.currentLeafL);
373     
374     var leafNum = this.currentLeafL;
375     var height  = this.getPageHeight(leafNum); 
376     var width   = this.getPageWidth(leafNum);
377     var handSide= this.getPageSide(leafNum);
378
379     var leafEdgeWidthL = this.leafEdgeWidth(leafNum);
380     var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
381     var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
382     var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
383     //console.log(leafEdgeWidthL);
384
385     var middle = ($('#GBcontainer').width() >> 1);            
386     var left = middle - this.twoPageW;
387     var top  = ($('#GBcontainer').height() - this.twoPageH) >> 1;                
388
389     var scaledW = parseInt(this.twoPageH*width/height);
390     left = 10+leafEdgeWidthL;
391     //var right = left+scaledW;
392     var right = $(this.twoPageDiv).width()-11-$(this.leafEdgeL).width()-scaledW;
393
394     var gutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
395     
396     this.prefetchImg(leafNum);
397     $(this.prefetchedImgs[leafNum]).css({
398         position: 'absolute',
399         /*right:   gutter+'px',*/
400         left: gutter-scaledW+'px',
401         right: '',
402         top:    top+'px',
403         backgroundColor: 'rgb(234, 226, 205)',
404         height: this.twoPageH +'px',
405         width:  scaledW + 'px',
406         borderRight: '1px solid black',
407         zIndex: 2
408     }).appendTo('#GBcontainer');
409     //$('#GBcontainer').append(this.prefetchedImgs[leafNum]);
410
411
412     var leafNum = this.currentLeafR;
413     var height  = this.getPageHeight(leafNum); 
414     var width   = this.getPageWidth(leafNum);
415     //    var left = ($('#GBcontainer').width() >> 1);
416     left += scaledW;
417
418     var scaledW = this.twoPageH*width/height;
419     this.prefetchImg(leafNum);
420     $(this.prefetchedImgs[leafNum]).css({
421         position: 'absolute',
422         left:   gutter+'px',
423         right: '',
424         top:    top+'px',
425         backgroundColor: 'rgb(234, 226, 205)',
426         height: this.twoPageH + 'px',
427         width:  scaledW + 'px',
428         borderLeft: '1px solid black',
429         zIndex: 2
430     }).appendTo('#GBcontainer');
431     //$('#GBcontainer').append(this.prefetchedImgs[leafNum]);
432         
433
434     this.displayedLeafs = [this.currentLeafL, this.currentLeafR];
435     this.setClickHandlers();
436
437     this.updatePageNumBox2UP();
438 }
439
440 // updatePageNumBox2UP
441 //______________________________________________________________________________
442 GnuBook.prototype.updatePageNumBox2UP = function() {
443     if (null != this.getPageNum(this.currentLeafL))  {
444         $("#GBpagenum").val(this.getPageNum(this.currentLeafL));
445     } else {
446         $("#GBpagenum").val('');
447     }
448     window.location.replace('#' + this.currentLeafL); 
449 }
450
451 // loadLeafs()
452 //______________________________________________________________________________
453 GnuBook.prototype.loadLeafs = function() {
454
455
456     var self = this;
457     if (null == this.timer) {
458         this.timer=setTimeout(function(){self.drawLeafs()},250);
459     } else {
460         clearTimeout(this.timer);
461         this.timer=setTimeout(function(){self.drawLeafs()},250);    
462     }
463 }
464
465
466 // zoom1up()
467 //______________________________________________________________________________
468 GnuBook.prototype.zoom1up = function(dir) {
469     if (2 == this.mode) {     //can only zoom in 1-page mode
470         this.switchMode(1);
471         return;
472     }
473     
474     if (1 == dir) {
475         if (this.reduce <= 0.5) return;
476         this.reduce*=0.5;           //zoom in
477     } else {
478         if (this.reduce >= 8) return;
479         this.reduce*=2;             //zoom out
480     }
481     
482     this.resizePageView();
483
484     $('#GBpageview').empty()
485     this.displayedLeafs = [];
486     this.loadLeafs();
487     
488     $('#GBzoom').text(100/this.reduce);
489 }
490
491
492 // resizePageView()
493 //______________________________________________________________________________
494 GnuBook.prototype.resizePageView = function() {
495     var i;
496     var viewHeight = 0;
497     //var viewWidth  = $('#GBcontainer').width(); //includes scrollBar
498     var viewWidth  = $('#GBcontainer').attr('clientWidth');   
499
500     var oldScrollTop  = $('#GBcontainer').attr('scrollTop');
501     var oldViewHeight = $('#GBpageview').height();
502     if (0 != oldViewHeight) {
503         var scrollRatio = oldScrollTop / oldViewHeight;
504     } else {
505         var scrollRatio = 0;
506     }
507     
508     for (i=0; i<this.numLeafs; i++) {
509         viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding; 
510         var width = parseInt(this.getPageWidth(i)/this.reduce);
511         if (width>viewWidth) viewWidth=width;
512     }
513     $('#GBpageview').height(viewHeight);
514     $('#GBpageview').width(viewWidth);    
515
516     $('#GBcontainer').attr('scrollTop', Math.floor(scrollRatio*viewHeight));
517     
518     this.centerPageView();
519     this.loadLeafs();
520     
521 }
522
523 // centerPageView()
524 //______________________________________________________________________________
525 GnuBook.prototype.centerPageView = function() {
526
527     var scrollWidth  = $('#GBcontainer').attr('scrollWidth');
528     var clientWidth  =  $('#GBcontainer').attr('clientWidth');
529     //console.log('sW='+scrollWidth+' cW='+clientWidth);
530     if (scrollWidth > clientWidth) {
531         $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
532     }
533
534 }
535
536 // jumpToPage()
537 //______________________________________________________________________________
538 GnuBook.prototype.jumpToPage = function(pageNum) {
539
540     var i;
541     var foundPage = false;
542     var foundLeaf = null;
543     for (i=0; i<this.numLeafs; i++) {
544         if (this.getPageNum(i) == pageNum) {
545             foundPage = true;
546             foundLeaf = i;
547             break;
548         }
549     }
550     
551     if (foundPage) {
552         var leafTop = 0;
553         var h;
554         this.jumpToIndex(foundLeaf);
555         $('#GBcontainer').attr('scrollTop', leafTop);
556     } else {
557         alert('Page not found. This book might not have pageNumbers in scandata.');
558     }
559 }
560
561 // jumpToIndex()
562 //______________________________________________________________________________
563 GnuBook.prototype.jumpToIndex = function(index) {
564
565     if (2 == this.mode) {
566         this.autoStop();
567         
568         // By checking against min/max we do nothing if requested index
569         // is current
570         if (index < Math.min(this.currentLeafL, this.currentLeafR)) {
571             this.flipBackToIndex(index);
572         } else if (index > Math.max(this.currentLeafL, this.currentLeafR)) {
573             this.flipFwdToIndex(index);
574         }
575
576     } else {        
577         var i;
578         var leafTop = 0;
579         var h;
580         for (i=0; i<index; i++) {
581             h = parseInt(this.getPageHeight(i)/this.reduce); 
582             leafTop += h + this.padding;
583         }
584         //$('#GBcontainer').attr('scrollTop', leafTop);
585         $('#GBcontainer').animate({scrollTop: leafTop },'fast');    
586     }
587 }
588
589
590
591 // switchMode()
592 //______________________________________________________________________________
593 GnuBook.prototype.switchMode = function(mode) {
594
595     //console.log('  asked to switch to mode ' + mode + ' from ' + this.mode);
596     
597     if (mode == this.mode) return;
598
599     this.autoStop();
600     this.removeSearchHilites();
601
602     this.mode = mode;
603     
604     this.switchToolbarMode(mode);
605     
606     if (1 == mode) {
607         this.prepareOnePageView();
608     } else {
609         this.prepareTwoPageView();
610     }
611
612 }
613
614 //prepareOnePageView()
615 //______________________________________________________________________________
616 GnuBook.prototype.prepareOnePageView = function() {
617
618     var startLeaf = this.displayedLeafs[0];
619     
620     $('#GBcontainer').empty();
621     $('#GBcontainer').css({
622         overflowY: 'scroll',
623         overflowX: 'auto'
624     });
625     
626     var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
627     this.resizePageView();
628     this.jumpToIndex(startLeaf);
629     this.displayedLeafs = [];    
630     this.drawLeafsOnePage();
631     $('#GBzoom').text(100/this.reduce);
632     
633     // Bind mouse handlers
634     // Disable mouse click to avoid selected/highlighted page images - bug 354239
635     gbPageView.bind('mousedown', function(e) {
636         return false;
637     })
638     // Special hack for IE7
639     gbPageView[0].onselectstart = function(e) { return false; };
640 }
641
642 // prepareTwoPageView()
643 //______________________________________________________________________________
644 GnuBook.prototype.prepareTwoPageView = function() {
645     $('#GBcontainer').empty();
646
647     // We want to display two facing pages.  We may be missing
648     // one side of the spread because it is the first/last leaf,
649     // foldouts, missing pages, etc
650
651     var targetLeaf = this.displayedLeafs[0];
652     
653     if (targetLeaf < this.firstDisplayableIndex()) {
654         targetLeaf = this.firstDisplayableIndex();
655     }
656     
657     if (targetLeaf > this.lastDisplayableIndex()) {
658         targetLeaf = this.lastDisplayableIndex();
659     }
660     
661     this.currentLeafL = null;
662     this.currentLeafR = null;
663     this.pruneUnusedImgs();
664     
665     var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
666     this.currentLeafL = currentSpreadIndices[0];
667     this.currentLeafR = currentSpreadIndices[1];
668     
669     this.calculateSpreadSize(); //sets this.twoPageW, twoPageH, and twoPageRatio
670
671     // We want to minimize the unused space in two-up mode (maximize the amount of page
672     // shown).  We give width to the leaf edges and these widths change (though the sum
673     // of the two remains constant) as we flip through the book.  With the book
674     // cover centered and fixed in the GBcontainer div the page images will meet
675     // at the "gutter" which is generally offset from the center.
676     var middle = ($('#GBcontainer').width() >> 1); // Middle of the GBcontainer div
677     //var gutter = middle+parseInt((2*this.currentLeafL - this.numLeafs)*this.twoPageEdgeW/this.numLeafs/2);
678     
679     var gutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
680     
681     var scaledWL = this.getPageWidth2UP(this.currentLeafL);
682     var scaledWR = this.getPageWidth2UP(this.currentLeafR);
683     var leafEdgeWidthL = this.leafEdgeWidth(this.currentLeafL);
684     var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
685
686     //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
687     //var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
688     
689     // The width of the book cover div.  The combined width of both pages, twice the width
690     // of the book cover internal padding (2*10) and the page edges
691     var bookCoverDivWidth = scaledWL + scaledWR + 20 + this.twoPageEdgeW;
692     
693     // The height of the book cover div
694     var bookCoverDivHeight = this.twoPageH+20;
695     
696     //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
697     var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-10;
698     var bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
699     //console.log('bookCoverDivWidth='+bookCoverDivWidth+' bookCoverDivHeight='+bookCoverDivHeight+ ' bookCoverDivLeft='+bookCoverDivLeft+' bookCoverDivTop='+bookCoverDivTop);
700
701     this.twoPageDiv = document.createElement('div');
702     $(this.twoPageDiv).attr('id', 'book_div_1').css({
703         border: '1px solid rgb(68, 25, 17)',
704         width:  bookCoverDivWidth + 'px',
705         height: bookCoverDivHeight+'px',
706         visibility: 'visible',
707         position: 'absolute',
708         backgroundColor: '#663929',
709         left: bookCoverDivLeft + 'px',
710         top: bookCoverDivTop+'px',
711         MozBorderRadiusTopleft: '7px',
712         MozBorderRadiusTopright: '7px',
713         MozBorderRadiusBottomright: '7px',
714         MozBorderRadiusBottomleft: '7px'
715     }).appendTo('#GBcontainer');
716     //$('#GBcontainer').append('<div id="book_div_1" style="border: 1px solid rgb(68, 25, 17); width: ' + bookCoverDivWidth + 'px; height: '+bookCoverDivHeight+'px; visibility: visible; position: absolute; background-color: rgb(136, 51, 34); left: ' + bookCoverDivLeft + 'px; top: '+bookCoverDivTop+'px; -moz-border-radius-topleft: 7px; -moz-border-radius-topright: 7px; -moz-border-radius-bottomright: 7px; -moz-border-radius-bottomleft: 7px;"/>');
717
718
719     var height  = this.getPageHeight(this.currentLeafR); 
720     var width   = this.getPageWidth(this.currentLeafR);    
721     var scaledW = this.twoPageH*width/height;
722     
723     this.leafEdgeR = document.createElement('div');
724     this.leafEdgeR.className = 'leafEdgeR';
725     $(this.leafEdgeR).css({
726         borderStyle: 'solid solid solid none',
727         borderColor: 'rgb(51, 51, 34)',
728         borderWidth: '1px 1px 1px 0px',
729         background: 'transparent url(images/right_edges.png) repeat scroll 0% 0%',
730         width: leafEdgeWidthR + 'px',
731         height: this.twoPageH-1 + 'px',
732         /*right: '10px',*/
733         left: gutter+scaledW+'px',
734         top: bookCoverDivTop+10+'px',
735         position: 'absolute'
736     }).appendTo('#GBcontainer');
737     
738     this.leafEdgeL = document.createElement('div');
739     this.leafEdgeL.className = 'leafEdgeL';
740     $(this.leafEdgeL).css({
741         borderStyle: 'solid none solid solid',
742         borderColor: 'rgb(51, 51, 34)',
743         borderWidth: '1px 0px 1px 1px',
744         background: 'transparent url(images/left_edges.png) repeat scroll 0% 0%',
745         width: leafEdgeWidthL + 'px',
746         height: this.twoPageH-1 + 'px',
747         left: bookCoverDivLeft+10+'px',
748         top: bookCoverDivTop+10+'px',    
749         position: 'absolute'
750     }).appendTo('#GBcontainer');
751
752
753
754     bookCoverDivWidth = 30;
755     bookCoverDivHeight = this.twoPageH+20;
756     bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
757     bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
758
759     div = document.createElement('div');
760     $(div).attr('id', 'book_div_2').css({
761         border:          '1px solid rgb(68, 25, 17)',
762         width:           bookCoverDivWidth+'px',
763         height:          bookCoverDivHeight+'px',
764         position:        'absolute',
765         backgroundColor: 'rgb(68, 25, 17)',
766         left:            bookCoverDivLeft+'px',
767         top:             bookCoverDivTop+'px'
768     }).appendTo('#GBcontainer');
769     //$('#GBcontainer').append('<div id="book_div_2" style="border: 1px solid rgb(68, 25, 17); width: '+bookCoverDivWidth+'px; height: '+bookCoverDivHeight+'px; visibility: visible; position: absolute; background-color: rgb(68, 25, 17); left: '+bookCoverDivLeft+'px; top: '+bookCoverDivTop+'px;"/>');
770
771     bookCoverDivWidth = this.twoPageW*2;
772     bookCoverDivHeight = this.twoPageH;
773     bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
774     bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
775
776
777     this.prepareTwoPagePopUp();
778
779     this.displayedLeafs = [];
780     
781     //this.leafsToDisplay=[firstLeaf, firstLeaf+1];
782     //console.log('leafsToDisplay: ' + this.leafsToDisplay[0] + ' ' + this.leafsToDisplay[1]);
783     
784     this.drawLeafsTwoPage();
785     this.updateSearchHilites2UP();
786     
787     this.prefetch();
788     $('#GBzoom').text((100*this.twoPageH/this.getPageHeight(this.currentLeafL)).toString().substr(0,4));
789 }
790
791 // prepareTwoPagePopUp()
792 //
793 // This function prepares the "View leaf n" popup that shows while the mouse is
794 // over the left/right "stack of sheets" edges.  It also binds the mouse
795 // events for these divs.
796 //______________________________________________________________________________
797 GnuBook.prototype.prepareTwoPagePopUp = function() {
798     this.twoPagePopUp = document.createElement('div');
799     $(this.twoPagePopUp).css({
800         border: '1px solid black',
801         padding: '2px 6px',
802         position: 'absolute',
803         fontFamily: 'sans-serif',
804         fontSize: '14px',
805         zIndex: '1000',
806         backgroundColor: 'rgb(255, 255, 238)',
807         opacity: 0.85
808     }).appendTo('#GBcontainer');
809     $(this.twoPagePopUp).hide();
810     
811     $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
812         $(e.data.twoPagePopUp).show();
813     });
814
815     $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
816         $(e.data.twoPagePopUp).hide();
817     });
818
819     $(this.leafEdgeL).bind('click', this, function(e) { 
820         e.data.autoStop();
821         var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
822         e.data.jumpToIndex(jumpIndex);
823     });
824
825     $(this.leafEdgeR).bind('click', this, function(e) { 
826         e.data.autoStop();
827         var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
828         e.data.jumpToIndex(jumpIndex);    
829     });
830
831     $(this.leafEdgeR).bind('mousemove', this, function(e) {
832
833         var jumpLeaf = e.data.jumpIndexForRightEdgePageX(e.pageX);
834         $(e.data.twoPagePopUp).text('View Leaf '+jumpLeaf);
835         
836         $(e.data.twoPagePopUp).css({
837             left: e.pageX +5+ 'px',
838             top: e.pageY-$('#GBcontainer').offset().top+ 'px'
839         });
840     });
841
842     $(this.leafEdgeL).bind('mousemove', this, function(e) {
843     
844         var jumpLeaf = e.data.jumpIndexForLeftEdgePageX(e.pageX);
845         $(e.data.twoPagePopUp).text('View Leaf '+jumpLeaf);
846         
847         $(e.data.twoPagePopUp).css({
848             left: e.pageX - $(e.data.twoPagePopUp).width() - 30 + 'px',
849             top: e.pageY-$('#GBcontainer').offset().top+ 'px'
850         });
851     });
852 }
853
854 // calculateSpreadSize()
855 //______________________________________________________________________________
856 // Calculates 2-page spread dimensions based on this.currentLeafL and
857 // this.currentLeafR
858 // This function sets this.twoPageH, twoPageW, and twoPageRatio
859
860 GnuBook.prototype.calculateSpreadSize = function() {
861     var firstLeaf  = this.currentLeafL;
862     var secondLeaf = this.currentLeafR;
863     //console.log('first page is ' + firstLeaf);
864
865     var canon5Dratio = 1.5;
866     
867     var firstLeafRatio  = this.getPageHeight(firstLeaf) / this.getPageWidth(firstLeaf);
868     var secondLeafRatio = this.getPageHeight(secondLeaf) / this.getPageWidth(secondLeaf);
869     //console.log('firstLeafRatio = ' + firstLeafRatio + ' secondLeafRatio = ' + secondLeafRatio);
870
871     var ratio;
872     if (Math.abs(firstLeafRatio - canon5Dratio) < Math.abs(secondLeafRatio - canon5Dratio)) {
873         ratio = firstLeafRatio;
874         //console.log('using firstLeafRatio ' + ratio);
875     } else {
876         ratio = secondLeafRatio;
877         //console.log('using secondLeafRatio ' + ratio);
878     }
879
880     var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
881     var maxLeafEdgeWidth   = parseInt($('#GBcontainer').width() * 0.1);
882     totalLeafEdgeWidth     = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
883     
884     $('#GBcontainer').css('overflow', 'hidden');
885
886     var idealWidth  = ($('#GBcontainer').width() - 30 - totalLeafEdgeWidth)>>1;
887     var idealHeight = $('#GBcontainer').height() - 30;
888     //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
889
890     if (idealHeight/ratio <= idealWidth) {
891         //use height
892         idealWidth = parseInt(idealHeight/ratio);
893     } else {
894         //use width
895         idealHeight = parseInt(idealWidth*ratio);
896     }
897
898     this.twoPageH     = idealHeight;
899     this.twoPageW     = idealWidth;
900     this.twoPageRatio = ratio;
901     this.twoPageEdgeW = totalLeafEdgeWidth; // The combined width of both edges
902
903 }
904
905 // right()
906 //______________________________________________________________________________
907 // Flip the right page over onto the left
908 GnuBook.prototype.right = function() {
909     if ('rl' != this.pageProgression) {
910         // LTR
911         gb.next();
912     } else {
913         // RTL
914         gb.prev();
915     }
916 }
917
918 // left()
919 //______________________________________________________________________________
920 // Flip the left page over onto the right.
921 GnuBook.prototype.left = function() {
922     if ('rl' != this.pageProgression) {
923         // LTR
924         gb.prev();
925     } else {
926         // RTL
927         gb.next();
928     }
929 }
930
931 // next()
932 //______________________________________________________________________________
933 GnuBook.prototype.next = function() {
934     if (2 == this.mode) {
935         this.autoStop();
936         this.flipFwdToIndex(null);
937     } else {
938         if (this.firstIndex < this.lastDisplayableIndex()) {
939             this.jumpToIndex(this.firstIndex+1);
940         }
941     }
942 }
943
944 // prev()
945 //______________________________________________________________________________
946 GnuBook.prototype.prev = function() {
947     if (2 == this.mode) {
948         this.autoStop();
949         this.flipBackToIndex(null);
950     } else {
951         if (this.firstIndex >= 1) {
952             this.jumpToIndex(this.firstIndex-1);
953         }    
954     }
955 }
956
957 GnuBook.prototype.home = function() {
958     if (2 == this.mode) {
959         this.jumpToIndex(2);
960     }
961     else {
962         this.jumpToIndex(0);
963     }
964 }
965
966 GnuBook.prototype.end = function() {
967     if (2 == this.mode) {
968         this.jumpToIndex(this.lastDisplayableIndex());
969     }
970     else {
971         this.jumpToIndex(this.lastDisplayableIndex());
972     }
973 }
974
975 // flipBackToIndex()
976 //______________________________________________________________________________
977 // to flip back one spread, pass index=null
978 GnuBook.prototype.flipBackToIndex = function(index) {
979     if (1 == this.mode) return;
980
981     var leftIndex = this.currentLeafL;
982     
983     // $$$ Need to change this to be able to see first spread.
984     //     See https://bugs.launchpad.net/gnubook/+bug/296788
985     if (leftIndex <= 2) return;
986     if (this.animating) return;
987
988     if (null != this.leafEdgeTmp) {
989         alert('error: leafEdgeTmp should be null!');
990         return;
991     }
992     
993     if (null == index) {
994         index = leftIndex-2;
995     }
996     //if (index<0) return;
997     
998     var previousIndices = this.getSpreadIndices(index);
999     
1000     if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1001         return;
1002     }
1003     
1004     //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1005
1006     this.animating = true;
1007     
1008     if ('rl' != this.pageProgression) {
1009         // Assume LTR and we are going backward    
1010         var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);        
1011         this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1012         
1013     } else {
1014         // RTL and going backward
1015         var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1016         this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1017     }
1018 }
1019
1020 // flipLeftToRight()
1021 //______________________________________________________________________________
1022 // Flips the page on the left towards the page on the right
1023 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1024
1025     var leftLeaf = this.currentLeafL;
1026     
1027     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentLeafL);
1028     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);    
1029     var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1030     
1031     var currWidthL   = this.getPageWidth2UP(leftLeaf);
1032     var newWidthL    = this.getPageWidth2UP(newIndexL);
1033     var newWidthR    = this.getPageWidth2UP(newIndexR);
1034
1035     var top  = ($('#GBcontainer').height() - this.twoPageH) >> 1;                
1036
1037     //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1038     //console.log('  gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1039     
1040     //animation strategy:
1041     // 0. remove search highlight, if any.
1042     // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge 
1043     //    of the left leaf and where the user clicked in the leaf edge.
1044     //    Note that if this function was triggered by left() and not a
1045     //    mouse click, the width of leafEdgeTmp is very small (zero px).
1046     // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1047     //    leftLeaf to width=0.
1048     // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1049     //    (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1050     //    its new full width.
1051     // 4. After step 3 is finished, do the following:
1052     //      - remove leafEdgeTmp from the dom.
1053     //      - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1054     //          and width=twoPageEdgeW-newLeafEdgeWidthL.
1055     //      - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1056     //          and width=newLeafEdgeWidthL.
1057     //      - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1058     //          and width=newWidthL+newWidthR+twoPageEdgeW+20
1059     //      - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1060     //      - remove old left and right leafs from the dom [pruneUnusedImgs()].
1061     //      - prefetch new adjacent leafs.
1062     //      - set up click handlers for both new left and right leafs.
1063     //      - redraw the search highlight.
1064     //      - update the pagenum box and the url.
1065     
1066     
1067     var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1068
1069     this.leafEdgeTmp = document.createElement('div');
1070     $(this.leafEdgeTmp).css({
1071         borderStyle: 'solid none solid solid',
1072         borderColor: 'rgb(51, 51, 34)',
1073         borderWidth: '1px 0px 1px 1px',
1074         background: 'transparent url(images/left_edges.png) repeat scroll 0% 0%',
1075         width: leafEdgeTmpW + 'px',
1076         height: this.twoPageH-1 + 'px',
1077         left: leftEdgeTmpLeft + 'px',
1078         top: top+'px',    
1079         position: 'absolute',
1080         zIndex:1000
1081     }).appendTo('#GBcontainer');
1082     
1083     //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1084     $(this.leafEdgeL).css({
1085         width: newLeafEdgeWidthL+'px', 
1086         left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1087     });   
1088
1089     // Left gets the offset of the current left leaf from the document
1090     var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1091     // $$$ This seems very similar to the gutter.  May be able to consolidate the logic.
1092     var right = $('#GBcontainer').width()-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBcontainer').offset().left-2+'px';
1093     // We change the left leaf to right positioning
1094     $(this.prefetchedImgs[leftLeaf]).css({
1095         right: right,
1096         left: ''
1097     });
1098
1099      left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1100      
1101      right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1102
1103     $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');    
1104     //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1105     
1106     var self = this;
1107
1108     this.removeSearchHilites();
1109
1110     //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1111     $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1112     
1113         //console.log('     and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1114         $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1115
1116         //console.log('  animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1117         $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1118             $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1119
1120             $(self.leafEdgeR).css({
1121                 // Moves the right leaf edge
1122                 width: self.twoPageEdgeW-newLeafEdgeWidthL+'px',
1123                 left:  gutter+newWidthR+'px'
1124             });
1125
1126             $(self.leafEdgeL).css({
1127                 // Moves and resizes the left leaf edge
1128                 width: newLeafEdgeWidthL+'px',
1129                 left:  gutter-newWidthL-newLeafEdgeWidthL+'px'
1130             });
1131
1132             
1133             $(self.twoPageDiv).css({
1134                 // Resizes the brown border div
1135                 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1136                 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1137             });
1138             
1139             $(self.leafEdgeTmp).remove();
1140             self.leafEdgeTmp = null;
1141             
1142             self.currentLeafL = newIndexL;
1143             self.currentLeafR = newIndexR;
1144             self.displayedLeafs = [newIndexL, newIndexR];
1145             self.setClickHandlers();
1146             self.pruneUnusedImgs();
1147             self.prefetch();
1148             self.animating = false;
1149             
1150             self.updateSearchHilites2UP();
1151             self.updatePageNumBox2UP();
1152             //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));            
1153         });
1154     });        
1155     
1156 }
1157
1158 // flipFwdToIndex()
1159 //______________________________________________________________________________
1160 // Whether we flip left or right is dependent on the page progression
1161 // to flip forward one spread, pass index=null
1162 GnuBook.prototype.flipFwdToIndex = function(index) {
1163
1164     if (this.animating) return;
1165
1166     if (null != this.leafEdgeTmp) {
1167         alert('error: leafEdgeTmp should be null!');
1168         return;
1169     }
1170
1171     if (null == index) {
1172         index = this.currentLeafR+2; // $$$ assumes indices are continuous
1173     }
1174     if (index > this.lastDisplayableIndex()) return;
1175
1176     this.animating = true;
1177     
1178     var nextIndices = this.getSpreadIndices(index);
1179     
1180     //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1181
1182     if ('rl' != this.pageProgression) {
1183         // We did not specify RTL
1184         var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1185         this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1186     } else {
1187         // RTL
1188         var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1189         this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1190     }
1191 }
1192
1193 // flipRightToLeft(nextL, nextR, gutter)
1194 // $$$ better not to have to pass gutter in
1195 //______________________________________________________________________________
1196 // Flip from left to right and show the nextL and nextR indices on those sides
1197 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1198     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentLeafL);
1199     var oldLeafEdgeWidthR = this.twoPageEdgeW-oldLeafEdgeWidthL;
1200     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);  
1201     var newLeafEdgeWidthR = this.twoPageEdgeW-newLeafEdgeWidthL;
1202
1203     var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1204
1205     var top  = ($('#GBcontainer').height() - this.twoPageH) >> 1;                
1206
1207     var scaledW = this.getPageWidth2UP(this.currentLeafR);
1208
1209     var middle     = ($('#GBcontainer').width() >> 1);
1210     var currGutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
1211
1212     this.leafEdgeTmp = document.createElement('div');
1213     $(this.leafEdgeTmp).css({
1214         borderStyle: 'solid none solid solid',
1215         borderColor: 'rgb(51, 51, 34)',
1216         borderWidth: '1px 0px 1px 1px',
1217         background: 'transparent url(images/left_edges.png) repeat scroll 0% 0%',
1218         width: leafEdgeTmpW + 'px',
1219         height: this.twoPageH-1 + 'px',
1220         left: currGutter+scaledW+'px',
1221         top: top+'px',    
1222         position: 'absolute',
1223         zIndex:1000
1224     }).appendTo('#GBcontainer');
1225
1226     //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1227     //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1228     
1229     var currWidthL = this.getPageWidth2UP(this.currentLeafL);
1230     var currWidthR = this.getPageWidth2UP(this.currentLeafR);
1231     var newWidthL = this.getPageWidth2UP(newIndexL);
1232     var newWidthR = this.getPageWidth2UP(newIndexR);
1233
1234     $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1235
1236     var self = this; // closure-tastic!
1237
1238     var speed = this.flipSpeed;
1239
1240     this.removeSearchHilites();
1241     
1242     $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');    
1243     $(this.prefetchedImgs[this.currentLeafR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1244         $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');    
1245         $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1246             $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1247
1248             $(self.leafEdgeL).css({
1249                 width: newLeafEdgeWidthL+'px', 
1250                 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1251             });
1252             
1253             $(self.twoPageDiv).css({
1254                 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1255                 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1256             });
1257             
1258             $(self.leafEdgeTmp).remove();
1259             self.leafEdgeTmp = null;
1260             
1261             self.currentLeafL = newIndexL;
1262             self.currentLeafR = newIndexR;
1263             self.displayedLeafs = [newIndexL, newIndexR];
1264             self.setClickHandlers();            
1265             self.pruneUnusedImgs();
1266             self.prefetch();
1267             self.animating = false;
1268
1269             self.updateSearchHilites2UP();
1270             self.updatePageNumBox2UP();
1271             //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1272         });
1273     });    
1274 }
1275
1276 // setClickHandlers
1277 //______________________________________________________________________________
1278 GnuBook.prototype.setClickHandlers = function() {
1279     var self = this;
1280     $(this.prefetchedImgs[this.currentLeafL]).click(function() {
1281         //self.prevPage();
1282         self.autoStop();
1283         self.left();
1284     });
1285     $(this.prefetchedImgs[this.currentLeafR]).click(function() {
1286         //self.nextPage();'
1287         self.autoStop();
1288         self.right();        
1289     });
1290 }
1291
1292 // prefetchImg()
1293 //______________________________________________________________________________
1294 GnuBook.prototype.prefetchImg = function(leafNum) {
1295     if (undefined == this.prefetchedImgs[leafNum]) {    
1296         //console.log('prefetching ' + leafNum);
1297         var img = document.createElement("img");
1298         img.src = this.getPageURI(leafNum);
1299         this.prefetchedImgs[leafNum] = img;
1300     }
1301 }
1302
1303
1304 // prepareFlipLeftToRight()
1305 //
1306 //______________________________________________________________________________
1307 //
1308 // Prepare to flip the left page towards the right.  This corresponds to moving
1309 // backward when the page progression is left to right.
1310 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1311
1312     //console.log('  preparing left->right for ' + prevL + ',' + prevR);
1313
1314     this.prefetchImg(prevL);
1315     this.prefetchImg(prevR);
1316     
1317     var height  = this.getPageHeight(prevL); 
1318     var width   = this.getPageWidth(prevL);    
1319     var middle = ($('#GBcontainer').width() >> 1);
1320     var top  = ($('#GBcontainer').height() - this.twoPageH) >> 1;                
1321     var scaledW = this.twoPageH*width/height;
1322
1323     // The gutter is the dividing line between the left and right pages.
1324     // It is offset from the middle to create the illusion of thickness to the pages
1325     var gutter = middle + this.gutterOffsetForIndex(prevL);
1326     
1327     //console.log('    gutter for ' + prevL + ' is ' + gutter);
1328     //console.log('    prevL.left: ' + (gutter - scaledW) + 'px');
1329     //console.log('    changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1330     
1331     $(this.prefetchedImgs[prevL]).css({
1332         position: 'absolute',
1333         /*right:   middle+'px',*/
1334         left: gutter-scaledW+'px',
1335         right: '',
1336         top:    top+'px',
1337         backgroundColor: 'rgb(234, 226, 205)',
1338         height: this.twoPageH,
1339         width:  scaledW+'px',
1340         borderRight: '1px solid black',
1341         zIndex: 1
1342     });
1343
1344     $('#GBcontainer').append(this.prefetchedImgs[prevL]);
1345
1346     //console.log('    changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1347
1348     $(this.prefetchedImgs[prevR]).css({
1349         position: 'absolute',
1350         left:   gutter+'px',
1351         right: '',
1352         top:    top+'px',
1353         backgroundColor: 'rgb(234, 226, 205)',
1354         height: this.twoPageH,
1355         width:  '0px',
1356         borderLeft: '1px solid black',
1357         zIndex: 2
1358     });
1359
1360     $('#GBcontainer').append(this.prefetchedImgs[prevR]);
1361
1362
1363     return gutter;
1364             
1365 }
1366
1367 // prepareFlipRightToLeft()
1368 //______________________________________________________________________________
1369 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1370
1371     //console.log('  preparing left<-right for ' + nextL + ',' + nextR);
1372
1373     this.prefetchImg(nextL);
1374     this.prefetchImg(nextR);
1375
1376     var height  = this.getPageHeight(nextR); 
1377     var width   = this.getPageWidth(nextR);    
1378     var middle = ($('#GBcontainer').width() >> 1);
1379     var top  = ($('#GBcontainer').height() - this.twoPageH) >> 1;                
1380     var scaledW = this.twoPageH*width/height;
1381
1382     var gutter = middle + this.gutterOffsetForIndex(nextL);
1383     
1384     //console.log('right to left to %d gutter is %d', nextL, gutter);
1385     
1386     //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1387     $(this.prefetchedImgs[nextR]).css({
1388         position: 'absolute',
1389         left:   gutter+'px',
1390         top:    top+'px',
1391         backgroundColor: 'rgb(234, 226, 205)',
1392         height: this.twoPageH,
1393         width:  scaledW+'px',
1394         borderLeft: '1px solid black',
1395         zIndex: 1
1396     });
1397
1398     $('#GBcontainer').append(this.prefetchedImgs[nextR]);
1399
1400     height  = this.getPageHeight(nextL); 
1401     width   = this.getPageWidth(nextL);      
1402     scaledW = this.twoPageH*width/height;
1403
1404     //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1405     $(this.prefetchedImgs[nextL]).css({
1406         position: 'absolute',
1407         right:   $('#GBcontainer').width()-gutter+'px',
1408         top:    top+'px',
1409         backgroundColor: 'rgb(234, 226, 205)',
1410         height: this.twoPageH,
1411         width:  0+'px',
1412         borderRight: '1px solid black',
1413         zIndex: 2
1414     });
1415
1416     $('#GBcontainer').append(this.prefetchedImgs[nextL]);    
1417
1418     return gutter;
1419             
1420 }
1421
1422 // getNextLeafs() -- NOT RTL AWARE
1423 //______________________________________________________________________________
1424 // GnuBook.prototype.getNextLeafs = function(o) {
1425 //     //TODO: we might have two left or two right leafs in a row (damaged book)
1426 //     //For now, assume that leafs are contiguous.
1427 //     
1428 //     //return [this.currentLeafL+2, this.currentLeafL+3];
1429 //     o.L = this.currentLeafL+2;
1430 //     o.R = this.currentLeafL+3;
1431 // }
1432
1433 // getprevLeafs() -- NOT RTL AWARE
1434 //______________________________________________________________________________
1435 // GnuBook.prototype.getPrevLeafs = function(o) {
1436 //     //TODO: we might have two left or two right leafs in a row (damaged book)
1437 //     //For now, assume that leafs are contiguous.
1438 //     
1439 //     //return [this.currentLeafL-2, this.currentLeafL-1];
1440 //     o.L = this.currentLeafL-2;
1441 //     o.R = this.currentLeafL-1;
1442 // }
1443
1444 // pruneUnusedImgs()
1445 //______________________________________________________________________________
1446 GnuBook.prototype.pruneUnusedImgs = function() {
1447     //console.log('current: ' + this.currentLeafL + ' ' + this.currentLeafR);
1448     for (var key in this.prefetchedImgs) {
1449         //console.log('key is ' + key);
1450         if ((key != this.currentLeafL) && (key != this.currentLeafR)) {
1451             //console.log('removing key '+ key);
1452             $(this.prefetchedImgs[key]).remove();
1453         }
1454         if ((key < this.currentLeafL-4) || (key > this.currentLeafR+4)) {
1455             //console.log('deleting key '+ key);
1456             delete this.prefetchedImgs[key];
1457         }
1458     }
1459 }
1460
1461 // prefetch()
1462 //______________________________________________________________________________
1463 GnuBook.prototype.prefetch = function() {
1464
1465     var lim = this.currentLeafL-4;
1466     var i;
1467     lim = Math.max(lim, 0);
1468     for (i = lim; i < this.currentLeafL; i++) {
1469         this.prefetchImg(i);
1470     }
1471     
1472     if (this.numLeafs > (this.currentLeafR+1)) {
1473         lim = Math.min(this.currentLeafR+4, this.numLeafs-1);
1474         for (i=this.currentLeafR+1; i<=lim; i++) {
1475             this.prefetchImg(i);
1476         }
1477     }
1478 }
1479
1480 // getPageWidth2UP()
1481 //______________________________________________________________________________
1482 GnuBook.prototype.getPageWidth2UP = function(index) {
1483     var height  = this.getPageHeight(index); 
1484     var width   = this.getPageWidth(index);    
1485     return Math.floor(this.twoPageH*width/height);
1486 }    
1487
1488 // search()
1489 //______________________________________________________________________________
1490 GnuBook.prototype.search = function(term) {
1491     $('#GnuBookSearchScript').remove();
1492         var script  = document.createElement("script");
1493         script.setAttribute('id', 'GnuBookSearchScript');
1494         script.setAttribute("type", "text/javascript");
1495         script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath+'/'+this.bookId+'_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1496         document.getElementsByTagName('head')[0].appendChild(script);
1497 }
1498
1499 // GBSearchCallback()
1500 //______________________________________________________________________________
1501 GnuBook.prototype.GBSearchCallback = function(txt) {
1502     //alert(txt);
1503     if (jQuery.browser.msie) {
1504         var dom=new ActiveXObject("Microsoft.XMLDOM");
1505         dom.async="false";
1506         dom.loadXML(txt);    
1507     } else {
1508         var parser = new DOMParser();
1509         var dom = parser.parseFromString(txt, "text/xml");    
1510     }
1511     
1512     $('#GnuBookSearchResults').empty();    
1513     $('#GnuBookSearchResults').append('<ul>');
1514     
1515     for (var key in this.searchResults) {
1516         if (null != this.searchResults[key].div) {
1517             $(this.searchResults[key].div).remove();
1518         }
1519         delete this.searchResults[key];
1520     }
1521     
1522     var pages = dom.getElementsByTagName('PAGE');
1523     
1524     if (0 == pages.length) {
1525         // $$$ it would be nice to echo the (sanitized) search result here
1526         $('#GnuBookSearchResults').append('<li>No search results found</li>');
1527     } else {    
1528         for (var i = 0; i < pages.length; i++){
1529             //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1530     
1531             
1532             var re = new RegExp (/_(\d{4})/);
1533             var reMatch = re.exec(pages[i].getAttribute('file'));
1534             var leafNum = parseInt(reMatch[1], 10);
1535             //var leafNum = parseInt(pages[i].getAttribute('file').substr(1), 10);
1536             
1537             var children = pages[i].childNodes;
1538             var context = '';
1539             for (var j=0; j<children.length; j++) {
1540                 //console.log(j + ' - ' + children[j].nodeName);
1541                 //console.log(children[j].firstChild.nodeValue);
1542                 if ('CONTEXT' == children[j].nodeName) {
1543                     context += children[j].firstChild.nodeValue;
1544                 } else if ('WORD' == children[j].nodeName) {
1545                     context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1546                     
1547                     var index = this.leafNumToIndex(leafNum);
1548                     if (null != index) {
1549                         //coordinates are [left, bottom, right, top, [baseline]]
1550                         //we'll skip baseline for now...
1551                         var coords = children[j].getAttribute('coords').split(',',4);
1552                         if (4 == coords.length) {
1553                             this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1554                         }
1555                     }
1556                 }
1557             }
1558             //TODO: remove hardcoded instance name
1559             $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">Leaf ' + leafNum + '</a></b> - ' + context+'</li>');
1560         }
1561     }
1562     $('#GnuBookSearchResults').append('</ul>');
1563
1564     this.updateSearchHilites();
1565 }
1566
1567 // updateSearchHilites()
1568 //______________________________________________________________________________
1569 GnuBook.prototype.updateSearchHilites = function() {
1570     if (2 == this.mode) {
1571         this.updateSearchHilites2UP();
1572     } else {
1573         this.updateSearchHilites1UP();
1574     }
1575 }
1576
1577 // showSearchHilites1UP()
1578 //______________________________________________________________________________
1579 GnuBook.prototype.updateSearchHilites1UP = function() {
1580
1581     for (var key in this.searchResults) {
1582         
1583         if (-1 != jQuery.inArray(parseInt(key), this.displayedLeafs)) {
1584             var result = this.searchResults[key];
1585             if(null == result.div) {
1586                 result.div = document.createElement('div');
1587                 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1588                 //console.log('appending ' + key);
1589             }    
1590             $(result.div).css({
1591                 width:  (result.r-result.l)/this.reduce + 'px',
1592                 height: (result.b-result.t)/this.reduce + 'px',
1593                 left:   (result.l)/this.reduce + 'px',
1594                 top:    (result.t)/this.reduce +'px'
1595             });
1596
1597         } else {
1598             //console.log(key + ' not displayed');
1599             this.searchResults[key].div=null;
1600         }
1601     }
1602 }
1603
1604 // showSearchHilites2UP()
1605 //______________________________________________________________________________
1606 GnuBook.prototype.updateSearchHilites2UP = function() {
1607
1608     var middle = ($('#GBcontainer').width() >> 1);
1609
1610     for (var key in this.searchResults) {
1611         key = parseInt(key, 10);
1612         if (-1 != jQuery.inArray(key, this.displayedLeafs)) {
1613             var result = this.searchResults[key];
1614             if(null == result.div) {
1615                 result.div = document.createElement('div');
1616                 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBcontainer');
1617                 //console.log('appending ' + key);
1618             }
1619
1620             var height = this.getPageHeight(key);
1621             var width  = this.getPageWidth(key)
1622             var reduce = this.twoPageH/height;
1623             var scaledW = parseInt(width*reduce);
1624             
1625             var gutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
1626             
1627             if ('L' == this.getPageSide(key)) {
1628                 var pageL = gutter-scaledW;
1629             } else {
1630                 var pageL = gutter;
1631             }
1632             var pageT  = ($('#GBcontainer').height() - this.twoPageH) >> 1;                
1633                         
1634             $(result.div).css({
1635                 width:  (result.r-result.l)*reduce + 'px',
1636                 height: (result.b-result.t)*reduce + 'px',
1637                 left:   pageL+(result.l)*reduce + 'px',
1638                 top:    pageT+(result.t)*reduce +'px'
1639             });
1640
1641         } else {
1642             //console.log(key + ' not displayed');
1643             if (null != this.searchResults[key].div) {
1644                 //console.log('removing ' + key);
1645                 $(this.searchResults[key].div).remove();
1646             }
1647             this.searchResults[key].div=null;
1648         }
1649     }
1650 }
1651
1652 // removeSearchHilites()
1653 //______________________________________________________________________________
1654 GnuBook.prototype.removeSearchHilites = function() {
1655     for (var key in this.searchResults) {
1656         if (null != this.searchResults[key].div) {
1657             $(this.searchResults[key].div).remove();
1658             this.searchResults[key].div=null;
1659         }        
1660     }
1661 }
1662
1663 // showEmbedCode()
1664 //______________________________________________________________________________
1665 GnuBook.prototype.showEmbedCode = function() {
1666     if (null != this.embedPopup) { // check if already showing
1667         return;
1668     }
1669     this.autoStop();
1670     this.embedPopup = document.createElement("div");
1671     $(this.embedPopup).css({
1672         position: 'absolute',
1673         top:      '20px',
1674         left:     ($('#GBcontainer').width()-400)/2 + 'px',
1675         width:    '400px',
1676         padding:  "20px",
1677         border:   "3px double #999999",
1678         zIndex:   3,
1679         backgroundColor: "#fff"
1680     }).appendTo('#GnuBook');
1681
1682     htmlStr =  '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1683     htmlStr += '<p><b>Note:</b> The bookreader is still in beta testing. URLs may change in the future, breaking embedded books. This feature is just for testing!</b></p>';
1684     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>';
1685     htmlStr += '<p>Embed Code: <input type="text" size="40" value="<iframe src=\'http://www.us.archive.org/GnuBook/GnuBookEmbed.php?id='+this.bookId+'\' width=\'430px\' height=\'430px\'></iframe>"></p>';
1686     htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';    
1687
1688     this.embedPopup.innerHTML = htmlStr;    
1689 }
1690
1691 // autoToggle()
1692 //______________________________________________________________________________
1693 GnuBook.prototype.autoToggle = function() {
1694
1695     var bComingFrom1up = false;
1696     if (2 != this.mode) {
1697         bComingFrom1up = true;
1698         this.switchMode(2);
1699     }
1700
1701     var self = this;
1702     if (null == this.autoTimer) {
1703         this.flipSpeed = 2000;
1704         
1705         // $$$ Draw events currently cause layout problems when they occur during animation.
1706         //     There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1707         //     we workaround for now by not triggering immediate animation in that case.
1708         //     See https://bugs.launchpad.net/gnubook/+bug/328327
1709         if (('rl' == this.pageProgression) && bComingFrom1up) {
1710             // don't flip immediately -- wait until timer fires
1711         } else {
1712             // flip immediately
1713             this.flipFwdToIndex();        
1714         }
1715
1716         $('#GBtoolbar .play').hide();
1717         $('#GBtoolbar .pause').show();
1718         this.autoTimer=setInterval(function(){
1719             if (self.animating) {return;}
1720             
1721             if (Math.max(self.currentLeafL, self.currentLeafR) >= self.lastDisplayableIndex()) {
1722                 self.flipBackToIndex(1); // $$$ really what we want?
1723             } else {            
1724                 self.flipFwdToIndex();
1725             }
1726         },5000);
1727     } else {
1728         this.autoStop();
1729     }
1730 }
1731
1732 // autoStop()
1733 //______________________________________________________________________________
1734 GnuBook.prototype.autoStop = function() {
1735     if (null != this.autoTimer) {
1736         clearInterval(this.autoTimer);
1737         this.flipSpeed = 'fast';
1738         $('#GBtoolbar .pause').hide();
1739         $('#GBtoolbar .play').show();
1740         this.autoTimer = null;
1741     }
1742 }
1743
1744 // keyboardNavigationIsDisabled(event)
1745 //   - returns true if keyboard navigation should be disabled for the event
1746 //______________________________________________________________________________
1747 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
1748     if (event.target.tagName == "INPUT") {
1749         return true;
1750     }   
1751     return false;
1752 }
1753
1754 // gutterOffsetForIndex
1755 //______________________________________________________________________________
1756 //
1757 // Returns the gutter offset for the spread containing the given index.
1758 // This function supports RTL
1759 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
1760
1761     // To find the offset of the gutter from the middle we calculate our percentage distance
1762     // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
1763     var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPageEdgeW);
1764     
1765     // But then again for RTL it's the opposite
1766     if ('rl' == this.pageProgression) {
1767         offset = -offset;
1768     }
1769     
1770     return offset;
1771 }
1772
1773 // leafEdgeWidth
1774 //______________________________________________________________________________
1775 // Returns the width of the leaf edge div for the page with index given
1776 GnuBook.prototype.leafEdgeWidth = function(pindex) {
1777     // $$$ could there be single pixel rounding errors for L vs R?
1778     if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
1779         return parseInt( (pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1780     } else {
1781         return parseInt( (1 - pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1782     }
1783 }
1784
1785 // jumpIndexForLeftEdgePageX
1786 //______________________________________________________________________________
1787 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
1788 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
1789     if ('rl' != this.pageProgression) {
1790         // LTR - flipping backward
1791         var jumpLeaf = this.currentLeafL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1792         // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
1793         jumpLeaf = Math.min(jumpLeaf, this.currentLeafL - 2);
1794         jumpLeaf = Math.max(jumpLeaf, this.firstDisplayableIndex());
1795         return jumpLeaf;
1796     } else {
1797         var jumpLeaf = this.currentLeafL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1798         jumpLeaf = Math.max(jumpLeaf, this.currentLeafL + 2);
1799         jumpLeaf = Math.min(jumpLeaf, this.lastDisplayableIndex());
1800         return jumpLeaf;
1801     }
1802 }
1803
1804 // jumpIndexForRightEdgePageX
1805 //______________________________________________________________________________
1806 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
1807 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
1808     if ('rl' != this.pageProgression) {
1809         // LTR
1810         var jumpLeaf = this.currentLeafR + (pageX - $(this.leafEdgeR).offset().left) * 10;
1811         jumpLeaf = Math.max(jumpLeaf, this.currentLeafR + 2);
1812         jumpLeaf = Math.min(jumpLeaf, this.lastDisplayableIndex());
1813         return jumpLeaf;
1814     } else {
1815         var jumpLeaf = this.currentLeafR - (pageX - $(this.leafEdgeR).offset().left) * 10;
1816         jumpLeaf = Math.min(jumpLeaf, this.currentLeafR - 2);
1817         jumpLeaf = Math.max(jumpLeaf, this.firstDisplayableIndex());
1818         return jumpLeaf;
1819     }
1820 }
1821
1822 GnuBook.prototype.initToolbar = function(mode) {
1823     $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
1824         + "<a class='GBicon logo rollover' href='" + this.logoURL + "'>&nbsp;</a>"
1825         + " <button class='GBicon rollover zoom_out' onclick='gb.zoom1up(-1); return false;'/>" 
1826         + "<button class='GBicon rollover zoom_in' onclick='gb.zoom1up(1); return false;'/>"
1827         + " <span class='label'>Zoom: <span id='GBzoom'>25</span>%</span>"
1828         + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
1829         + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
1830         + "&nbsp;&nbsp;<a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
1831         + "</span></div>");
1832
1833     // $$$ turn this into a member variable
1834     var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
1835     
1836     // We build in mode 2
1837     jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
1838         + "<button class='GBicon rollover embed' />"
1839         + "<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>"
1840         + "<div class='GBtoolbarmode2' style='display: inline'><button class='GBicon rollover book_left' /><button class='GBicon rollover book_right' /></div>"
1841         + "<div class='GBtoolbarmode1' style='display: hidden'><button class='GBicon rollover book_up' /> <button class='GBicon rollover book_down' /></div>"
1842         + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
1843
1844     // Bind the non-changing click handlers
1845     jToolbar.find('.embed').bind('click', function(e) {
1846         gb.showEmbedCode();
1847         return false;
1848     });
1849     jToolbar.find('.play').bind('click', function(e) {
1850         gb.autoToggle();
1851         return false;
1852     });
1853     jToolbar.find('.pause').bind('click', function(e) {
1854         gb.autoToggle();
1855         return false;
1856     });
1857     
1858     // Setup tooltips -- later we could load these from a file for i18n
1859     var titles = { '.logo': 'Go to Archive.org',
1860                    '.zoom_in': 'Zoom in',
1861                    '.zoom_out': 'Zoom out',
1862                    '.one_page_mode': 'One-page view',
1863                    '.two_page_mode': 'Two-page view',
1864                    '.embed': 'Embed bookreader',
1865                    '.book_left': 'Flip left',
1866                    '.book_right': 'Flip right',
1867                    '.book_up': 'Page up',
1868                    '.book_down': 'Page down',
1869                    '.play': 'Play',
1870                    '.pause': 'Pause'
1871                   };                  
1872     for (var icon in titles) {
1873         jToolbar.find(icon).attr('title', titles[icon]);
1874     }
1875
1876     // Switch to requested mode -- binds other click handlers
1877     this.switchToolbarMode(mode);
1878
1879 }
1880
1881
1882 // switchToolbarMode
1883 //______________________________________________________________________________
1884 // Update the toolbar for the given mode (changes navigation buttons)
1885 // $$$ we should soon split the toolbar out into its own module
1886 GnuBook.prototype.switchToolbarMode = function(mode) {
1887     if (1 == mode) {
1888         // 1-up     
1889         $('#GBtoolbar .GBtoolbarmode2').hide();
1890         $('#GBtoolbar .GBtoolbarmode1').css('display', 'inline').show();
1891     } else {
1892         // 2-up
1893         $('#GBtoolbar .GBtoolbarmode1').hide();
1894         $('#GBtoolbar .GBtoolbarmode2').css('display', 'inline').show();
1895     }
1896     
1897     this.bindToolbarNavHandlers($('#GBtoolbar'));
1898 }
1899
1900 // bindToolbarNavHandlers
1901 //______________________________________________________________________________
1902 // Binds the toolbar handlers
1903 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
1904
1905     jToolbar.find('.book_left').unbind('click')
1906         .bind('click', function(e) {
1907             gb.left();
1908             return false;
1909          });
1910          
1911     jToolbar.find('.book_right').unbind('click')
1912         .bind('click', function(e) {
1913             gb.right();
1914             return false;
1915         });
1916         
1917     jToolbar.find('.book_up').unbind('click')
1918         .bind('click', function(e) {
1919             gb.prev();
1920             return false;
1921         });        
1922         
1923     jToolbar.find('.book_down').unbind('click')
1924         .bind('click', function(e) {
1925             gb.next();
1926             return false;
1927         });      
1928 }
1929
1930 // firstDisplayableIndex
1931 //______________________________________________________________________________
1932 // Returns the index of the first visible page, dependent on the mode.
1933 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
1934 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
1935 GnuBook.prototype.firstDisplayableIndex = function() {
1936     if (this.mode == 0) {
1937         return 0;
1938     } else {
1939         return 1; // $$$ we assume there are enough pages... we need logic for very short books
1940     }
1941 }
1942
1943 // lastDisplayableIndex
1944 //______________________________________________________________________________
1945 // Returns the index of the last visible page, dependent on the mode.
1946 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
1947 // this function when we can as pa  rt of https://bugs.launchpad.net/gnubook/+bug/296788
1948 GnuBook.prototype.lastDisplayableIndex = function() {
1949     if (this.mode == 2) {
1950         if (this.lastDisplayableIndex2up === null) {
1951             // Calculate and cache
1952             var candidate = this.numLeafs - 1;
1953             for ( ; candidate >= 0; candidate--) {
1954                 var spreadIndices = this.getSpreadIndices(candidate);
1955                 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
1956                     break;
1957                 }
1958             }
1959             this.lastDisplayableIndex2up = candidate;
1960         }
1961         return this.lastDisplayableIndex2up;
1962     } else {
1963         return this.numLeafs - 1;
1964     }
1965 }
1966
1967 // shortTitle(maximumCharacters)
1968 //________
1969 // Returns a shortened version of the title with the maximum number of characters
1970 GnuBook.prototype.shortTitle = function(maximumCharacters) {
1971     if (this.bookTitle.length < maximumCharacters) {
1972         return this.bookTitle;
1973     }
1974     
1975     var title = this.bookTitle.substr(0, maximumCharacters - 3);
1976     title += '...';
1977     return title;
1978 }