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