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