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