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