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