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