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