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