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