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