5a2dc3912fc58b4703445e99e6cc244576722c2f
[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 function GnuBook() {
34     this.reduce  = 4;
35     this.padding = 10;
36     this.mode    = 1; //1 or 2
37     this.ui = 'full'; // UI mode
38     
39     this.displayedIndices = []; 
40     //this.indicesToDisplay = [];
41     this.imgs = {};
42     this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
43     
44     this.timer     = null;
45     this.animating = false;
46     this.auto      = false;
47     this.autoTimer = null;
48     this.flipSpeed = 'fast';
49
50     this.twoPagePopUp = null;
51     this.leafEdgeTmp  = null;
52     this.embedPopup = null;
53     this.printPopup = null;
54     
55     this.searchTerm = '';
56     this.searchResults = {};
57     
58     this.firstIndex = null;
59     
60     this.lastDisplayableIndex2up = null;
61     
62     // We link to index.php to avoid redirect which breaks back button
63     this.logoURL = 'http://www.archive.org/index.php';
64     
65     // Base URL for images
66     this.imagesBaseURL = '/bookreader/images/';
67     
68     // Mode constants
69     this.constMode1up = 1;
70     this.constMode2up = 2;
71     
72     // Zoom levels
73     this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
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             
146             // We only need to prepare again in autofit (size of spread changes)
147             if (e.data.twoPage.autofit) {
148                 e.data.prepareTwoPageView();
149             } else {
150                 // Re-center if the scrollbars have disappeared
151                 var center = e.data.twoPageGetViewCenter();
152                 var doRecenter = false;
153                 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
154                     center.percentageX = 0.5;
155                     doRecenter = true;
156                 }
157                 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
158                     center.percentageY = 0.5;
159                     doRecenter = true;
160                 }
161                 if (doRecenter) {
162                     e.data.twoPageCenterView(center.percentageX, center.percentageY);
163                 }
164             }
165         }
166     });
167     
168     $('.GBpagediv1up').bind('mousedown', this, function(e) {
169         // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
170         //     but this also interferes with right-click.  See https://bugs.edge.launchpad.net/gnubook/+bug/362626
171     });
172
173     if (1 == this.mode) {
174         this.resizePageView();
175         this.firstIndex = startIndex;
176         this.jumpToIndex(startIndex);
177     } else {
178         //this.resizePageView();
179         
180         this.displayedIndices=[0];
181         this.firstIndex = startIndex;
182         this.displayedIndices = [this.firstIndex];
183         //console.log('titleLeaf: %d', this.titleLeaf);
184         //console.log('displayedIndices: %s', this.displayedIndices);
185         this.prepareTwoPageView();
186     }
187         
188     // Enact other parts of initial params
189     this.updateFromParams(params);
190 }
191
192 GnuBook.prototype.setupKeyListeners = function() {
193     var self = this;
194     
195     var KEY_PGUP = 33;
196     var KEY_PGDOWN = 34;
197     var KEY_END = 35;
198     var KEY_HOME = 36;
199
200     var KEY_LEFT = 37;
201     var KEY_UP = 38;
202     var KEY_RIGHT = 39;
203     var KEY_DOWN = 40;
204
205     // We use document here instead of window to avoid a bug in jQuery on IE7
206     $(document).keydown(function(e) {
207         // Keyboard navigation        
208         switch(e.keyCode) {
209             case KEY_PGUP:
210             case KEY_UP:            
211                 // In 1up mode page scrolling is handled by browser
212                 if (2 == self.mode) {
213                     e.preventDefault();
214                     self.prev();
215                 }
216                 break;
217             case KEY_DOWN:
218             case KEY_PGDOWN:
219                 if (2 == self.mode) {
220                     e.preventDefault();
221                     self.next();
222                 }
223                 break;
224             case KEY_END:
225                 e.preventDefault();
226                 self.last();
227                 break;
228             case KEY_HOME:
229                 e.preventDefault();
230                 self.first();
231                 break;
232             case KEY_LEFT:
233                 if (self.keyboardNavigationIsDisabled(e)) {
234                     e.preventDefault();
235                     break;
236                 }
237                 if (2 == self.mode) {
238                     e.preventDefault();
239                     self.left();
240                 }
241                 break;
242             case KEY_RIGHT:
243                 if (self.keyboardNavigationIsDisabled(e)) {
244                     e.preventDefault();
245                     break;
246                 }
247                 if (2 == self.mode) {
248                     e.preventDefault();
249                     self.right();
250                 }
251                 break;
252         }
253     });
254 }
255
256 // drawLeafs()
257 //______________________________________________________________________________
258 GnuBook.prototype.drawLeafs = function() {
259     if (1 == this.mode) {
260         this.drawLeafsOnePage();
261     } else {
262         this.drawLeafsTwoPage();
263     }
264 }
265
266 // setDragHandler()
267 //______________________________________________________________________________
268 GnuBook.prototype.setDragHandler = function(div) {
269     div.dragging = false;
270
271     $(div).unbind('mousedown').bind('mousedown', function(e) {
272         e.preventDefault();
273         
274         //console.log('mousedown at ' + e.pageY);
275
276         this.dragging = true;
277         this.prevMouseX = e.pageX;
278         this.prevMouseY = e.pageY;
279     
280         var startX    = e.pageX;
281         var startY    = e.pageY;
282         var startTop  = $('#GBcontainer').attr('scrollTop');
283         var startLeft =  $('#GBcontainer').attr('scrollLeft');
284
285     });
286         
287     $(div).unbind('mousemove').bind('mousemove', function(ee) {
288         ee.preventDefault();
289
290         // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
291         
292         var offsetX = ee.pageX - this.prevMouseX;
293         var offsetY = ee.pageY - this.prevMouseY;
294         
295         if (this.dragging) {
296             $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
297             $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
298         }
299         
300         this.prevMouseX = ee.pageX;
301         this.prevMouseY = ee.pageY;
302         
303     });
304     
305     $(div).unbind('mouseup').bind('mouseup', function(ee) {
306         ee.preventDefault();
307         //console.log('mouseup');
308
309         this.dragging = false;
310     });
311     
312     $(div).unbind('mouseleave').bind('mouseleave', function(e) {
313         e.preventDefault();
314         //console.log('mouseleave');
315
316         this.dragging = false;        
317     });
318     
319     $(div).unbind('mouseenter').bind('mouseenter', function(e) {
320         e.preventDefault();
321         //console.log('mouseenter');
322         
323         this.dragging = false;
324     });
325 }
326
327 // setDragHandler2UP()
328 //______________________________________________________________________________
329 GnuBook.prototype.setDragHandler2UP = function(div) {
330     div.dragging = false;
331     
332     $(div).unbind('mousedown').bind('mousedown', function(e) {
333         e.preventDefault();
334         
335         //console.log('mousedown at ' + e.pageY);
336
337         this.dragStart = {x: e.pageX, y: e.pageY };
338         this.mouseDown = true;
339         this.dragging = false; // wait until drag distance
340         this.prevMouseX = e.pageX;
341         this.prevMouseY = e.pageY;
342     
343         var startX    = e.pageX;
344         var startY    = e.pageY;
345         var startTop  = $('#GBcontainer').attr('scrollTop');
346         var startLeft =  $('#GBcontainer').attr('scrollLeft');
347
348     });
349         
350     $(div).unbind('mousemove').bind('mousemove', function(ee) {
351         ee.preventDefault();
352
353         // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
354         
355         var offsetX = ee.pageX - this.prevMouseX;
356         var offsetY = ee.pageY - this.prevMouseY;
357         
358         var minDragDistance = 5; // $$$ constant
359
360         var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
361                 
362         if (this.mouseDown && (distance > minDragDistance)) {
363             //console.log('drag start!');
364             
365             this.dragging = true;
366         }
367         
368         if (this.dragging) {        
369             $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
370             $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
371             this.prevMouseX = ee.pageX;
372             this.prevMouseY = ee.pageY;
373         }
374         
375         
376     });
377     
378     /*
379     $(div).unbind('mouseup').bind('mouseup', function(ee) {
380         ee.preventDefault();
381         //console.log('mouseup');
382
383         this.dragging = false;
384         this.mouseDown = false;
385     });
386     */
387     
388     
389     $(div).unbind('mouseleave').bind('mouseleave', function(e) {
390         e.preventDefault();
391         //console.log('mouseleave');
392
393         this.dragging = false;  
394         this.mouseDown = false;
395     });
396     
397     $(div).unbind('mouseenter').bind('mouseenter', function(e) {
398         e.preventDefault();
399         //console.log('mouseenter');
400         
401         this.dragging = false;
402         this.mouseDown = false;
403     });
404 }
405
406 GnuBook.prototype.setClickHandler2UP = function( element, data, handler) {
407     //console.log('setting handler');
408     //console.log(element.tagName);
409     
410     $(element).unbind('click').bind('click', data, function(e) {
411         e.preventDefault();
412         
413         //console.log('click!');
414         
415         if (this.mouseDown && (!this.dragging)) {
416             //console.log('click not dragging!');
417             handler(e);
418         }
419         
420         this.dragging = false;
421         this.mouseDown = false;
422     });
423 }
424
425 // drawLeafsOnePage()
426 //______________________________________________________________________________
427 GnuBook.prototype.drawLeafsOnePage = function() {
428     //alert('drawing leafs!');
429     this.timer = null;
430
431
432     var scrollTop = $('#GBcontainer').attr('scrollTop');
433     var scrollBottom = scrollTop + $('#GBcontainer').height();
434     //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
435     
436     var indicesToDisplay = [];
437     
438     var i;
439     var leafTop = 0;
440     var leafBottom = 0;
441     for (i=0; i<this.numLeafs; i++) {
442         var height  = parseInt(this.getPageHeight(i)/this.reduce); 
443     
444         leafBottom += height;
445         //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
446         var topInView    = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
447         var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
448         var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
449         if (topInView | bottomInView | middleInView) {
450             //console.log('displayed: ' + this.displayedIndices);
451             //console.log('to display: ' + i);
452             indicesToDisplay.push(i);
453         }
454         leafTop += height +10;      
455         leafBottom += 10;
456     }
457
458     var firstIndexToDraw  = indicesToDisplay[0];
459     this.firstIndex      = firstIndexToDraw;
460     
461     // Update hash, but only if we're currently displaying a leaf
462     // Hack that fixes #365790
463     if (this.displayedIndices.length > 0) {
464         this.updateLocationHash();
465     }
466
467     if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
468         firstIndexToDraw--;
469         indicesToDisplay.unshift(firstIndexToDraw);
470     }
471     
472     var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
473     if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
474         indicesToDisplay.push(lastIndexToDraw+1);
475     }
476     
477     leafTop = 0;
478     var i;
479     for (i=0; i<firstIndexToDraw; i++) {
480         leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
481     }
482
483     //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
484     var viewWidth = $('#GBcontainer').attr('scrollWidth');
485
486
487     for (i=0; i<indicesToDisplay.length; i++) {
488         var index = indicesToDisplay[i];    
489         var height  = parseInt(this.getPageHeight(index)/this.reduce); 
490
491         if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {            
492             var width   = parseInt(this.getPageWidth(index)/this.reduce); 
493             //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
494             var div = document.createElement("div");
495             div.className = 'GBpagediv1up';
496             div.id = 'pagediv'+index;
497             div.style.position = "absolute";
498             $(div).css('top', leafTop + 'px');
499             var left = (viewWidth-width)>>1;
500             if (left<0) left = 0;
501             $(div).css('left', left+'px');
502             $(div).css('width', width+'px');
503             $(div).css('height', height+'px');
504             //$(div).text('loading...');
505             
506             this.setDragHandler(div);
507             
508             $('#GBpageview').append(div);
509
510             var img = document.createElement("img");
511             img.src = this.getPageURI(index, this.reduce, 0);
512             $(img).css('width', width+'px');
513             $(img).css('height', height+'px');
514             $(div).append(img);
515
516         } else {
517             //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));            
518         }
519
520         leafTop += height +10;
521
522     }
523     
524     for (i=0; i<this.displayedIndices.length; i++) {
525         if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
526             var index = this.displayedIndices[i];
527             //console.log('Removing leaf ' + index);
528             //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
529             $('#pagediv'+index).remove();
530         } else {
531             //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
532         }
533     }
534     
535     this.displayedIndices = indicesToDisplay.slice();
536     this.updateSearchHilites();
537     
538     if (null != this.getPageNum(firstIndexToDraw))  {
539         $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
540     } else {
541         $("#GBpagenum").val('');
542     }
543             
544     this.updateToolbarZoom(this.reduce);
545     
546 }
547
548 // drawLeafsTwoPage()
549 //______________________________________________________________________________
550 GnuBook.prototype.drawLeafsTwoPage = function() {
551     var scrollTop = $('#GBtwopageview').attr('scrollTop');
552     var scrollBottom = scrollTop + $('#GBtwopageview').height();
553     
554     // $$$ we should use calculated values in this.twoPage (recalc if necessary)
555     
556     var indexL = this.twoPage.currentIndexL;
557     var heightL  = this.getPageHeight(indexL); 
558     var widthL   = this.getPageWidth(indexL);
559
560     var leafEdgeWidthL = this.leafEdgeWidth(indexL);
561     var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
562     //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
563     var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
564     //console.log(leafEdgeWidthL);
565
566     var middle = this.twoPage.middle; // $$$ getter instead?
567     var top = this.twoPageTop();
568     var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
569
570     this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
571     this.twoPage.gutter = this.twoPageGutter();
572     
573     this.prefetchImg(indexL);
574     $(this.prefetchedImgs[indexL]).css({
575         position: 'absolute',
576         left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
577         right: '',
578         top:    top+'px',
579         backgroundColor: 'rgb(234, 226, 205)',
580         height: this.twoPage.height +'px', // $$$ height forced the same for both pages
581         width:  this.twoPage.scaledWL + 'px',
582         borderRight: '1px solid black',
583         zIndex: 2
584     }).appendTo('#GBtwopageview');
585     
586     var indexR = this.twoPage.currentIndexR;
587     var heightR  = this.getPageHeight(indexR); 
588     var widthR   = this.getPageWidth(indexR);
589
590     // $$$ should use getwidth2up?
591     //var scaledWR = this.twoPage.height*widthR/heightR;
592     this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
593     this.prefetchImg(indexR);
594     $(this.prefetchedImgs[indexR]).css({
595         position: 'absolute',
596         left:   this.twoPage.gutter+'px',
597         right: '',
598         top:    top+'px',
599         backgroundColor: 'rgb(234, 226, 205)',
600         height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
601         width:  this.twoPage.scaledWR + 'px',
602         borderLeft: '1px solid black',
603         zIndex: 2
604     }).appendTo('#GBtwopageview');
605         
606
607     this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
608     this.setMouseHandlers2UP();
609     this.twoPageSetCursor();
610
611     this.updatePageNumBox2UP();
612     this.updateToolbarZoom(this.reduce);
613     
614     // this.twoPagePlaceFlipAreas();  // No longer used
615
616 }
617
618 // updatePageNumBox2UP
619 //______________________________________________________________________________
620 GnuBook.prototype.updatePageNumBox2UP = function() {
621     if (null != this.getPageNum(this.twoPage.currentIndexL))  {
622         $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
623     } else {
624         $("#GBpagenum").val('');
625     }
626     this.updateLocationHash();
627 }
628
629 // loadLeafs()
630 //______________________________________________________________________________
631 GnuBook.prototype.loadLeafs = function() {
632
633
634     var self = this;
635     if (null == this.timer) {
636         this.timer=setTimeout(function(){self.drawLeafs()},250);
637     } else {
638         clearTimeout(this.timer);
639         this.timer=setTimeout(function(){self.drawLeafs()},250);    
640     }
641 }
642
643 // zoom(direction)
644 //
645 // Pass 1 to zoom in, anything else to zoom out
646 //______________________________________________________________________________
647 GnuBook.prototype.zoom = function(direction) {
648     switch (this.mode) {
649         case this.constMode1up:
650             return this.zoom1up(direction);
651         case this.constMode2up:
652             return this.zoom2up(direction);
653     }
654 }
655
656 // zoom1up(dir)
657 //______________________________________________________________________________
658 GnuBook.prototype.zoom1up = function(dir) {
659     if (2 == this.mode) {     //can only zoom in 1-page mode
660         this.switchMode(1);
661         return;
662     }
663     
664     // $$$ with flexible zoom we could "snap" to /2 page reductions
665     //     for better scaling
666     if (1 == dir) {
667         if (this.reduce <= 0.5) return;
668         this.reduce*=0.5;           //zoom in
669     } else {
670         if (this.reduce >= 8) return;
671         this.reduce*=2;             //zoom out
672     }
673     
674     this.resizePageView();
675
676     $('#GBpageview').empty()
677     this.displayedIndices = [];
678     this.loadLeafs();
679     
680     this.updateToolbarZoom(this.reduce);
681 }
682
683 // resizePageView()
684 //______________________________________________________________________________
685 GnuBook.prototype.resizePageView = function() {
686     var i;
687     var viewHeight = 0;
688     //var viewWidth  = $('#GBcontainer').width(); //includes scrollBar
689     var viewWidth  = $('#GBcontainer').attr('clientWidth');   
690
691     var oldScrollTop  = $('#GBcontainer').attr('scrollTop');
692     var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
693     var oldPageViewHeight = $('#GBpageview').height();
694     var oldPageViewWidth = $('#GBpageview').width();
695     
696     var oldCenterY = this.centerY1up();
697     var oldCenterX = this.centerX1up();
698     
699     if (0 != oldPageViewHeight) {
700         var scrollRatio = oldCenterY / oldPageViewHeight;
701     } else {
702         var scrollRatio = 0;
703     }
704     
705     for (i=0; i<this.numLeafs; i++) {
706         viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding; 
707         var width = parseInt(this.getPageWidth(i)/this.reduce);
708         if (width>viewWidth) viewWidth=width;
709     }
710     $('#GBpageview').height(viewHeight);
711     $('#GBpageview').width(viewWidth);    
712
713     var newCenterY = scrollRatio*viewHeight;
714     var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
715     $('#GBcontainer').attr('scrollTop', newTop);
716     
717     // We use clientWidth here to avoid miscalculating due to scroll bar
718     var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
719     var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
720     newLeft = Math.max(newLeft, 0);
721     $('#GBcontainer').attr('scrollLeft', newLeft);
722     //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
723     
724     //this.centerPageView();
725     this.loadLeafs();
726     
727 }
728
729 // centerX1up()
730 //______________________________________________________________________________
731 // Returns the current offset of the viewport center in scaled document coordinates.
732 GnuBook.prototype.centerX1up = function() {
733     var centerX;
734     if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
735         centerX = $('#GBpageview').width();
736     } else {
737         centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
738     }
739     centerX = Math.floor(centerX);
740     return centerX;
741 }
742
743 // centerY1up()
744 //______________________________________________________________________________
745 // Returns the current offset of the viewport center in scaled document coordinates.
746 GnuBook.prototype.centerY1up = function() {
747     var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
748     return Math.floor(centerY);
749 }
750
751 // centerPageView()
752 //______________________________________________________________________________
753 GnuBook.prototype.centerPageView = function() {
754
755     var scrollWidth  = $('#GBcontainer').attr('scrollWidth');
756     var clientWidth  =  $('#GBcontainer').attr('clientWidth');
757     //console.log('sW='+scrollWidth+' cW='+clientWidth);
758     if (scrollWidth > clientWidth) {
759         $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
760     }
761
762 }
763
764 // zoom2up(direction)
765 //______________________________________________________________________________
766 GnuBook.prototype.zoom2up = function(direction) {
767
768     // Hard stop autoplay
769     this.stopFlipAnimations();
770     
771     // Get new zoom state    
772     var newZoom = this.twoPageNextReduce(this.reduce, direction);
773     if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
774         return;
775     }
776     this.twoPage.autofit = newZoom.autofit;
777     this.reduce = newZoom.reduce;
778
779     // Preserve view center position
780     var oldCenter = this.twoPageGetViewCenter();
781     
782     // If zooming in, reload imgs.  DOM elements will be removed by prepareTwoPageView
783     // $$$ An improvement would be to use the low res image until the larger one is loaded.
784     if (1 == direction) {
785         for (var img in this.prefetchedImgs) {
786             delete this.prefetchedImgs[img];
787         }
788     }
789     
790     // Prepare view with new center to minimize visual glitches
791     this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
792 }
793
794
795 // quantizeReduce(reduce)
796 //______________________________________________________________________________
797 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
798 GnuBook.prototype.quantizeReduce = function(reduce) {
799     var quantized = this.reductionFactors[0];
800     var distance = Math.abs(reduce - quantized);
801     for (var i = 1; i < this.reductionFactors.length; i++) {
802         newDistance = Math.abs(reduce - this.reductionFactors[i]);
803         if (newDistance < distance) {
804             distance = newDistance;
805             quantized = this.reductionFactors[i];
806         }
807     }
808     
809     return quantized;
810 }
811
812 // twoPageNextReduce()
813 //______________________________________________________________________________
814 // Returns the next reduction level
815 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
816     var result = {};
817     var autofitReduce = this.twoPageGetAutofitReduce();
818
819     if (0 == direction) { // autofit
820         result.autofit = true;
821         result.reduce = autofitReduce;
822         
823     } else if (1 == direction) { // zoom in
824         var newReduce = this.reductionFactors[0];
825     
826         for (var i = 1; i < this.reductionFactors.length; i++) {
827             if (this.reductionFactors[i] < reduce) {
828                 newReduce = this.reductionFactors[i];
829             }
830         }
831         
832         if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
833             // use autofit
834             result.autofit = true;
835             result.reduce = autofitReduce;
836         } else {        
837             result.autofit = false;
838             result.reduce = newReduce;
839         }
840         
841     } else { // zoom out
842         var lastIndex = this.reductionFactors.length - 1;
843         var newReduce = this.reductionFactors[lastIndex];
844         
845         for (var i = lastIndex; i >= 0; i--) {
846             if (this.reductionFactors[i] > reduce) {
847                 newReduce = this.reductionFactors[i];
848             }
849         }
850          
851         if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
852             // use autofit
853             result.autofit = true;
854             result.reduce = autofitReduce;
855         } else {
856             result.autofit = false;
857             result.reduce = newReduce;
858         }
859     }
860     
861     return result;
862 }
863
864 // jumpToPage()
865 //______________________________________________________________________________
866 // Attempts to jump to page.  Returns true if page could be found, false otherwise.
867 GnuBook.prototype.jumpToPage = function(pageNum) {
868
869     var pageIndex = this.getPageIndex(pageNum);
870
871     if ('undefined' != typeof(pageIndex)) {
872         var leafTop = 0;
873         var h;
874         this.jumpToIndex(pageIndex);
875         $('#GBcontainer').attr('scrollTop', leafTop);
876         return true;
877     }
878     
879     // Page not found
880     return false;
881 }
882
883 // jumpToIndex()
884 //______________________________________________________________________________
885 GnuBook.prototype.jumpToIndex = function(index) {
886
887     if (2 == this.mode) {
888         this.autoStop();
889         
890         // By checking against min/max we do nothing if requested index
891         // is current
892         if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
893             this.flipBackToIndex(index);
894         } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
895             this.flipFwdToIndex(index);
896         }
897
898     } else {        
899         var i;
900         var leafTop = 0;
901         var h;
902         for (i=0; i<index; i++) {
903             h = parseInt(this.getPageHeight(i)/this.reduce); 
904             leafTop += h + this.padding;
905         }
906         //$('#GBcontainer').attr('scrollTop', leafTop);
907         $('#GBcontainer').animate({scrollTop: leafTop },'fast');
908     }
909 }
910
911
912
913 // switchMode()
914 //______________________________________________________________________________
915 GnuBook.prototype.switchMode = function(mode) {
916
917     //console.log('  asked to switch to mode ' + mode + ' from ' + this.mode);
918     
919     if (mode == this.mode) return;
920     
921     if (!this.canSwitchToMode(mode)) {
922         return;
923     }
924
925     this.autoStop();
926     this.removeSearchHilites();
927
928     this.mode = mode;
929     
930     this.switchToolbarMode(mode);
931     
932     // $$$ TODO preserve center of view when switching between mode
933     //     See https://bugs.edge.launchpad.net/gnubook/+bug/416682
934     
935     if (1 == mode) {
936         this.reduce = this.quantizeReduce(this.reduce);
937         this.prepareOnePageView();
938     } else {
939         this.twoPage.autofit = false; // Take zoom level from other mode
940         this.reduce = this.quantizeReduce(this.reduce);
941         this.prepareTwoPageView();
942         this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
943     }
944
945 }
946
947 //prepareOnePageView()
948 //______________________________________________________________________________
949 GnuBook.prototype.prepareOnePageView = function() {
950
951     // var startLeaf = this.displayedIndices[0];
952     var startLeaf = this.currentIndex();
953     
954     $('#GBcontainer').empty();
955     $('#GBcontainer').css({
956         overflowY: 'scroll',
957         overflowX: 'auto'
958     });
959     
960     var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
961     
962     this.resizePageView();
963     
964     this.jumpToIndex(startLeaf);
965     this.displayedIndices = [];
966     
967     this.drawLeafsOnePage();
968         
969     // Bind mouse handlers
970     // Disable mouse click to avoid selected/highlighted page images - bug 354239
971     gbPageView.bind('mousedown', function(e) {
972         // $$$ check here for right-click and don't disable.  Also use jQuery style
973         //     for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
974         return false;
975     })
976     // Special hack for IE7
977     gbPageView[0].onselectstart = function(e) { return false; };
978 }
979
980 // prepareTwoPageView()
981 //______________________________________________________________________________
982 // Some decisions about two page view:
983 //
984 // Both pages will be displayed at the same height, even if they were different physical/scanned
985 // sizes.  This simplifies the animation (from a design as well as technical standpoint).  We
986 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
987 // aspect ratio to determine the height.
988 //
989 // The two page view div is resized to keep the middle of the book in the middle of the div
990 // even as the page sizes change.  To e.g. keep the middle of the book in the middle of the GBcontent
991 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
992 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
993     $('#GBcontainer').empty();
994     $('#GBcontainer').css('overflow', 'auto');
995         
996     // We want to display two facing pages.  We may be missing
997     // one side of the spread because it is the first/last leaf,
998     // foldouts, missing pages, etc
999
1000     //var targetLeaf = this.displayedIndices[0];
1001     var targetLeaf = this.firstIndex;
1002
1003     if (targetLeaf < this.firstDisplayableIndex()) {
1004         targetLeaf = this.firstDisplayableIndex();
1005     }
1006     
1007     if (targetLeaf > this.lastDisplayableIndex()) {
1008         targetLeaf = this.lastDisplayableIndex();
1009     }
1010     
1011     //this.twoPage.currentIndexL = null;
1012     //this.twoPage.currentIndexR = null;
1013     //this.pruneUnusedImgs();
1014     
1015     var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1016     this.twoPage.currentIndexL = currentSpreadIndices[0];
1017     this.twoPage.currentIndexR = currentSpreadIndices[1];
1018     this.firstIndex = this.twoPage.currentIndexL;
1019     
1020     this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1021
1022     this.pruneUnusedImgs();
1023     this.prefetch(); // Preload images or reload if scaling has changed
1024
1025     //console.dir(this.twoPage);
1026     
1027     // Add the two page view
1028     // $$$ Can we get everything set up and then append?
1029     $('#GBcontainer').append('<div id="GBtwopageview"></div>');
1030
1031     // $$$ calculate first then set
1032     $('#GBtwopageview').css( {
1033         height: this.twoPage.totalHeight + 'px',
1034         width: this.twoPage.totalWidth + 'px',
1035         position: 'absolute'
1036         });
1037         
1038     // If there will not be scrollbars (e.g. when zooming out) we center the book
1039     // since otherwise the book will be stuck off-center
1040     if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
1041         centerPercentageX = 0.5;
1042     }
1043     if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
1044         centerPercentageY = 0.5;
1045     }
1046         
1047     this.twoPageCenterView(centerPercentageX, centerPercentageY);
1048     
1049     this.twoPage.coverDiv = document.createElement('div');
1050     $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
1051         border: '1px solid rgb(68, 25, 17)',
1052         width:  this.twoPage.bookCoverDivWidth + 'px',
1053         height: this.twoPage.bookCoverDivHeight+'px',
1054         visibility: 'visible',
1055         position: 'absolute',
1056         backgroundColor: '#663929',
1057         left: this.twoPage.bookCoverDivLeft + 'px',
1058         top: this.twoPage.bookCoverDivTop+'px',
1059         MozBorderRadiusTopleft: '7px',
1060         MozBorderRadiusTopright: '7px',
1061         MozBorderRadiusBottomright: '7px',
1062         MozBorderRadiusBottomleft: '7px'
1063     }).appendTo('#GBtwopageview');
1064     
1065     this.leafEdgeR = document.createElement('div');
1066     this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1067     $(this.leafEdgeR).css({
1068         borderStyle: 'solid solid solid none',
1069         borderColor: 'rgb(51, 51, 34)',
1070         borderWidth: '1px 1px 1px 0px',
1071         background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1072         width: this.twoPage.leafEdgeWidthR + 'px',
1073         height: this.twoPage.height-1 + 'px',
1074         /*right: '10px',*/
1075         left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1076         top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1077         position: 'absolute'
1078     }).appendTo('#GBtwopageview');
1079     
1080     this.leafEdgeL = document.createElement('div');
1081     this.leafEdgeL.className = 'leafEdgeL';
1082     $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1083         borderStyle: 'solid none solid solid',
1084         borderColor: 'rgb(51, 51, 34)',
1085         borderWidth: '1px 0px 1px 1px',
1086         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1087         width: this.twoPage.leafEdgeWidthL + 'px',
1088         height: this.twoPage.height-1 + 'px',
1089         left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1090         top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',    
1091         position: 'absolute'
1092     }).appendTo('#GBtwopageview');
1093
1094     div = document.createElement('div');
1095     $(div).attr('id', 'GBbookspine').css({
1096         border:          '1px solid rgb(68, 25, 17)',
1097         width:           this.twoPage.bookSpineDivWidth+'px',
1098         height:          this.twoPage.bookSpineDivHeight+'px',
1099         position:        'absolute',
1100         backgroundColor: 'rgb(68, 25, 17)',
1101         left:            this.twoPage.bookSpineDivLeft+'px',
1102         top:             this.twoPage.bookSpineDivTop+'px'
1103     }).appendTo('#GBtwopageview');
1104     
1105     var self = this; // for closure
1106     
1107     /* Flip areas no longer used
1108     this.twoPage.leftFlipArea = document.createElement('div');
1109     this.twoPage.leftFlipArea.className = 'GBfliparea';
1110     $(this.twoPage.leftFlipArea).attr('id', 'GBleftflip').css({
1111         border: '0',
1112         width:  this.twoPageFlipAreaWidth() + 'px',
1113         height: this.twoPageFlipAreaHeight() + 'px',
1114         position: 'absolute',
1115         left:   this.twoPageLeftFlipAreaLeft() + 'px',
1116         top:    this.twoPageFlipAreaTop() + 'px',
1117         cursor: 'w-resize',
1118         zIndex: 100
1119     }).bind('click', function(e) {
1120         self.left();
1121     }).bind('mousedown', function(e) {
1122         e.preventDefault();
1123     }).appendTo('#GBtwopageview');
1124     
1125     this.twoPage.rightFlipArea = document.createElement('div');
1126     this.twoPage.rightFlipArea.className = 'GBfliparea';
1127     $(this.twoPage.rightFlipArea).attr('id', 'GBrightflip').css({
1128         border: '0',
1129         width:  this.twoPageFlipAreaWidth() + 'px',
1130         height: this.twoPageFlipAreaHeight() + 'px',
1131         position: 'absolute',
1132         left:   this.twoPageRightFlipAreaLeft() + 'px',
1133         top:    this.twoPageFlipAreaTop() + 'px',
1134         cursor: 'e-resize',
1135         zIndex: 100
1136     }).bind('click', function(e) {
1137         self.right();
1138     }).bind('mousedown', function(e) {
1139         e.preventDefault();
1140     }).appendTo('#GBtwopageview');
1141     */
1142     
1143     this.prepareTwoPagePopUp();
1144     
1145     this.displayedIndices = [];
1146     
1147     //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1148     //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1149     
1150     this.drawLeafsTwoPage();
1151     this.updateSearchHilites2UP();
1152     this.updateToolbarZoom(this.reduce);
1153     
1154     this.prefetch();
1155 }
1156
1157 // prepareTwoPagePopUp()
1158 //
1159 // This function prepares the "View Page n" popup that shows while the mouse is
1160 // over the left/right "stack of sheets" edges.  It also binds the mouse
1161 // events for these divs.
1162 //______________________________________________________________________________
1163 GnuBook.prototype.prepareTwoPagePopUp = function() {
1164
1165     this.twoPagePopUp = document.createElement('div');
1166     $(this.twoPagePopUp).css({
1167         border: '1px solid black',
1168         padding: '2px 6px',
1169         position: 'absolute',
1170         fontFamily: 'sans-serif',
1171         fontSize: '14px',
1172         zIndex: '1000',
1173         backgroundColor: 'rgb(255, 255, 238)',
1174         opacity: 0.85
1175     }).appendTo('#GBcontainer');
1176     $(this.twoPagePopUp).hide();
1177     
1178     $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1179         $(e.data.twoPagePopUp).show();
1180     });
1181
1182     $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1183         $(e.data.twoPagePopUp).hide();
1184     });
1185
1186     $(this.leafEdgeL).bind('click', this, function(e) { 
1187         e.data.autoStop();
1188         var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1189         e.data.jumpToIndex(jumpIndex);
1190     });
1191
1192     $(this.leafEdgeR).bind('click', this, function(e) { 
1193         e.data.autoStop();
1194         var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1195         e.data.jumpToIndex(jumpIndex);    
1196     });
1197
1198     $(this.leafEdgeR).bind('mousemove', this, function(e) {
1199
1200         var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1201         $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1202         
1203         // $$$ TODO: Make sure popup is positioned so that it is in view
1204         // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)        
1205         $(e.data.twoPagePopUp).css({
1206             left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1207             top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1208         });
1209     });
1210
1211     $(this.leafEdgeL).bind('mousemove', this, function(e) {
1212     
1213         var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1214         $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1215
1216         // $$$ TODO: Make sure popup is positioned so that it is in view
1217         //           (https://bugs.edge.launchpad.net/gnubook/+bug/327456)        
1218         $(e.data.twoPagePopUp).css({
1219             left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1220             top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1221         });
1222     });
1223 }
1224
1225 // calculateSpreadSize()
1226 //______________________________________________________________________________
1227 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1228 // this.twoPage.currentIndexR
1229 // This function sets this.twoPage.height, twoPage.width
1230
1231 GnuBook.prototype.calculateSpreadSize = function() {
1232
1233     var firstIndex  = this.twoPage.currentIndexL;
1234     var secondIndex = this.twoPage.currentIndexR;
1235     //console.log('first page is ' + firstIndex);
1236
1237     // Calculate page sizes and total leaf width
1238     var spreadSize;
1239     if ( this.twoPage.autofit) {    
1240         spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1241     } else {
1242         // set based on reduction factor
1243         spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1244     }
1245     
1246     // Both pages together
1247     this.twoPage.height = spreadSize.height;
1248     this.twoPage.width = spreadSize.width;
1249     
1250     // Individual pages
1251     this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1252     this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1253     
1254     // Leaf edges
1255     this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1256     this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1257     this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1258     
1259     
1260     // Book cover
1261     // The width of the book cover div.  The combined width of both pages, twice the width
1262     // of the book cover internal padding (2*10) and the page edges
1263     this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1264     // The height of the book cover div
1265     this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1266     
1267     
1268     // We calculate the total width and height for the div so that we can make the book
1269     // spine centered
1270     var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1271     var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1272     var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1273     var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1274     this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1275     this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1276         
1277     // We want to minimize the unused space in two-up mode (maximize the amount of page
1278     // shown).  We give width to the leaf edges and these widths change (though the sum
1279     // of the two remains constant) as we flip through the book.  With the book
1280     // cover centered and fixed in the GBcontainer div the page images will meet
1281     // at the "gutter" which is generally offset from the center.
1282     this.twoPage.middle = this.twoPage.totalWidth >> 1;
1283     this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1284     
1285     // The left edge of the book cover moves depending on the width of the pages
1286     // $$$ change to getter
1287     this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1288     // The top edge of the book cover stays a fixed distance from the top
1289     this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1290
1291     // Book spine
1292     this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1293     this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1294     this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1295
1296
1297     this.reduce = spreadSize.reduce; // $$$ really set this here?
1298 }
1299
1300 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1301     var ideal = {};
1302
1303     // We check which page is closest to a "normal" page and use that to set the height
1304     // for both pages.  This means that foldouts and other odd size pages will be displayed
1305     // smaller than the nominal zoom amount.
1306     var canon5Dratio = 1.5;
1307     
1308     var first = {
1309         height: this.getPageHeight(firstIndex),
1310         width: this.getPageWidth(firstIndex)
1311     }
1312     
1313     var second = {
1314         height: this.getPageHeight(secondIndex),
1315         width: this.getPageWidth(secondIndex)
1316     }
1317     
1318     var firstIndexRatio  = first.height / first.width;
1319     var secondIndexRatio = second.height / second.width;
1320     //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1321
1322     var ratio;
1323     if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1324         ratio = firstIndexRatio;
1325         //console.log('using firstIndexRatio ' + ratio);
1326     } else {
1327         ratio = secondIndexRatio;
1328         //console.log('using secondIndexRatio ' + ratio);
1329     }
1330
1331     var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1332     var maxLeafEdgeWidth   = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1333     ideal.totalLeafEdgeWidth     = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1334     
1335     var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1336     var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1337     
1338     ideal.width = ($('#GBcontainer').width() - widthOutsidePages) >> 1;
1339     ideal.width -= 10; // $$$ fudge factor
1340     ideal.height = $('#GBcontainer').height() - heightOutsidePages;
1341     ideal.height -= 20; // fudge factor
1342     //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1343
1344     if (ideal.height/ratio <= ideal.width) {
1345         //use height
1346         ideal.width = parseInt(ideal.height/ratio);
1347     } else {
1348         //use width
1349         ideal.height = parseInt(ideal.width*ratio);
1350     }
1351     
1352     // $$$ check this logic with large spreads
1353     ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1354     
1355     return ideal;
1356 }
1357
1358 // getSpreadSizeFromReduce()
1359 //______________________________________________________________________________
1360 // Returns the spread size calculated from the reduction factor for the given pages
1361 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1362     var spreadSize = {};
1363     // $$$ Scale this based on reduce?
1364     var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1365     var maxLeafEdgeWidth   = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1366     spreadSize.totalLeafEdgeWidth     = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1367
1368     // $$$ Possibly incorrect -- we should make height "dominant"
1369     var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1370     var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1371     spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1372     spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1373     spreadSize.reduce = reduce;
1374     
1375     return spreadSize;
1376 }
1377
1378 // twoPageGetAutofitReduce()
1379 //______________________________________________________________________________
1380 // Returns the current ideal reduction factor
1381 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1382     var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1383     return spreadSize.reduce;
1384 }
1385
1386 // twoPageSetCursor()
1387 //______________________________________________________________________________
1388 // Set the cursor for two page view
1389 GnuBook.prototype.twoPageSetCursor = function() {
1390     // console.log('setting cursor');
1391     if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1392          ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1393         $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1394         $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1395     } else {
1396         $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1397         $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1398     }
1399 }
1400
1401 // currentIndex()
1402 //______________________________________________________________________________
1403 // Returns the currently active index.
1404 GnuBook.prototype.currentIndex = function() {
1405     // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1406     if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1407         return this.firstIndex;
1408     } else {
1409         throw 'currentIndex called for unimplemented mode ' + this.mode;
1410     }
1411 }
1412
1413 // right()
1414 //______________________________________________________________________________
1415 // Flip the right page over onto the left
1416 GnuBook.prototype.right = function() {
1417     if ('rl' != this.pageProgression) {
1418         // LTR
1419         gb.next();
1420     } else {
1421         // RTL
1422         gb.prev();
1423     }
1424 }
1425
1426 // rightmost()
1427 //______________________________________________________________________________
1428 // Flip to the rightmost page
1429 GnuBook.prototype.rightmost = function() {
1430     if ('rl' != this.pageProgression) {
1431         gb.last();
1432     } else {
1433         gb.first();
1434     }
1435 }
1436
1437 // left()
1438 //______________________________________________________________________________
1439 // Flip the left page over onto the right.
1440 GnuBook.prototype.left = function() {
1441     if ('rl' != this.pageProgression) {
1442         // LTR
1443         gb.prev();
1444     } else {
1445         // RTL
1446         gb.next();
1447     }
1448 }
1449
1450 // leftmost()
1451 //______________________________________________________________________________
1452 // Flip to the leftmost page
1453 GnuBook.prototype.leftmost = function() {
1454     if ('rl' != this.pageProgression) {
1455         gb.first();
1456     } else {
1457         gb.last();
1458     }
1459 }
1460
1461 // next()
1462 //______________________________________________________________________________
1463 GnuBook.prototype.next = function() {
1464     if (2 == this.mode) {
1465         this.autoStop();
1466         this.flipFwdToIndex(null);
1467     } else {
1468         if (this.firstIndex < this.lastDisplayableIndex()) {
1469             this.jumpToIndex(this.firstIndex+1);
1470         }
1471     }
1472 }
1473
1474 // prev()
1475 //______________________________________________________________________________
1476 GnuBook.prototype.prev = function() {
1477     if (2 == this.mode) {
1478         this.autoStop();
1479         this.flipBackToIndex(null);
1480     } else {
1481         if (this.firstIndex >= 1) {
1482             this.jumpToIndex(this.firstIndex-1);
1483         }    
1484     }
1485 }
1486
1487 GnuBook.prototype.first = function() {
1488     if (2 == this.mode) {
1489         this.jumpToIndex(2);
1490     }
1491     else {
1492         this.jumpToIndex(0);
1493     }
1494 }
1495
1496 GnuBook.prototype.last = function() {
1497     if (2 == this.mode) {
1498         this.jumpToIndex(this.lastDisplayableIndex());
1499     }
1500     else {
1501         this.jumpToIndex(this.lastDisplayableIndex());
1502     }
1503 }
1504
1505 // flipBackToIndex()
1506 //______________________________________________________________________________
1507 // to flip back one spread, pass index=null
1508 GnuBook.prototype.flipBackToIndex = function(index) {
1509     if (1 == this.mode) return;
1510
1511     var leftIndex = this.twoPage.currentIndexL;
1512     
1513     // $$$ Need to change this to be able to see first spread.
1514     //     See https://bugs.launchpad.net/gnubook/+bug/296788
1515     if (leftIndex <= 2) return;
1516     if (this.animating) return;
1517
1518     if (null != this.leafEdgeTmp) {
1519         alert('error: leafEdgeTmp should be null!');
1520         return;
1521     }
1522     
1523     if (null == index) {
1524         index = leftIndex-2;
1525     }
1526     //if (index<0) return;
1527     
1528     var previousIndices = this.getSpreadIndices(index);
1529     
1530     if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1531         return;
1532     }
1533     
1534     //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1535
1536     this.animating = true;
1537     
1538     if ('rl' != this.pageProgression) {
1539         // Assume LTR and we are going backward    
1540         this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);        
1541         this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1542     } else {
1543         // RTL and going backward
1544         var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1545         this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1546     }
1547 }
1548
1549 // flipLeftToRight()
1550 //______________________________________________________________________________
1551 // Flips the page on the left towards the page on the right
1552 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1553
1554     var leftLeaf = this.twoPage.currentIndexL;
1555     
1556     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1557     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);    
1558     var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1559     
1560     var currWidthL   = this.getPageWidth2UP(leftLeaf);
1561     var newWidthL    = this.getPageWidth2UP(newIndexL);
1562     var newWidthR    = this.getPageWidth2UP(newIndexR);
1563
1564     var top  = this.twoPageTop();
1565     var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1566     
1567     //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1568     //console.log('  gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1569     
1570     //animation strategy:
1571     // 0. remove search highlight, if any.
1572     // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge 
1573     //    of the left leaf and where the user clicked in the leaf edge.
1574     //    Note that if this function was triggered by left() and not a
1575     //    mouse click, the width of leafEdgeTmp is very small (zero px).
1576     // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1577     //    leftLeaf to width=0.
1578     // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1579     //    (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1580     //    its new full width.
1581     // 4. After step 3 is finished, do the following:
1582     //      - remove leafEdgeTmp from the dom.
1583     //      - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1584     //          and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1585     //      - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1586     //          and width=newLeafEdgeWidthL.
1587     //      - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1588     //          and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1589     //      - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1590     //      - remove old left and right leafs from the dom [pruneUnusedImgs()].
1591     //      - prefetch new adjacent leafs.
1592     //      - set up click handlers for both new left and right leafs.
1593     //      - redraw the search highlight.
1594     //      - update the pagenum box and the url.
1595     
1596     
1597     var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1598
1599     this.leafEdgeTmp = document.createElement('div');
1600     $(this.leafEdgeTmp).css({
1601         borderStyle: 'solid none solid solid',
1602         borderColor: 'rgb(51, 51, 34)',
1603         borderWidth: '1px 0px 1px 1px',
1604         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1605         width: leafEdgeTmpW + 'px',
1606         height: this.twoPage.height-1 + 'px',
1607         left: leftEdgeTmpLeft + 'px',
1608         top: top+'px',    
1609         position: 'absolute',
1610         zIndex:1000
1611     }).appendTo('#GBtwopageview');
1612     
1613     //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1614     $(this.leafEdgeL).css({
1615         width: newLeafEdgeWidthL+'px', 
1616         left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1617     });   
1618
1619     // Left gets the offset of the current left leaf from the document
1620     var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1621     // $$$ This seems very similar to the gutter.  May be able to consolidate the logic.
1622     var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1623     
1624     // We change the left leaf to right positioning
1625     // $$$ This causes animation glitches during resize.  See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1626     $(this.prefetchedImgs[leftLeaf]).css({
1627         right: right,
1628         left: ''
1629     });
1630
1631     $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');    
1632     //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1633     
1634     var self = this;
1635
1636     this.removeSearchHilites();
1637
1638     //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1639     $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1640     
1641         //console.log('     and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1642         $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1643
1644         //console.log('  animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1645         $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1646             $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1647             
1648             $(self.leafEdgeR).css({
1649                 // Moves the right leaf edge
1650                 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1651                 left:  gutter+newWidthR+'px'
1652             });
1653
1654             $(self.leafEdgeL).css({
1655                 // Moves and resizes the left leaf edge
1656                 width: newLeafEdgeWidthL+'px',
1657                 left:  gutter-newWidthL-newLeafEdgeWidthL+'px'
1658             });
1659
1660             // Resizes the brown border div
1661             $(self.twoPage.coverDiv).css({
1662                 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1663                 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1664             });
1665             
1666             $(self.leafEdgeTmp).remove();
1667             self.leafEdgeTmp = null;
1668
1669             // $$$ TODO refactor with opposite direction flip
1670             
1671             self.twoPage.currentIndexL = newIndexL;
1672             self.twoPage.currentIndexR = newIndexR;
1673             self.twoPage.scaledWL = newWidthL;
1674             self.twoPage.scaledWR = newWidthR;
1675             self.twoPage.gutter = gutter;
1676             
1677             self.firstIndex = self.twoPage.currentIndexL;
1678             self.displayedIndices = [newIndexL, newIndexR];
1679             self.pruneUnusedImgs();
1680             self.prefetch();            
1681             self.animating = false;
1682             
1683             self.updateSearchHilites2UP();
1684             self.updatePageNumBox2UP();
1685             
1686             // self.twoPagePlaceFlipAreas(); // No longer used
1687             self.setMouseHandlers2UP();
1688             self.twoPageSetCursor();
1689             
1690             if (self.animationFinishedCallback) {
1691                 self.animationFinishedCallback();
1692                 self.animationFinishedCallback = null;
1693             }
1694         });
1695     });        
1696     
1697 }
1698
1699 // flipFwdToIndex()
1700 //______________________________________________________________________________
1701 // Whether we flip left or right is dependent on the page progression
1702 // to flip forward one spread, pass index=null
1703 GnuBook.prototype.flipFwdToIndex = function(index) {
1704
1705     if (this.animating) return;
1706
1707     if (null != this.leafEdgeTmp) {
1708         alert('error: leafEdgeTmp should be null!');
1709         return;
1710     }
1711
1712     if (null == index) {
1713         index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1714     }
1715     if (index > this.lastDisplayableIndex()) return;
1716
1717     this.animating = true;
1718     
1719     var nextIndices = this.getSpreadIndices(index);
1720     
1721     //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1722
1723     if ('rl' != this.pageProgression) {
1724         // We did not specify RTL
1725         var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1726         this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1727     } else {
1728         // RTL
1729         var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1730         this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1731     }
1732 }
1733
1734 // flipRightToLeft(nextL, nextR, gutter)
1735 // $$$ better not to have to pass gutter in
1736 //______________________________________________________________________________
1737 // Flip from left to right and show the nextL and nextR indices on those sides
1738 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1739     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1740     var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1741     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);  
1742     var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1743
1744     var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1745
1746     var top = this.twoPageTop();
1747     var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1748
1749     var middle = this.twoPage.middle;
1750     var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1751     
1752     this.leafEdgeTmp = document.createElement('div');
1753     $(this.leafEdgeTmp).css({
1754         borderStyle: 'solid none solid solid',
1755         borderColor: 'rgb(51, 51, 34)',
1756         borderWidth: '1px 0px 1px 1px',
1757         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1758         width: leafEdgeTmpW + 'px',
1759         height: this.twoPage.height-1 + 'px',
1760         left: gutter+scaledW+'px',
1761         top: top+'px',    
1762         position: 'absolute',
1763         zIndex:1000
1764     }).appendTo('#GBtwopageview');
1765
1766     //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1767     //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1768     
1769     var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1770     var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1771     var newWidthL = this.getPageWidth2UP(newIndexL);
1772     var newWidthR = this.getPageWidth2UP(newIndexR);
1773     
1774     $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1775
1776     var self = this; // closure-tastic!
1777
1778     var speed = this.flipSpeed;
1779
1780     this.removeSearchHilites();
1781     
1782     $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');    
1783     $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1784         $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');    
1785         $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1786             $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1787             
1788             $(self.leafEdgeL).css({
1789                 width: newLeafEdgeWidthL+'px', 
1790                 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1791             });
1792             
1793             // Resizes the book cover
1794             $(self.twoPage.coverDiv).css({
1795                 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1796                 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1797             });
1798             
1799             $(self.leafEdgeTmp).remove();
1800             self.leafEdgeTmp = null;
1801             
1802             self.twoPage.currentIndexL = newIndexL;
1803             self.twoPage.currentIndexR = newIndexR;
1804             self.twoPage.scaledWL = newWidthL;
1805             self.twoPage.scaledWR = newWidthR;
1806             self.twoPage.gutter = gutter;
1807
1808             self.firstIndex = self.twoPage.currentIndexL;
1809             self.displayedIndices = [newIndexL, newIndexR];
1810             self.pruneUnusedImgs();
1811             self.prefetch();
1812             self.animating = false;
1813
1814
1815             self.updateSearchHilites2UP();
1816             self.updatePageNumBox2UP();
1817             
1818             // self.twoPagePlaceFlipAreas(); // No longer used
1819             self.setMouseHandlers2UP();     
1820             self.twoPageSetCursor();
1821             
1822             if (self.animationFinishedCallback) {
1823                 self.animationFinishedCallback();
1824                 self.animationFinishedCallback = null;
1825             }
1826         });
1827     });    
1828 }
1829
1830 // setMouseHandlers2UP
1831 //______________________________________________________________________________
1832 GnuBook.prototype.setMouseHandlers2UP = function() {
1833     /*
1834     $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1835         //self.prevPage();
1836         self.autoStop();
1837         self.left();
1838     });
1839     $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1840         //self.nextPage();'
1841         self.autoStop();
1842         self.right();        
1843     });
1844     */
1845     
1846     this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
1847     this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
1848         { self: this },
1849         function(e) {
1850             e.data.self.left();
1851         }
1852     );
1853         
1854     this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
1855     this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
1856         { self: this },
1857         function(e) {
1858             e.data.self.right();
1859         }
1860     );
1861 }
1862
1863 // prefetchImg()
1864 //______________________________________________________________________________
1865 GnuBook.prototype.prefetchImg = function(index) {
1866     var pageURI = this.getPageURI(index);
1867
1868     // Load image if not loaded or URI has changed (e.g. due to scaling)
1869     var loadImage = false;
1870     if (undefined == this.prefetchedImgs[index]) {
1871         //console.log('no image for ' + index);
1872         loadImage = true;
1873     } else if (pageURI != this.prefetchedImgs[index].uri) {
1874         //console.log('uri changed for ' + index);
1875         loadImage = true;
1876     }
1877     
1878     if (loadImage) {
1879         //console.log('prefetching ' + index);
1880         var img = document.createElement("img");
1881         img.src = pageURI;
1882         img.uri = pageURI; // browser may rewrite src so we stash raw URI here
1883         this.prefetchedImgs[index] = img;
1884     }
1885 }
1886
1887
1888 // prepareFlipLeftToRight()
1889 //
1890 //______________________________________________________________________________
1891 //
1892 // Prepare to flip the left page towards the right.  This corresponds to moving
1893 // backward when the page progression is left to right.
1894 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1895
1896     //console.log('  preparing left->right for ' + prevL + ',' + prevR);
1897
1898     this.prefetchImg(prevL);
1899     this.prefetchImg(prevR);
1900     
1901     var height  = this.getPageHeight(prevL); 
1902     var width   = this.getPageWidth(prevL);    
1903     var middle = this.twoPage.middle;
1904     var top  = this.twoPageTop();                
1905     var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1906
1907     // The gutter is the dividing line between the left and right pages.
1908     // It is offset from the middle to create the illusion of thickness to the pages
1909     var gutter = middle + this.gutterOffsetForIndex(prevL);
1910     
1911     //console.log('    gutter for ' + prevL + ' is ' + gutter);
1912     //console.log('    prevL.left: ' + (gutter - scaledW) + 'px');
1913     //console.log('    changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1914     
1915     $(this.prefetchedImgs[prevL]).css({
1916         position: 'absolute',
1917         left: gutter-scaledW+'px',
1918         right: '', // clear right property
1919         top:    top+'px',
1920         backgroundColor: 'rgb(234, 226, 205)',
1921         height: this.twoPage.height,
1922         width:  scaledW+'px',
1923         borderRight: '1px solid black',
1924         zIndex: 1
1925     });
1926
1927     $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1928
1929     //console.log('    changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1930
1931     $(this.prefetchedImgs[prevR]).css({
1932         position: 'absolute',
1933         left:   gutter+'px',
1934         right: '',
1935         top:    top+'px',
1936         backgroundColor: 'rgb(234, 226, 205)',
1937         height: this.twoPage.height,
1938         width:  '0px',
1939         borderLeft: '1px solid black',
1940         zIndex: 2
1941     });
1942
1943     $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1944             
1945 }
1946
1947 // $$$ mang we're adding an extra pixel in the middle.  See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1948 // prepareFlipRightToLeft()
1949 //______________________________________________________________________________
1950 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1951
1952     //console.log('  preparing left<-right for ' + nextL + ',' + nextR);
1953
1954     // Prefetch images
1955     this.prefetchImg(nextL);
1956     this.prefetchImg(nextR);
1957
1958     var height  = this.getPageHeight(nextR); 
1959     var width   = this.getPageWidth(nextR);    
1960     var middle = this.twoPage.middle;
1961     var top  = this.twoPageTop();               
1962     var scaledW = this.twoPage.height*width/height;
1963
1964     var gutter = middle + this.gutterOffsetForIndex(nextL);
1965         
1966     //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1967     $(this.prefetchedImgs[nextR]).css({
1968         position: 'absolute',
1969         left:   gutter+'px',
1970         top:    top+'px',
1971         backgroundColor: 'rgb(234, 226, 205)',
1972         height: this.twoPage.height,
1973         width:  scaledW+'px',
1974         borderLeft: '1px solid black',
1975         zIndex: 1
1976     });
1977
1978     $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1979
1980     height  = this.getPageHeight(nextL); 
1981     width   = this.getPageWidth(nextL);      
1982     scaledW = this.twoPage.height*width/height;
1983
1984     //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1985     $(this.prefetchedImgs[nextL]).css({
1986         position: 'absolute',
1987         right:   $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1988         top:    top+'px',
1989         backgroundColor: 'rgb(234, 226, 205)',
1990         height: this.twoPage.height,
1991         width:  0+'px', // Start at 0 width, then grow to the left
1992         borderRight: '1px solid black',
1993         zIndex: 2
1994     });
1995
1996     $('#GBtwopageview').append(this.prefetchedImgs[nextL]);    
1997             
1998 }
1999
2000 // getNextLeafs() -- NOT RTL AWARE
2001 //______________________________________________________________________________
2002 // GnuBook.prototype.getNextLeafs = function(o) {
2003 //     //TODO: we might have two left or two right leafs in a row (damaged book)
2004 //     //For now, assume that leafs are contiguous.
2005 //     
2006 //     //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2007 //     o.L = this.twoPage.currentIndexL+2;
2008 //     o.R = this.twoPage.currentIndexL+3;
2009 // }
2010
2011 // getprevLeafs() -- NOT RTL AWARE
2012 //______________________________________________________________________________
2013 // GnuBook.prototype.getPrevLeafs = function(o) {
2014 //     //TODO: we might have two left or two right leafs in a row (damaged book)
2015 //     //For now, assume that leafs are contiguous.
2016 //     
2017 //     //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2018 //     o.L = this.twoPage.currentIndexL-2;
2019 //     o.R = this.twoPage.currentIndexL-1;
2020 // }
2021
2022 // pruneUnusedImgs()
2023 //______________________________________________________________________________
2024 GnuBook.prototype.pruneUnusedImgs = function() {
2025     //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2026     for (var key in this.prefetchedImgs) {
2027         //console.log('key is ' + key);
2028         if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2029             //console.log('removing key '+ key);
2030             $(this.prefetchedImgs[key]).remove();
2031         }
2032         if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2033             //console.log('deleting key '+ key);
2034             delete this.prefetchedImgs[key];
2035         }
2036     }
2037 }
2038
2039 // prefetch()
2040 //______________________________________________________________________________
2041 GnuBook.prototype.prefetch = function() {
2042
2043     // prefetch visible pages first
2044     this.prefetchImg(this.twoPage.currentIndexL);
2045     this.prefetchImg(this.twoPage.currentIndexR);
2046     
2047     var adjacentPagesToLoad = 3;
2048     
2049     var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2050     var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2051         
2052     var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2053     var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2054     
2055     // Load images spreading out from current
2056     for (var i = 1; i <= adjacentPagesToLoad; i++) {
2057         var goingDown = lowCurrent - i;
2058         if (goingDown >= start) {
2059             this.prefetchImg(goingDown);
2060         }
2061         var goingUp = highCurrent + i;
2062         if (goingUp <= end) {
2063             this.prefetchImg(goingUp);
2064         }
2065     }
2066
2067     /*
2068     var lim = this.twoPage.currentIndexL-4;
2069     var i;
2070     lim = Math.max(lim, 0);
2071     for (i = lim; i < this.twoPage.currentIndexL; i++) {
2072         this.prefetchImg(i);
2073     }
2074     
2075     if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2076         lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2077         for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2078             this.prefetchImg(i);
2079         }
2080     }
2081     */
2082 }
2083
2084 // getPageWidth2UP()
2085 //______________________________________________________________________________
2086 GnuBook.prototype.getPageWidth2UP = function(index) {
2087     // We return the width based on the dominant height
2088     var height  = this.getPageHeight(index); 
2089     var width   = this.getPageWidth(index);    
2090     return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2091 }    
2092
2093 // search()
2094 //______________________________________________________________________________
2095 GnuBook.prototype.search = function(term) {
2096     this.searchTerm = term;
2097     $('#GnuBookSearchScript').remove();
2098         var script  = document.createElement("script");
2099         script.setAttribute('id', 'GnuBookSearchScript');
2100         script.setAttribute("type", "text/javascript");
2101         script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
2102         document.getElementsByTagName('head')[0].appendChild(script);
2103         $('#GnuBookSearchBox').val(term);
2104         $('#GnuBookSearchResults').html('Searching...');
2105 }
2106
2107 // GBSearchCallback()
2108 //______________________________________________________________________________
2109 GnuBook.prototype.GBSearchCallback = function(txt) {
2110     //alert(txt);
2111     if (jQuery.browser.msie) {
2112         var dom=new ActiveXObject("Microsoft.XMLDOM");
2113         dom.async="false";
2114         dom.loadXML(txt);    
2115     } else {
2116         var parser = new DOMParser();
2117         var dom = parser.parseFromString(txt, "text/xml");    
2118     }
2119     
2120     $('#GnuBookSearchResults').empty();    
2121     $('#GnuBookSearchResults').append('<ul>');
2122     
2123     for (var key in this.searchResults) {
2124         if (null != this.searchResults[key].div) {
2125             $(this.searchResults[key].div).remove();
2126         }
2127         delete this.searchResults[key];
2128     }
2129     
2130     var pages = dom.getElementsByTagName('PAGE');
2131     
2132     if (0 == pages.length) {
2133         // $$$ it would be nice to echo the (sanitized) search result here
2134         $('#GnuBookSearchResults').append('<li>No search results found</li>');
2135     } else {    
2136         for (var i = 0; i < pages.length; i++){
2137             //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2138     
2139             
2140             var re = new RegExp (/_(\d{4})/);
2141             var reMatch = re.exec(pages[i].getAttribute('file'));
2142             var index = parseInt(reMatch[1], 10);
2143             //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2144             
2145             var children = pages[i].childNodes;
2146             var context = '';
2147             for (var j=0; j<children.length; j++) {
2148                 //console.log(j + ' - ' + children[j].nodeName);
2149                 //console.log(children[j].firstChild.nodeValue);
2150                 if ('CONTEXT' == children[j].nodeName) {
2151                     context += children[j].firstChild.nodeValue;
2152                 } else if ('WORD' == children[j].nodeName) {
2153                     context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2154                     
2155                     var index = this.leafNumToIndex(index);
2156                     if (null != index) {
2157                         //coordinates are [left, bottom, right, top, [baseline]]
2158                         //we'll skip baseline for now...
2159                         var coords = children[j].getAttribute('coords').split(',',4);
2160                         if (4 == coords.length) {
2161                             this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
2162                         }
2163                     }
2164                 }
2165             }
2166             var pageName = this.getPageName(index);
2167             //TODO: remove hardcoded instance name
2168             $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
2169         }
2170     }
2171     $('#GnuBookSearchResults').append('</ul>');
2172
2173     this.updateSearchHilites();
2174 }
2175
2176 // updateSearchHilites()
2177 //______________________________________________________________________________
2178 GnuBook.prototype.updateSearchHilites = function() {
2179     if (2 == this.mode) {
2180         this.updateSearchHilites2UP();
2181     } else {
2182         this.updateSearchHilites1UP();
2183     }
2184 }
2185
2186 // showSearchHilites1UP()
2187 //______________________________________________________________________________
2188 GnuBook.prototype.updateSearchHilites1UP = function() {
2189
2190     for (var key in this.searchResults) {
2191         
2192         if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2193             var result = this.searchResults[key];
2194             if(null == result.div) {
2195                 result.div = document.createElement('div');
2196                 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
2197                 //console.log('appending ' + key);
2198             }    
2199             $(result.div).css({
2200                 width:  (result.r-result.l)/this.reduce + 'px',
2201                 height: (result.b-result.t)/this.reduce + 'px',
2202                 left:   (result.l)/this.reduce + 'px',
2203                 top:    (result.t)/this.reduce +'px'
2204             });
2205
2206         } else {
2207             //console.log(key + ' not displayed');
2208             this.searchResults[key].div=null;
2209         }
2210     }
2211 }
2212
2213 // twoPageGutter()
2214 //______________________________________________________________________________
2215 // Returns the position of the gutter (line between the page images)
2216 GnuBook.prototype.twoPageGutter = function() {
2217     return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2218 }
2219
2220 // twoPageTop()
2221 //______________________________________________________________________________
2222 // Returns the offset for the top of the page images
2223 GnuBook.prototype.twoPageTop = function() {
2224     return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2225 }
2226
2227 // twoPageCoverWidth()
2228 //______________________________________________________________________________
2229 // Returns the width of the cover div given the total page width
2230 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2231     return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2232 }
2233
2234 // twoPageGetViewCenter()
2235 //______________________________________________________________________________
2236 // Returns the percentage offset into twopageview div at the center of container div
2237 // { percentageX: float, percentageY: float }
2238 GnuBook.prototype.twoPageGetViewCenter = function() {
2239     var center = {};
2240
2241     var containerOffset = $('#GBcontainer').offset();
2242     var viewOffset = $('#GBtwopageview').offset();
2243     center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2244     center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2245     
2246     return center;
2247 }
2248
2249 // twoPageCenterView(percentageX, percentageY)
2250 //______________________________________________________________________________
2251 // Centers the point given by percentage from left,top of twopageview
2252 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2253     if ('undefined' == typeof(percentageX)) {
2254         percentageX = 0.5;
2255     }
2256     if ('undefined' == typeof(percentageY)) {
2257         percentageY = 0.5;
2258     }
2259
2260     var viewWidth = $('#GBtwopageview').width();
2261     var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2262     var intoViewX = percentageX * viewWidth;
2263     
2264     var viewHeight = $('#GBtwopageview').height();
2265     var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2266     var intoViewY = percentageY * viewHeight;
2267     
2268     if (viewWidth < containerClientWidth) {
2269         // Can fit width without scrollbars - center by adjusting offset
2270         $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');    
2271     } else {
2272         // Need to scroll to center
2273         $('#GBtwopageview').css('left', 0);
2274         $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2275     }
2276     
2277     if (viewHeight < containerClientHeight) {
2278         // Fits with scrollbars - add offset
2279         $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2280     } else {
2281         $('#GBtwopageview').css('top', 0);
2282         $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2283     }
2284 }
2285
2286 // twoPageFlipAreaHeight
2287 //______________________________________________________________________________
2288 // Returns the integer height of the click-to-flip areas at the edges of the book
2289 GnuBook.prototype.twoPageFlipAreaHeight = function() {
2290     return parseInt(this.twoPage.height);
2291 }
2292
2293 // twoPageFlipAreaWidth
2294 //______________________________________________________________________________
2295 // Returns the integer width of the flip areas 
2296 GnuBook.prototype.twoPageFlipAreaWidth = function() {
2297     var max = 100; // $$$ TODO base on view width?
2298     var min = 10;
2299     
2300     var width = this.twoPage.width * 0.15;
2301     return parseInt(GnuBook.util.clamp(width, min, max));
2302 }
2303
2304 // twoPageFlipAreaTop
2305 //______________________________________________________________________________
2306 // Returns integer top offset for flip areas
2307 GnuBook.prototype.twoPageFlipAreaTop = function() {
2308     return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2309 }
2310
2311 // twoPageLeftFlipAreaLeft
2312 //______________________________________________________________________________
2313 // Left offset for left flip area
2314 GnuBook.prototype.twoPageLeftFlipAreaLeft = function() {
2315     return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2316 }
2317
2318 // twoPageRightFlipAreaLeft
2319 //______________________________________________________________________________
2320 // Left offset for right flip area
2321 GnuBook.prototype.twoPageRightFlipAreaLeft = function() {
2322     return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2323 }
2324
2325 // twoPagePlaceFlipAreas
2326 //______________________________________________________________________________
2327 // Readjusts position of flip areas based on current layout
2328 GnuBook.prototype.twoPagePlaceFlipAreas = function() {
2329     // We don't set top since it shouldn't change relative to view
2330     $(this.twoPage.leftFlipArea).css({
2331         left: this.twoPageLeftFlipAreaLeft() + 'px',
2332         width: this.twoPageFlipAreaWidth() + 'px'
2333     });
2334     $(this.twoPage.rightFlipArea).css({
2335         left: this.twoPageRightFlipAreaLeft() + 'px',
2336         width: this.twoPageFlipAreaWidth() + 'px'
2337     });
2338 }
2339     
2340 // showSearchHilites2UP()
2341 //______________________________________________________________________________
2342 GnuBook.prototype.updateSearchHilites2UP = function() {
2343
2344     for (var key in this.searchResults) {
2345         key = parseInt(key, 10);
2346         if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2347             var result = this.searchResults[key];
2348             if(null == result.div) {
2349                 result.div = document.createElement('div');
2350                 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2351                 //console.log('appending ' + key);
2352             }
2353
2354             // We calculate the reduction factor for the specific page because it can be different
2355             // for each page in the spread
2356             var height = this.getPageHeight(key);
2357             var width  = this.getPageWidth(key)
2358             var reduce = this.twoPage.height/height;
2359             var scaledW = parseInt(width*reduce);
2360             
2361             var gutter = this.twoPageGutter();
2362             var pageL;
2363             if ('L' == this.getPageSide(key)) {
2364                 pageL = gutter-scaledW;
2365             } else {
2366                 pageL = gutter;
2367             }
2368             var pageT  = this.twoPageTop();
2369             
2370             $(result.div).css({
2371                 width:  (result.r-result.l)*reduce + 'px',
2372                 height: (result.b-result.t)*reduce + 'px',
2373                 left:   pageL+(result.l)*reduce + 'px',
2374                 top:    pageT+(result.t)*reduce +'px'
2375             });
2376
2377         } else {
2378             //console.log(key + ' not displayed');
2379             if (null != this.searchResults[key].div) {
2380                 //console.log('removing ' + key);
2381                 $(this.searchResults[key].div).remove();
2382             }
2383             this.searchResults[key].div=null;
2384         }
2385     }
2386 }
2387
2388 // removeSearchHilites()
2389 //______________________________________________________________________________
2390 GnuBook.prototype.removeSearchHilites = function() {
2391     for (var key in this.searchResults) {
2392         if (null != this.searchResults[key].div) {
2393             $(this.searchResults[key].div).remove();
2394             this.searchResults[key].div=null;
2395         }        
2396     }
2397 }
2398
2399 // printPage
2400 //______________________________________________________________________________
2401 GnuBook.prototype.printPage = function() {
2402     window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2403
2404     /* iframe implementation
2405
2406     if (null != this.printPopup) { // check if already showing
2407         return;
2408     }
2409     this.printPopup = document.createElement("div");
2410     $(this.printPopup).css({
2411         position: 'absolute',
2412         top:      '20px',
2413         left:     ($('#GBcontainer').width()-400)/2 + 'px',
2414         width:    '400px',
2415         padding:  "20px",
2416         border:   "3px double #999999",
2417         zIndex:   3,
2418         backgroundColor: "#fff"
2419     }).appendTo('#GnuBook');
2420
2421     var indexToPrint;
2422     if (this.constMode1up == this.mode) {
2423         indexToPrint = this.firstIndex;
2424     } else {
2425         indexToPrint = this.twoPage.currentIndexL;
2426     }
2427     
2428     this.indexToPrint = indexToPrint;
2429     
2430     var htmlStr = '<div style="text-align: center;">';
2431     htmlStr =  '<p style="text-align:center;"><b><a href="javascript:void(0);" onclick="window.frames[0].focus(); window.frames[0].print(); return false;">Click here to print this page</a></b></p>';
2432     htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2433     htmlStr +=   '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2434     //htmlStr +=     '<button class="GBicon rollover book_up" onclick="gb.updatePrintFrame(-1); return false;"></button> ';
2435     //htmlStr +=     '<button class="GBicon rollover book_down" onclick="gb.updatePrintFrame(1); return false;"></button>';
2436     htmlStr += '<a href="#" onclick="gb.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="gb.updatePrintFrame(1); return false;">Next</a>';
2437     htmlStr +=   '</p>';
2438     htmlStr += '</div>';
2439     htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2440     htmlStr += '</div>';
2441     
2442     this.printPopup.innerHTML = htmlStr;
2443     
2444     var iframe = document.createElement('iframe');
2445     iframe.id = 'printFrame';
2446     iframe.name = 'printFrame';
2447     iframe.width = '233px'; // 8.5 x 11 aspect
2448     iframe.height = '300px';
2449     
2450     var self = this; // closure
2451         
2452     $(iframe).load(function() {
2453         var doc = GnuBook.util.getIFrameDocument(this);
2454         $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2455     });
2456     
2457     $('#printDiv').prepend(iframe);
2458     */
2459 }
2460
2461 // Get print URI from current indices and mode
2462 GnuBook.prototype.getPrintURI = function() {
2463     var indexToPrint;
2464     if (this.constMode2up == this.mode) {
2465         indexToPrint = this.twoPage.currentIndexL;        
2466     } else {
2467         indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2468     }
2469     
2470     var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2471         + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2472         + '&width=' + this.getPageWidth(indexToPrint) + '&height=' + this.getPageHeight(indexToPrint);
2473    
2474     if (this.constMode2up == this.mode) {
2475         options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this.getPageWidth(this.twoPage.currentIndexR);
2476         options += '&height2=' + this.getPageHeight(this.twoPage.currentIndexR);
2477         options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2478     } else {
2479         options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2480     }
2481
2482     return '/bookreader/print.php?' + options;
2483 }
2484
2485 /* iframe implementation
2486 GnuBook.prototype.getPrintFrameContent = function(index) {    
2487     // We fit the image based on an assumed A4 aspect ratio.  A4 is a bit taller aspect than
2488     // 8.5x11 so we should end up not overflowing on either paper size.
2489     var paperAspect = 8.5 / 11;
2490     var imageAspect = this.getPageWidth(index) / this.getPageHeight(index);
2491     
2492     var rotate = 0;
2493     
2494     // Rotate if possible and appropriate, to get larger image size on printed page
2495     if (this.canRotatePage(index)) {
2496         if (imageAspect > 1 && imageAspect > paperAspect) {
2497             // more wide than square, and more wide than paper
2498             rotate = 90;
2499             imageAspect = 1/imageAspect;
2500         }
2501     }
2502     
2503     var fitAttrs;
2504     if (imageAspect > paperAspect) {
2505         // wider than paper, fit width
2506         fitAttrs = 'width="95%"';
2507     } else {
2508         // taller than paper, fit height
2509         fitAttrs = 'height="95%"';
2510     }
2511
2512     var imageURL = this.getPageURI(index, 1, rotate);
2513     var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2514     iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2515     iframeStr +=   '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2516     iframeStr += '</div>';
2517     iframeStr += '</body></html>';
2518     
2519     return iframeStr;
2520 }
2521
2522 GnuBook.prototype.updatePrintFrame = function(delta) {
2523     var newIndex = this.indexToPrint + delta;
2524     newIndex = GnuBook.util.clamp(newIndex, 0, this.numLeafs - 1);
2525     if (newIndex == this.indexToPrint) {
2526         return;
2527     }
2528     this.indexToPrint = newIndex;
2529     var doc = GnuBook.util.getIFrameDocument($('#printFrame')[0]);
2530     $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2531 }
2532 */
2533
2534 // showEmbedCode()
2535 //______________________________________________________________________________
2536 GnuBook.prototype.showEmbedCode = function() {
2537     if (null != this.embedPopup) { // check if already showing
2538         return;
2539     }
2540     this.autoStop();
2541     this.embedPopup = document.createElement("div");
2542     $(this.embedPopup).css({
2543         position: 'absolute',
2544         top:      '20px',
2545         left:     ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2546         width:    '400px',
2547         padding:  "20px",
2548         border:   "3px double #999999",
2549         zIndex:   3,
2550         backgroundColor: "#fff"
2551     }).appendTo('#GnuBook');
2552
2553     htmlStr =  '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2554     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>';
2555     htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2556     htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';    
2557
2558     this.embedPopup.innerHTML = htmlStr;
2559     $(this.embedPopup).find('input').bind('click', function() {
2560         this.select();
2561     })
2562 }
2563
2564 // autoToggle()
2565 //______________________________________________________________________________
2566 GnuBook.prototype.autoToggle = function() {
2567
2568     var bComingFrom1up = false;
2569     if (2 != this.mode) {
2570         bComingFrom1up = true;
2571         this.switchMode(2);
2572     }
2573     
2574     // Change to autofit if book is too large
2575     if (this.reduce < this.twoPageGetAutofitReduce()) {
2576         this.zoom2up(0);
2577     }
2578
2579     var self = this;
2580     if (null == this.autoTimer) {
2581         this.flipSpeed = 2000;
2582         
2583         // $$$ Draw events currently cause layout problems when they occur during animation.
2584         //     There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2585         //     we workaround for now by not triggering immediate animation in that case.
2586         //     See https://bugs.launchpad.net/gnubook/+bug/328327
2587         if (('rl' == this.pageProgression) && bComingFrom1up) {
2588             // don't flip immediately -- wait until timer fires
2589         } else {
2590             // flip immediately
2591             this.flipFwdToIndex();        
2592         }
2593
2594         $('#GBtoolbar .play').hide();
2595         $('#GBtoolbar .pause').show();
2596         this.autoTimer=setInterval(function(){
2597             if (self.animating) {return;}
2598             
2599             if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2600                 self.flipBackToIndex(1); // $$$ really what we want?
2601             } else {            
2602                 self.flipFwdToIndex();
2603             }
2604         },5000);
2605     } else {
2606         this.autoStop();
2607     }
2608 }
2609
2610 // autoStop()
2611 //______________________________________________________________________________
2612 // Stop autoplay mode, allowing animations to finish
2613 GnuBook.prototype.autoStop = function() {
2614     if (null != this.autoTimer) {
2615         clearInterval(this.autoTimer);
2616         this.flipSpeed = 'fast';
2617         $('#GBtoolbar .pause').hide();
2618         $('#GBtoolbar .play').show();
2619         this.autoTimer = null;
2620     }
2621 }
2622
2623 // stopFlipAnimations
2624 //______________________________________________________________________________
2625 // Immediately stop flip animations.  Callbacks are triggered.
2626 GnuBook.prototype.stopFlipAnimations = function() {
2627
2628     this.autoStop(); // Clear timers
2629
2630     // Stop animation, clear queue, trigger callbacks
2631     if (this.leafEdgeTmp) {
2632         $(this.leafEdgeTmp).stop(false, true);
2633     }
2634     jQuery.each(this.prefetchedImgs, function() {
2635         $(this).stop(false, true);
2636         });
2637
2638     // And again since animations also queued in callbacks
2639     if (this.leafEdgeTmp) {
2640         $(this.leafEdgeTmp).stop(false, true);
2641     }
2642     jQuery.each(this.prefetchedImgs, function() {
2643         $(this).stop(false, true);
2644         });
2645    
2646 }
2647
2648 // keyboardNavigationIsDisabled(event)
2649 //   - returns true if keyboard navigation should be disabled for the event
2650 //______________________________________________________________________________
2651 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2652     if (event.target.tagName == "INPUT") {
2653         return true;
2654     }   
2655     return false;
2656 }
2657
2658 // gutterOffsetForIndex
2659 //______________________________________________________________________________
2660 //
2661 // Returns the gutter offset for the spread containing the given index.
2662 // This function supports RTL
2663 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2664
2665     // To find the offset of the gutter from the middle we calculate our percentage distance
2666     // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2667     var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2668     
2669     // But then again for RTL it's the opposite
2670     if ('rl' == this.pageProgression) {
2671         offset = -offset;
2672     }
2673     
2674     return offset;
2675 }
2676
2677 // leafEdgeWidth
2678 //______________________________________________________________________________
2679 // Returns the width of the leaf edge div for the page with index given
2680 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2681     // $$$ could there be single pixel rounding errors for L vs R?
2682     if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2683         return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2684     } else {
2685         return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2686     }
2687 }
2688
2689 // jumpIndexForLeftEdgePageX
2690 //______________________________________________________________________________
2691 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2692 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2693     if ('rl' != this.pageProgression) {
2694         // LTR - flipping backward
2695         var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2696
2697         // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570        
2698         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2699         return jumpIndex;
2700
2701     } else {
2702         var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2703         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2704         return jumpIndex;
2705     }
2706 }
2707
2708 // jumpIndexForRightEdgePageX
2709 //______________________________________________________________________________
2710 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2711 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2712     if ('rl' != this.pageProgression) {
2713         // LTR
2714         var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2715         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2716         return jumpIndex;
2717     } else {
2718         var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2719         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2720         return jumpIndex;
2721     }
2722 }
2723
2724 GnuBook.prototype.initToolbar = function(mode, ui) {
2725
2726     $("#GnuBook").append("<div id='GBtoolbar'>"
2727         + "<span id='GBtoolbarbuttons' style='float: right'>"
2728         +   "<button class='GBicon print rollover' /> <button class='GBicon rollover embed' />"
2729         +   "<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>"
2730         +   "<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>"
2731         +   "<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>"
2732         +   "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' />"
2733         + "</span>"
2734         
2735         + "<span>"
2736         +   "<a class='GBicon logo rollover' href='" + this.logoURL + "'>&nbsp;</a>"
2737         +   " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>" 
2738         +   "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2739         +   " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2740         +   " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2741         +   " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2742         + "</span>"
2743         
2744         + "<span id='#GBbooktitle'>"
2745         +   "&nbsp;&nbsp;<a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
2746         + "</span>"
2747         + "</div>");
2748     
2749     this.updateToolbarZoom(this.reduce); // Pretty format
2750         
2751     if (ui == "embed") {
2752         $("#GnuBook a.logo").attr("target","_blank");
2753     }
2754
2755     // $$$ turn this into a member variable
2756     var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2757     
2758     // We build in mode 2
2759     jToolbar.append();
2760
2761     this.bindToolbarNavHandlers(jToolbar);
2762     
2763     // Setup tooltips -- later we could load these from a file for i18n
2764     var titles = { '.logo': 'Go to Archive.org',
2765                    '.zoom_in': 'Zoom in',
2766                    '.zoom_out': 'Zoom out',
2767                    '.one_page_mode': 'One-page view',
2768                    '.two_page_mode': 'Two-page view',
2769                    '.print': 'Print this page',
2770                    '.embed': 'Embed bookreader',
2771                    '.book_left': 'Flip left',
2772                    '.book_right': 'Flip right',
2773                    '.book_up': 'Page up',
2774                    '.book_down': 'Page down',
2775                    '.play': 'Play',
2776                    '.pause': 'Pause',
2777                    '.book_top': 'First page',
2778                    '.book_bottom': 'Last page'
2779                   };
2780     if ('rl' == this.pageProgression) {
2781         titles['.book_leftmost'] = 'Last page';
2782         titles['.book_rightmost'] = 'First page';
2783     } else { // LTR
2784         titles['.book_leftmost'] = 'First page';
2785         titles['.book_rightmost'] = 'Last page';
2786     }
2787                   
2788     for (var icon in titles) {
2789         jToolbar.find(icon).attr('title', titles[icon]);
2790     }
2791     
2792     // Hide mode buttons and autoplay if 2up is not available
2793     // $$$ if we end up with more than two modes we should show the applicable buttons
2794     if ( !this.canSwitchToMode(this.constMode2up) ) {
2795         jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2796     }
2797
2798     // Switch to requested mode -- binds other click handlers
2799     this.switchToolbarMode(mode);
2800
2801 }
2802
2803
2804 // switchToolbarMode
2805 //______________________________________________________________________________
2806 // Update the toolbar for the given mode (changes navigation buttons)
2807 // $$$ we should soon split the toolbar out into its own module
2808 GnuBook.prototype.switchToolbarMode = function(mode) {
2809     if (1 == mode) {
2810         // 1-up     
2811         $('#GBtoolbar .GBtoolbarmode2').hide();
2812         $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2813     } else {
2814         // 2-up
2815         $('#GBtoolbar .GBtoolbarmode1').hide();
2816         $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2817     }
2818 }
2819
2820 // bindToolbarNavHandlers
2821 //______________________________________________________________________________
2822 // Binds the toolbar handlers
2823 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2824
2825     jToolbar.find('.book_left').bind('click', function(e) {
2826         gb.left();
2827         return false;
2828     });
2829          
2830     jToolbar.find('.book_right').bind('click', function(e) {
2831         gb.right();
2832         return false;
2833     });
2834         
2835     jToolbar.find('.book_up').bind('click', function(e) {
2836         gb.prev();
2837         return false;
2838     });        
2839         
2840     jToolbar.find('.book_down').bind('click', function(e) {
2841         gb.next();
2842         return false;
2843     });
2844
2845     jToolbar.find('.print').bind('click', function(e) {
2846         gb.printPage();
2847         return false;
2848     });
2849         
2850     jToolbar.find('.embed').bind('click', function(e) {
2851         gb.showEmbedCode();
2852         return false;
2853     });
2854
2855     jToolbar.find('.play').bind('click', function(e) {
2856         gb.autoToggle();
2857         return false;
2858     });
2859
2860     jToolbar.find('.pause').bind('click', function(e) {
2861         gb.autoToggle();
2862         return false;
2863     });
2864     
2865     jToolbar.find('.book_top').bind('click', function(e) {
2866         gb.first();
2867         return false;
2868     });
2869
2870     jToolbar.find('.book_bottom').bind('click', function(e) {
2871         gb.last();
2872         return false;
2873     });
2874     
2875     jToolbar.find('.book_leftmost').bind('click', function(e) {
2876         gb.leftmost();
2877         return false;
2878     });
2879   
2880     jToolbar.find('.book_rightmost').bind('click', function(e) {
2881         gb.rightmost();
2882         return false;
2883     });
2884 }
2885
2886 // updateToolbarZoom(reduce)
2887 //______________________________________________________________________________
2888 // Update the displayed zoom factor based on reduction factor
2889 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2890     var value;
2891     if (this.constMode2up == this.mode && this.twoPage.autofit) {
2892         value = 'Auto';
2893     } else {
2894         value = (100 / reduce).toFixed(2);
2895         // Strip trailing zeroes and decimal if all zeroes
2896         value = value.replace(/0+$/,'');
2897         value = value.replace(/\.$/,'');
2898         value += '%';
2899     }
2900     $('#GBzoom').text(value);
2901 }
2902
2903 // firstDisplayableIndex
2904 //______________________________________________________________________________
2905 // Returns the index of the first visible page, dependent on the mode.
2906 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2907 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2908 GnuBook.prototype.firstDisplayableIndex = function() {
2909     if (this.mode == 0) {
2910         return 0;
2911     } else {
2912         return 1; // $$$ we assume there are enough pages... we need logic for very short books
2913     }
2914 }
2915
2916 // lastDisplayableIndex
2917 //______________________________________________________________________________
2918 // Returns the index of the last visible page, dependent on the mode.
2919 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2920 // this function when we can as pa  rt of https://bugs.launchpad.net/gnubook/+bug/296788
2921 GnuBook.prototype.lastDisplayableIndex = function() {
2922     if (this.mode == 2) {
2923         if (this.lastDisplayableIndex2up === null) {
2924             // Calculate and cache
2925             var candidate = this.numLeafs - 1;
2926             for ( ; candidate >= 0; candidate--) {
2927                 var spreadIndices = this.getSpreadIndices(candidate);
2928                 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2929                     break;
2930                 }
2931             }
2932             this.lastDisplayableIndex2up = candidate;
2933         }
2934         return this.lastDisplayableIndex2up;
2935     } else {
2936         return this.numLeafs - 1;
2937     }
2938 }
2939
2940 // shortTitle(maximumCharacters)
2941 //________
2942 // Returns a shortened version of the title with the maximum number of characters
2943 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2944     if (this.bookTitle.length < maximumCharacters) {
2945         return this.bookTitle;
2946     }
2947     
2948     var title = this.bookTitle.substr(0, maximumCharacters - 3);
2949     title += '...';
2950     return title;
2951 }
2952
2953 // Parameter related functions
2954
2955 // updateFromParams(params)
2956 //________
2957 // Update ourselves from the params object.
2958 //
2959 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2960 GnuBook.prototype.updateFromParams = function(params) {
2961     if ('undefined' != typeof(params.mode)) {
2962         this.switchMode(params.mode);
2963     }
2964
2965     // process /search
2966     if ('undefined' != typeof(params.searchTerm)) {
2967         this.search(params.searchTerm);
2968     }
2969     
2970     // $$$ process /zoom
2971     
2972     // We only respect page if index is not set
2973     if ('undefined' != typeof(params.index)) {
2974         if (params.index != this.currentIndex()) {
2975             this.jumpToIndex(params.index);
2976         }
2977     } else if ('undefined' != typeof(params.page)) {
2978         // $$$ this assumes page numbers are unique
2979         if (params.page != this.getPageNum(this.currentIndex())) {
2980             this.jumpToPage(params.page);
2981         }
2982     }
2983     
2984     // $$$ process /region
2985     // $$$ process /highlight
2986 }
2987
2988 // paramsFromFragment(urlFragment)
2989 //________
2990 // Returns a object with configuration parametes from a URL fragment.
2991 //
2992 // E.g paramsFromFragment(window.location.hash)
2993 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2994     // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2995     
2996     var params = {};
2997     
2998     // For convenience we allow an initial # character (as from window.location.hash)
2999     // but don't require it
3000     if (urlFragment.substr(0,1) == '#') {
3001         urlFragment = urlFragment.substr(1);
3002     }
3003     
3004     // Simple #nn syntax
3005     var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3006     if ( !isNaN(oldStyleLeafNum) ) {
3007         params.index = oldStyleLeafNum;
3008         
3009         // Done processing if using old-style syntax
3010         return params;
3011     }
3012     
3013     // Split into key-value pairs
3014     var urlArray = urlFragment.split('/');
3015     var urlHash = {};
3016     for (var i = 0; i < urlArray.length; i += 2) {
3017         urlHash[urlArray[i]] = urlArray[i+1];
3018     }
3019     
3020     // Mode
3021     if ('1up' == urlHash['mode']) {
3022         params.mode = this.constMode1up;
3023     } else if ('2up' == urlHash['mode']) {
3024         params.mode = this.constMode2up;
3025     }
3026     
3027     // Index and page
3028     if ('undefined' != typeof(urlHash['page'])) {
3029         // page was set -- may not be int
3030         params.page = urlHash['page'];
3031     }
3032     
3033     // $$$ process /region
3034     // $$$ process /search
3035     
3036     if (urlHash['search'] != undefined) {
3037         params.searchTerm = GnuBook.util.decodeURIComponentPlus(urlHash['search']);
3038     }
3039     
3040     // $$$ process /highlight
3041         
3042     return params;
3043 }
3044
3045 // paramsFromCurrent()
3046 //________
3047 // Create a params object from the current parameters.
3048 GnuBook.prototype.paramsFromCurrent = function() {
3049
3050     var params = {};
3051
3052     var pageNum = this.getPageNum(this.currentIndex());
3053     if ((pageNum === 0) || pageNum) {
3054         params.page = pageNum;
3055     }
3056     
3057     params.index = this.currentIndex();
3058     params.mode = this.mode;
3059     
3060     // $$$ highlight
3061     // $$$ region
3062
3063     // search    
3064     if (this.searchHighlightVisible()) {
3065         params.searchTerm = this.searchTerm;
3066     }
3067     
3068     return params;
3069 }
3070
3071 // fragmentFromParams(params)
3072 //________
3073 // Create a fragment string from the params object.
3074 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3075 GnuBook.prototype.fragmentFromParams = function(params) {
3076     var separator = '/';
3077     
3078     var fragments = [];
3079     
3080     if ('undefined' != typeof(params.page)) {
3081         fragments.push('page', params.page);
3082     } else {
3083         // Don't have page numbering -- use index instead
3084         fragments.push('page', 'n' + params.index);
3085     }
3086     
3087     // $$$ highlight
3088     // $$$ region
3089     
3090     // mode
3091     if ('undefined' != typeof(params.mode)) {    
3092         if (params.mode == this.constMode1up) {
3093             fragments.push('mode', '1up');
3094         } else if (params.mode == this.constMode2up) {
3095             fragments.push('mode', '2up');
3096         } else {
3097             throw 'fragmentFromParams called with unknown mode ' + params.mode;
3098         }
3099     }
3100     
3101     // search
3102     if (params.searchTerm) {
3103         fragments.push('search', params.searchTerm);
3104     }
3105     
3106     return GnuBook.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3107 }
3108
3109 // getPageIndex(pageNum)
3110 //________
3111 // Returns the *highest* index the given page number, or undefined
3112 GnuBook.prototype.getPageIndex = function(pageNum) {
3113     var pageIndices = this.getPageIndices(pageNum);
3114     
3115     if (pageIndices.length > 0) {
3116         return pageIndices[pageIndices.length - 1];
3117     }
3118
3119     return undefined;
3120 }
3121
3122 // getPageIndices(pageNum)
3123 //________
3124 // Returns an array (possibly empty) of the indices with the given page number
3125 GnuBook.prototype.getPageIndices = function(pageNum) {
3126     var indices = [];
3127
3128     // Check for special "nXX" page number
3129     if (pageNum.slice(0,1) == 'n') {
3130         try {
3131             var pageIntStr = pageNum.slice(1, pageNum.length);
3132             var pageIndex = parseInt(pageIntStr);
3133             indices.push(pageIndex);
3134             return indices;
3135         } catch(err) {
3136             // Do nothing... will run through page names and see if one matches
3137         }
3138     }
3139
3140     var i;
3141     for (i=0; i<this.numLeafs; i++) {
3142         if (this.getPageNum(i) == pageNum) {
3143             indices.push(i);
3144         }
3145     }
3146     
3147     return indices;
3148 }
3149
3150 // getPageName(index)
3151 //________
3152 // Returns the name of the page as it should be displayed in the user interface
3153 GnuBook.prototype.getPageName = function(index) {
3154     return 'Page ' + this.getPageNum(index);
3155 }
3156
3157 // updateLocationHash
3158 //________
3159 // Update the location hash from the current parameters.  Call this instead of manually
3160 // using window.location.replace
3161 GnuBook.prototype.updateLocationHash = function() {
3162     var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3163     window.location.replace(newHash);
3164     
3165     // This is the variable checked in the timer.  Only user-generated changes
3166     // to the URL will trigger the event.
3167     this.oldLocationHash = newHash;
3168 }
3169
3170 // startLocationPolling
3171 //________
3172 // Starts polling of window.location to see hash fragment changes
3173 GnuBook.prototype.startLocationPolling = function() {
3174     var self = this; // remember who I am
3175     self.oldLocationHash = window.location.hash;
3176     
3177     if (this.locationPollId) {
3178         clearInterval(this.locationPollID);
3179         this.locationPollId = null;
3180     }
3181     
3182     this.locationPollId = setInterval(function() {
3183         var newHash = window.location.hash;
3184         if (newHash != self.oldLocationHash) {
3185             if (newHash != self.oldUserHash) { // Only process new user hash once
3186                 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3187                 
3188                 // Queue change if animating
3189                 if (self.animating) {
3190                     self.autoStop();
3191                     self.animationFinishedCallback = function() {
3192                         self.updateFromParams(self.paramsFromFragment(newHash));
3193                     }                        
3194                 } else { // update immediately
3195                     self.updateFromParams(self.paramsFromFragment(newHash));
3196                 }
3197                 self.oldUserHash = newHash;
3198             }
3199         }
3200     }, 500);
3201 }
3202
3203 // canSwitchToMode
3204 //________
3205 // Returns true if we can switch to the requested mode
3206 GnuBook.prototype.canSwitchToMode = function(mode) {
3207     if (mode == this.constMode2up) {
3208         // check there are enough pages to display
3209         // $$$ this is a workaround for the mis-feature that we can't display
3210         //     short books in 2up mode
3211         if (this.numLeafs < 6) {
3212             return false;
3213         }
3214     }
3215     
3216     return true;
3217 }
3218
3219 // searchHighlightVisible
3220 //________
3221 // Returns true if a search highlight is currently being displayed
3222 GnuBook.prototype.searchHighlightVisible = function() {
3223     if (this.constMode2up == this.mode) {
3224         if (this.searchResults[this.twoPage.currentIndexL]
3225                 || this.searchResults[this.twoPage.currentIndexR]) {
3226             return true;
3227         }
3228     } else { // 1up
3229         if (this.searchResults[this.currentIndex()]) {
3230             return true;
3231         }
3232     }
3233     return false;
3234 }
3235
3236 // Library functions
3237 GnuBook.util = {
3238     clamp: function(value, min, max) {
3239         return Math.min(Math.max(value, min), max);
3240     },
3241
3242     getIFrameDocument: function(iframe) {
3243         // Adapted from http://xkr.us/articles/dom/iframe-document/
3244         var outer = (iframe.contentWindow || iframe.contentDocument);
3245         return (outer.document || outer);
3246     },
3247     
3248     decodeURIComponentPlus: function(value) {
3249         // Decodes a URI component and converts '+' to ' '
3250         return decodeURIComponent(value).replace(/\+/g, ' ');
3251     },
3252     
3253     encodeURIComponentPlus: function(value) {
3254         // Encodes a URI component and converts ' ' to '+'
3255         return encodeURIComponent(value).replace(/%20/g, '+');
3256     },
3257 }