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