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