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