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