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