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