Resolve conflicts with upstream repository
[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
45     this.displayedIndices = []; 
46         this.displayedRows=[];
47     //this.indicesToDisplay = [];
48     this.imgs = {};
49     this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
50     
51     this.timer     = null;
52     this.animating = false;
53     this.auto      = false;
54     this.autoTimer = null;
55     this.flipSpeed = 'fast';
56
57     this.twoPagePopUp = null;
58     this.leafEdgeTmp  = null;
59     this.embedPopup = null;
60     this.printPopup = null;
61     
62     this.searchTerm = '';
63     this.searchResults = {};
64     
65     this.firstIndex = null;
66     
67     this.lastDisplayableIndex2up = null;
68     
69     // We link to index.php to avoid redirect which breaks back button
70     this.logoURL = 'http://www.archive.org/index.php';
71     
72     // Base URL for images
73     this.imagesBaseURL = '/bookreader/images/';
74     
75     // Mode constants
76     this.constMode1up = 1;
77     this.constMode2up = 2;
78     this.constModeThumb = 3;
79     
80     // Zoom levels
81     this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
82
83     // Object to hold parameters related to 2up mode
84     this.twoPage = {
85         coverInternalPadding: 10, // Width of cover
86         coverExternalPadding: 10, // Padding outside of cover
87         bookSpineDivWidth: 30,    // Width of book spine  $$$ consider sizing based on book length
88         autofit: true
89     };
90     
91     // Background color for pages (e.g. when loading page image)
92     // $$$ TODO dynamically calculate based on page images
93     this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
94 };
95
96 // init()
97 //______________________________________________________________________________
98 GnuBook.prototype.init = function() {
99
100     var startIndex = undefined;
101         this.pageScale = this.reduce; // preserve current reduce
102     
103     // Find start index and mode if set in location hash
104     var params = this.paramsFromFragment(window.location.hash);
105         
106     if ('undefined' != typeof(params.index)) {
107         startIndex = params.index;
108     } else if ('undefined' != typeof(params.page)) {
109         startIndex = this.getPageIndex(params.page);
110     }
111     
112     if ('undefined' == typeof(startIndex)) {
113         if ('undefined' != typeof(this.titleLeaf)) {
114             startIndex = this.leafNumToIndex(this.titleLeaf);
115         }
116     }
117     
118     if ('undefined' == typeof(startIndex)) {
119         startIndex = 0;
120     }
121     
122     if ('undefined' != typeof(params.mode)) {
123         this.mode = params.mode;
124     }
125     
126     // Set document title -- may have already been set in enclosing html for
127     // search engine visibility
128     document.title = this.shortTitle(50);
129     
130     // Sanitize parameters
131     if ( !this.canSwitchToMode( this.mode ) ) {
132         this.mode = this.constMode1up;
133     }
134     
135     $("#GnuBook").empty();
136     this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
137     $("#GnuBook").append("<div id='GBcontainer'></div>");
138     $("#GBcontainer").append("<div id='GBpageview'></div>");
139
140     $("#GBcontainer").bind('scroll', this, function(e) {
141         e.data.loadLeafs();
142     });
143
144     this.setupKeyListeners();
145     this.startLocationPolling();
146
147     $(window).bind('resize', this, function(e) {
148         //console.log('resize!');
149         if (1 == e.data.mode) {
150             //console.log('centering 1page view');
151             e.data.centerPageView();
152             $('#GBpageview').empty()
153             e.data.displayedIndices = [];
154             e.data.updateSearchHilites(); //deletes hilights but does not call remove()            
155             e.data.loadLeafs();
156                 } else if (3 == e.data.mode){
157                         e.data.prepareThumbnailView();
158         } else {
159             //console.log('drawing 2 page view');
160             
161             // We only need to prepare again in autofit (size of spread changes)
162             if (e.data.twoPage.autofit) {
163                 e.data.prepareTwoPageView();
164             } else {
165                 // Re-center if the scrollbars have disappeared
166                 var center = e.data.twoPageGetViewCenter();
167                 var doRecenter = false;
168                 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
169                     center.percentageX = 0.5;
170                     doRecenter = true;
171                 }
172                 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
173                     center.percentageY = 0.5;
174                     doRecenter = true;
175                 }
176                 if (doRecenter) {
177                     e.data.twoPageCenterView(center.percentageX, center.percentageY);
178                 }
179             }
180         }
181     });
182     
183     $('.GBpagediv1up').bind('mousedown', this, function(e) {
184         // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
185         //     but this also interferes with right-click.  See https://bugs.edge.launchpad.net/gnubook/+bug/362626
186     });
187
188     if (1 == this.mode) {
189         this.resizePageView();
190         this.firstIndex = startIndex;
191         this.jumpToIndex(startIndex);
192     } else if (3 == this.mode) {
193                 this.firstIndex = startIndex;
194                 this.prepareThumbnailView();
195                 this.jumpToIndex(startIndex);
196         } else {
197         //this.resizePageView();
198         
199         this.displayedIndices=[0];
200         this.firstIndex = startIndex;
201         this.displayedIndices = [this.firstIndex];
202         //console.log('titleLeaf: %d', this.titleLeaf);
203         //console.log('displayedIndices: %s', this.displayedIndices);
204         this.prepareTwoPageView();
205     }
206         
207     // Enact other parts of initial params
208     this.updateFromParams(params);
209 }
210
211 GnuBook.prototype.setupKeyListeners = function() {
212     var self = this;
213     
214     var KEY_PGUP = 33;
215     var KEY_PGDOWN = 34;
216     var KEY_END = 35;
217     var KEY_HOME = 36;
218
219     var KEY_LEFT = 37;
220     var KEY_UP = 38;
221     var KEY_RIGHT = 39;
222     var KEY_DOWN = 40;
223
224     // We use document here instead of window to avoid a bug in jQuery on IE7
225     $(document).keydown(function(e) {
226     
227         // Keyboard navigation        
228         if (!self.keyboardNavigationIsDisabled(e)) {
229             switch(e.keyCode) {
230                 case KEY_PGUP:
231                 case KEY_UP:            
232                     // In 1up mode page scrolling is handled by browser
233                     if (2 == self.mode) {
234                         e.preventDefault();
235                         self.prev();
236                     }
237                     break;
238                 case KEY_DOWN:
239                 case KEY_PGDOWN:
240                     if (2 == self.mode) {
241                         e.preventDefault();
242                         self.next();
243                     }
244                     break;
245                 case KEY_END:
246                     e.preventDefault();
247                     self.last();
248                     break;
249                 case KEY_HOME:
250                     e.preventDefault();
251                     self.first();
252                     break;
253                 case KEY_LEFT:
254                     if (2 == self.mode) {
255                         e.preventDefault();
256                         self.left();
257                     }
258                     break;
259                 case KEY_RIGHT:
260                     if (2 == self.mode) {
261                         e.preventDefault();
262                         self.right();
263                     }
264                     break;
265             }
266         }
267     });
268 }
269
270 // drawLeafs()
271 //______________________________________________________________________________
272 GnuBook.prototype.drawLeafs = function() {
273     if (1 == this.mode) {
274         this.drawLeafsOnePage();
275         } else if(3 == this.mode) {
276                 this.drawLeafsThumbnail();
277     } else {
278         this.drawLeafsTwoPage();
279     }
280 }
281
282 // setDragHandler()
283 //______________________________________________________________________________
284 GnuBook.prototype.setDragHandler = function(div) {
285     div.dragging = false;
286
287     $(div).unbind('mousedown').bind('mousedown', function(e) {
288         e.preventDefault();
289         
290         //console.log('mousedown at ' + e.pageY);
291
292         this.dragging = true;
293         this.prevMouseX = e.pageX;
294         this.prevMouseY = e.pageY;
295     
296         var startX    = e.pageX;
297         var startY    = e.pageY;
298         var startTop  = $('#GBcontainer').attr('scrollTop');
299         var startLeft =  $('#GBcontainer').attr('scrollLeft');
300
301     });
302         
303     $(div).unbind('mousemove').bind('mousemove', function(ee) {
304         ee.preventDefault();
305
306         // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
307         
308         var offsetX = ee.pageX - this.prevMouseX;
309         var offsetY = ee.pageY - this.prevMouseY;
310         
311         if (this.dragging) {
312             $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
313             $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
314         }
315         
316         this.prevMouseX = ee.pageX;
317         this.prevMouseY = ee.pageY;
318         
319     });
320     
321     $(div).unbind('mouseup').bind('mouseup', function(ee) {
322         ee.preventDefault();
323         //console.log('mouseup');
324
325         this.dragging = false;
326     });
327     
328     $(div).unbind('mouseleave').bind('mouseleave', function(e) {
329         e.preventDefault();
330         //console.log('mouseleave');
331
332         this.dragging = false;        
333     });
334     
335     $(div).unbind('mouseenter').bind('mouseenter', function(e) {
336         e.preventDefault();
337         //console.log('mouseenter');
338         
339         this.dragging = false;
340     });
341 }
342
343 // setDragHandler2UP()
344 //______________________________________________________________________________
345 GnuBook.prototype.setDragHandler2UP = function(div) {
346     div.dragging = false;
347     
348     $(div).unbind('mousedown').bind('mousedown', function(e) {
349         e.preventDefault();
350         
351         //console.log('mousedown at ' + e.pageY);
352
353         this.dragStart = {x: e.pageX, y: e.pageY };
354         this.mouseDown = true;
355         this.dragging = false; // wait until drag distance
356         this.prevMouseX = e.pageX;
357         this.prevMouseY = e.pageY;
358     
359         var startX    = e.pageX;
360         var startY    = e.pageY;
361         var startTop  = $('#GBcontainer').attr('scrollTop');
362         var startLeft =  $('#GBcontainer').attr('scrollLeft');
363
364     });
365         
366     $(div).unbind('mousemove').bind('mousemove', function(ee) {
367         ee.preventDefault();
368
369         // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
370         
371         var offsetX = ee.pageX - this.prevMouseX;
372         var offsetY = ee.pageY - this.prevMouseY;
373         
374         var minDragDistance = 5; // $$$ constant
375
376         var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
377                 
378         if (this.mouseDown && (distance > minDragDistance)) {
379             //console.log('drag start!');
380             
381             this.dragging = true;
382         }
383         
384         if (this.dragging) {        
385             $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
386             $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
387             this.prevMouseX = ee.pageX;
388             this.prevMouseY = ee.pageY;
389         }
390         
391         
392     });
393     
394     /*
395     $(div).unbind('mouseup').bind('mouseup', function(ee) {
396         ee.preventDefault();
397         //console.log('mouseup');
398
399         this.dragging = false;
400         this.mouseDown = false;
401     });
402     */
403     
404     
405     $(div).unbind('mouseleave').bind('mouseleave', function(e) {
406         e.preventDefault();
407         //console.log('mouseleave');
408
409         this.dragging = false;  
410         this.mouseDown = false;
411     });
412     
413     $(div).unbind('mouseenter').bind('mouseenter', function(e) {
414         e.preventDefault();
415         //console.log('mouseenter');
416         
417         this.dragging = false;
418         this.mouseDown = false;
419     });
420 }
421
422 GnuBook.prototype.setClickHandler2UP = function( element, data, handler) {
423     //console.log('setting handler');
424     //console.log(element.tagName);
425     
426     $(element).unbind('click').bind('click', data, function(e) {
427         e.preventDefault();
428         
429         //console.log('click!');
430         
431         if (this.mouseDown && (!this.dragging)) {
432             //console.log('click not dragging!');
433             handler(e);
434         }
435         
436         this.dragging = false;
437         this.mouseDown = false;
438     });
439 }
440
441 // drawLeafsOnePage()
442 //______________________________________________________________________________
443 GnuBook.prototype.drawLeafsOnePage = function() {
444     //alert('drawing leafs!');
445     this.timer = null;
446
447
448     var scrollTop = $('#GBcontainer').attr('scrollTop');
449     var scrollBottom = scrollTop + $('#GBcontainer').height();
450     //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
451     
452     var indicesToDisplay = [];
453     
454     var i;
455     var leafTop = 0;
456     var leafBottom = 0;
457     for (i=0; i<this.numLeafs; i++) {
458         var height  = parseInt(this._getPageHeight(i)/this.reduce); 
459     
460         leafBottom += height;
461         //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
462         var topInView    = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
463         var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
464         var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
465         if (topInView | bottomInView | middleInView) {
466             //console.log('displayed: ' + this.displayedIndices);
467             //console.log('to display: ' + i);
468             indicesToDisplay.push(i);
469         }
470         leafTop += height +10;      
471         leafBottom += 10;
472     }
473
474     var firstIndexToDraw  = indicesToDisplay[0];
475     this.firstIndex      = firstIndexToDraw;
476     
477     // Update hash, but only if we're currently displaying a leaf
478     // Hack that fixes #365790
479     if (this.displayedIndices.length > 0) {
480         this.updateLocationHash();
481     }
482
483     if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
484         firstIndexToDraw--;
485         indicesToDisplay.unshift(firstIndexToDraw);
486     }
487     
488     var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
489     if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
490         indicesToDisplay.push(lastIndexToDraw+1);
491     }
492     
493     leafTop = 0;
494     var i;
495     for (i=0; i<firstIndexToDraw; i++) {
496         leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
497     }
498
499     //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
500     var viewWidth = $('#GBcontainer').attr('scrollWidth');
501
502
503     for (i=0; i<indicesToDisplay.length; i++) {
504         var index = indicesToDisplay[i];    
505         var height  = parseInt(this._getPageHeight(index)/this.reduce); 
506
507         if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {            
508             var width   = parseInt(this._getPageWidth(index)/this.reduce); 
509             //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
510             var div = document.createElement("div");
511             div.className = 'GBpagediv1up';
512             div.id = 'pagediv'+index;
513             div.style.position = "absolute";
514             $(div).css('top', leafTop + 'px');
515             var left = (viewWidth-width)>>1;
516             if (left<0) left = 0;
517             $(div).css('left', left+'px');
518             $(div).css('width', width+'px');
519             $(div).css('height', height+'px');
520             //$(div).text('loading...');
521             
522             this.setDragHandler(div);
523             
524             $('#GBpageview').append(div);
525
526             var img = document.createElement("img");
527             img.src = this._getPageURI(index, this.reduce, 0);
528             $(img).css('width', width+'px');
529             $(img).css('height', height+'px');
530             $(div).append(img);
531
532         } else {
533             //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));            
534         }
535
536         leafTop += height +10;
537
538     }
539     
540     for (i=0; i<this.displayedIndices.length; i++) {
541         if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
542             var index = this.displayedIndices[i];
543             //console.log('Removing leaf ' + index);
544             //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
545             $('#pagediv'+index).remove();
546         } else {
547             //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
548         }
549     }
550     
551     this.displayedIndices = indicesToDisplay.slice();
552     this.updateSearchHilites();
553     
554     if (null != this.getPageNum(firstIndexToDraw))  {
555         $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
556     } else {
557         $("#GBpagenum").val('');
558     }
559             
560     this.updateToolbarZoom(this.reduce);
561     
562 }
563
564 // drawLeafsThumbnail()
565 //______________________________________________________________________________
566 GnuBook.prototype.drawLeafsThumbnail = function() {
567     //alert('drawing leafs!');
568     this.timer = null;
569
570         var viewWidth = $('#GBcontainer').attr('scrollWidth') - 20; // width minus buffer
571         
572     //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
573
574         var i;
575         var leafWidth;
576         var leafHeight;
577         var rightPos = 0;
578         var bottomPos = 0;
579         var maxRight = 0;
580         var currentRow = 0;
581         var leafIndex = 0;
582         var leafMap = [];
583         
584         for (i=0; i<this.numLeafs; i++) {
585                 leafWidth = parseInt(this.getPageWidth(i)/this.reduce, 10);
586                 if (rightPos + (leafWidth + this.padding) > viewWidth){
587                         currentRow++;
588                         rightPos = 0;
589                         leafIndex = 0;
590                 }
591         
592                 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
593                 if (leafMap[currentRow].leafs===undefined) {
594                         leafMap[currentRow].leafs = [];
595                         leafMap[currentRow].height = 0;
596                         leafMap[currentRow].top = 0;
597                 }
598                 leafMap[currentRow].leafs[leafIndex] = {};
599                 leafMap[currentRow].leafs[leafIndex].num = i;
600                 leafMap[currentRow].leafs[leafIndex].left = rightPos;
601
602                 leafHeight = parseInt(this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)/this.reduce, 10);
603                 if (leafHeight > leafMap[currentRow].height) { leafMap[currentRow].height = leafHeight; }
604                 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
605                 rightPos += leafWidth + this.padding;
606                 if (rightPos > maxRight) { maxRight = rightPos; }
607                 leafIndex++;
608         }
609         
610         // reset the bottom position based on thumbnails
611         $('#GBpageview').height(bottomPos);
612         
613         var pageViewBuffer = Math.floor(($('#GBcontainer').attr('scrollWidth') - maxRight) / 2) - 14;   
614         var scrollTop = $('#GBcontainer').attr('scrollTop');
615     var scrollBottom = scrollTop + $('#GBcontainer').height();
616
617         var leafTop = 0;
618         var leafBottom = 0;
619         var rowsToDisplay = [];
620
621     for (i=0; i<leafMap.length; i++) {
622                 leafBottom += this.padding + leafMap[i].height;
623         var topInView    = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
624         var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
625         var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
626         if (topInView | bottomInView | middleInView) {
627             //console.log('row to display: ' + j);
628                         rowsToDisplay.push(i);
629         }
630                 if(leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
631                 leafTop = leafBottom;
632     }
633         
634         var firstRow = rowsToDisplay[0];
635         var lastRow = rowsToDisplay[rowsToDisplay.length-1];
636         var rowBuffer = 4;
637         for (i=1; i<rowBuffer+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                 +       "<button class='GBicon rollover thumbnail_mode' onclick='gb.switchMode(3); return false;'/>"
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         +   " <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>"
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         + "</span>"
3027         
3028         + "<span id='#GBbooktitle'>"
3029         +   "&nbsp;&nbsp;<a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3030         + "</span>"
3031         + "</div>");
3032     
3033     this.updateToolbarZoom(this.reduce); // Pretty format
3034         
3035     if (ui == "embed") {
3036         $("#GnuBook a.logo").attr("target","_blank");
3037     }
3038
3039     // $$$ turn this into a member variable
3040     var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
3041     
3042     // We build in mode 2
3043     jToolbar.append();
3044
3045     this.bindToolbarNavHandlers(jToolbar);
3046     
3047     // Setup tooltips -- later we could load these from a file for i18n
3048     var titles = { '.logo': 'Go to Archive.org',
3049                    '.zoom_in': 'Zoom in',
3050                    '.zoom_out': 'Zoom out',
3051                    '.one_page_mode': 'One-page view',
3052                    '.two_page_mode': 'Two-page view',
3053                                    '.thumbnail_mode': 'Thumbnail view',
3054                    '.print': 'Print this page',
3055                    '.embed': 'Embed bookreader',
3056                    '.book_left': 'Flip left',
3057                    '.book_right': 'Flip right',
3058                    '.book_up': 'Page up',
3059                    '.book_down': 'Page down',
3060                    '.play': 'Play',
3061                    '.pause': 'Pause',
3062                    '.book_top': 'First page',
3063                    '.book_bottom': 'Last page'
3064                   };
3065     if ('rl' == this.pageProgression) {
3066         titles['.book_leftmost'] = 'Last page';
3067         titles['.book_rightmost'] = 'First page';
3068     } else { // LTR
3069         titles['.book_leftmost'] = 'First page';
3070         titles['.book_rightmost'] = 'Last page';
3071     }
3072                   
3073     for (var icon in titles) {
3074         jToolbar.find(icon).attr('title', titles[icon]);
3075     }
3076     
3077     // Hide mode buttons and autoplay if 2up is not available
3078     // $$$ if we end up with more than two modes we should show the applicable buttons
3079     if ( !this.canSwitchToMode(this.constMode2up) ) {
3080         jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3081     }
3082
3083     // Switch to requested mode -- binds other click handlers
3084     this.switchToolbarMode(mode);
3085     
3086 }
3087
3088
3089 // switchToolbarMode
3090 //______________________________________________________________________________
3091 // Update the toolbar for the given mode (changes navigation buttons)
3092 // $$$ we should soon split the toolbar out into its own module
3093 GnuBook.prototype.switchToolbarMode = function(mode) {
3094     if (1 == mode) {
3095         // 1-up     
3096         $('#GBtoolbar .GBtoolbarmode2').hide();
3097         $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
3098     } else {
3099         // 2-up
3100         $('#GBtoolbar .GBtoolbarmode1').hide();
3101         $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
3102     }
3103 }
3104
3105 // bindToolbarNavHandlers
3106 //______________________________________________________________________________
3107 // Binds the toolbar handlers
3108 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
3109
3110     jToolbar.find('.book_left').bind('click', function(e) {
3111         gb.left();
3112         return false;
3113     });
3114          
3115     jToolbar.find('.book_right').bind('click', function(e) {
3116         gb.right();
3117         return false;
3118     });
3119         
3120     jToolbar.find('.book_up').bind('click', function(e) {
3121         gb.prev();
3122         return false;
3123     });        
3124         
3125     jToolbar.find('.book_down').bind('click', function(e) {
3126         gb.next();
3127         return false;
3128     });
3129
3130     jToolbar.find('.print').bind('click', function(e) {
3131         gb.printPage();
3132         return false;
3133     });
3134         
3135     jToolbar.find('.embed').bind('click', function(e) {
3136         gb.showEmbedCode();
3137         return false;
3138     });
3139
3140     jToolbar.find('.play').bind('click', function(e) {
3141         gb.autoToggle();
3142         return false;
3143     });
3144
3145     jToolbar.find('.pause').bind('click', function(e) {
3146         gb.autoToggle();
3147         return false;
3148     });
3149     
3150     jToolbar.find('.book_top').bind('click', function(e) {
3151         gb.first();
3152         return false;
3153     });
3154
3155     jToolbar.find('.book_bottom').bind('click', function(e) {
3156         gb.last();
3157         return false;
3158     });
3159     
3160     jToolbar.find('.book_leftmost').bind('click', function(e) {
3161         gb.leftmost();
3162         return false;
3163     });
3164   
3165     jToolbar.find('.book_rightmost').bind('click', function(e) {
3166         gb.rightmost();
3167         return false;
3168     });
3169 }
3170
3171 // updateToolbarZoom(reduce)
3172 //______________________________________________________________________________
3173 // Update the displayed zoom factor based on reduction factor
3174 GnuBook.prototype.updateToolbarZoom = function(reduce) {
3175     var value;
3176     if (this.constMode2up == this.mode && this.twoPage.autofit) {
3177         value = 'Auto';
3178     } else {
3179         value = (100 / reduce).toFixed(2);
3180         // Strip trailing zeroes and decimal if all zeroes
3181         value = value.replace(/0+$/,'');
3182         value = value.replace(/\.$/,'');
3183         value += '%';
3184     }
3185     $('#GBzoom').text(value);
3186 }
3187
3188 // firstDisplayableIndex
3189 //______________________________________________________________________________
3190 // Returns the index of the first visible page, dependent on the mode.
3191 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3192 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3193 GnuBook.prototype.firstDisplayableIndex = function() {
3194     if (this.mode != this.constMode2up) {
3195         return 0;
3196     }
3197     
3198     if ('rl' != this.pageProgression) {
3199         // LTR
3200         if (this.getPageSide(0) == 'L') {
3201             return 0;
3202         } else {
3203             return -1;
3204         }
3205     } else {
3206         // RTL
3207         if (this.getPageSide(0) == 'R') {
3208             return 0;
3209         } else {
3210             return -1;
3211         }
3212     }
3213 }
3214
3215 // lastDisplayableIndex
3216 //______________________________________________________________________________
3217 // Returns the index of the last visible page, dependent on the mode.
3218 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3219 // this function when we can as pa  rt of https://bugs.launchpad.net/gnubook/+bug/296788
3220 GnuBook.prototype.lastDisplayableIndex = function() {
3221
3222     var lastIndex = this.numLeafs - 1;
3223     
3224     if (this.mode != this.constMode2up) {
3225         return lastIndex;
3226     }
3227
3228     if ('rl' != this.pageProgression) {
3229         // LTR
3230         if (this.getPageSide(lastIndex) == 'R') {
3231             return lastIndex;
3232         } else {
3233             return lastIndex + 1;
3234         }
3235     } else {
3236         // RTL
3237         if (this.getPageSide(lastIndex) == 'L') {
3238             return lastIndex;
3239         } else {
3240             return lastIndex + 1;
3241         }
3242     }
3243 }
3244
3245 // shortTitle(maximumCharacters)
3246 //________
3247 // Returns a shortened version of the title with the maximum number of characters
3248 GnuBook.prototype.shortTitle = function(maximumCharacters) {
3249     if (this.bookTitle.length < maximumCharacters) {
3250         return this.bookTitle;
3251     }
3252     
3253     var title = this.bookTitle.substr(0, maximumCharacters - 3);
3254     title += '...';
3255     return title;
3256 }
3257
3258 // Parameter related functions
3259
3260 // updateFromParams(params)
3261 //________
3262 // Update ourselves from the params object.
3263 //
3264 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3265 GnuBook.prototype.updateFromParams = function(params) {
3266     if ('undefined' != typeof(params.mode)) {
3267         this.switchMode(params.mode);
3268     }
3269
3270     // process /search
3271     if ('undefined' != typeof(params.searchTerm)) {
3272         if (this.searchTerm != params.searchTerm) {
3273             this.search(params.searchTerm);
3274         }
3275     }
3276     
3277     // $$$ process /zoom
3278     
3279     // We only respect page if index is not set
3280     if ('undefined' != typeof(params.index)) {
3281         if (params.index != this.currentIndex()) {
3282             this.jumpToIndex(params.index);
3283         }
3284     } else if ('undefined' != typeof(params.page)) {
3285         // $$$ this assumes page numbers are unique
3286         if (params.page != this.getPageNum(this.currentIndex())) {
3287             this.jumpToPage(params.page);
3288         }
3289     }
3290     
3291     // $$$ process /region
3292     // $$$ process /highlight
3293 }
3294
3295 // paramsFromFragment(urlFragment)
3296 //________
3297 // Returns a object with configuration parametes from a URL fragment.
3298 //
3299 // E.g paramsFromFragment(window.location.hash)
3300 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
3301     // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3302
3303     var params = {};
3304     
3305     // For convenience we allow an initial # character (as from window.location.hash)
3306     // but don't require it
3307     if (urlFragment.substr(0,1) == '#') {
3308         urlFragment = urlFragment.substr(1);
3309     }
3310     
3311     // Simple #nn syntax
3312     var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3313     if ( !isNaN(oldStyleLeafNum) ) {
3314         params.index = oldStyleLeafNum;
3315         
3316         // Done processing if using old-style syntax
3317         return params;
3318     }
3319     
3320     // Split into key-value pairs
3321     var urlArray = urlFragment.split('/');
3322     var urlHash = {};
3323     for (var i = 0; i < urlArray.length; i += 2) {
3324         urlHash[urlArray[i]] = urlArray[i+1];
3325     }
3326     
3327     // Mode
3328     if ('1up' == urlHash['mode']) {
3329         params.mode = this.constMode1up;
3330     } else if ('2up' == urlHash['mode']) {
3331         params.mode = this.constMode2up;
3332     } else if ('thumb' == urlHash['mode']) {
3333         params.mode = this.constModeThumb;
3334     }
3335     
3336     // Index and page
3337     if ('undefined' != typeof(urlHash['page'])) {
3338         // page was set -- may not be int
3339         params.page = urlHash['page'];
3340     }
3341     
3342     // $$$ process /region
3343     // $$$ process /search
3344     
3345     if (urlHash['search'] != undefined) {
3346         params.searchTerm = GnuBook.util.decodeURIComponentPlus(urlHash['search']);
3347     }
3348     
3349     // $$$ process /highlight
3350         
3351     return params;
3352 }
3353
3354 // paramsFromCurrent()
3355 //________
3356 // Create a params object from the current parameters.
3357 GnuBook.prototype.paramsFromCurrent = function() {
3358
3359     var params = {};
3360     
3361     var index = this.currentIndex();
3362     var pageNum = this.getPageNum(index);
3363     if ((pageNum === 0) || pageNum) {
3364         params.page = pageNum;
3365     }
3366     
3367     params.index = index;
3368     params.mode = this.mode;
3369     
3370     // $$$ highlight
3371     // $$$ region
3372
3373     // search    
3374     if (this.searchHighlightVisible()) {
3375         params.searchTerm = this.searchTerm;
3376     }
3377     
3378     return params;
3379 }
3380
3381 // fragmentFromParams(params)
3382 //________
3383 // Create a fragment string from the params object.
3384 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3385 GnuBook.prototype.fragmentFromParams = function(params) {
3386     var separator = '/';
3387
3388     var fragments = [];
3389     
3390     if ('undefined' != typeof(params.page)) {
3391         fragments.push('page', params.page);
3392     } else {
3393         // Don't have page numbering -- use index instead
3394         fragments.push('page', 'n' + params.index);
3395     }
3396     
3397     // $$$ highlight
3398     // $$$ region
3399     
3400     // mode
3401     if ('undefined' != typeof(params.mode)) {    
3402         if (params.mode == this.constMode1up) {
3403             fragments.push('mode', '1up');
3404         } else if (params.mode == this.constMode2up) {
3405             fragments.push('mode', '2up');
3406         } else if (params.mode == this.constModeThumb) {
3407             fragments.push('mode', 'thumb');
3408         } else {
3409             throw 'fragmentFromParams called with unknown mode ' + params.mode;
3410         }
3411     }
3412     
3413     // search
3414     if (params.searchTerm) {
3415         fragments.push('search', params.searchTerm);
3416     }
3417     
3418     return GnuBook.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3419 }
3420
3421 // getPageIndex(pageNum)
3422 //________
3423 // Returns the *highest* index the given page number, or undefined
3424 GnuBook.prototype.getPageIndex = function(pageNum) {
3425     var pageIndices = this.getPageIndices(pageNum);
3426     
3427     if (pageIndices.length > 0) {
3428         return pageIndices[pageIndices.length - 1];
3429     }
3430
3431     return undefined;
3432 }
3433
3434 // getPageIndices(pageNum)
3435 //________
3436 // Returns an array (possibly empty) of the indices with the given page number
3437 GnuBook.prototype.getPageIndices = function(pageNum) {
3438     var indices = [];
3439
3440     // Check for special "nXX" page number
3441     if (pageNum.slice(0,1) == 'n') {
3442         try {
3443             var pageIntStr = pageNum.slice(1, pageNum.length);
3444             var pageIndex = parseInt(pageIntStr);
3445             indices.push(pageIndex);
3446             return indices;
3447         } catch(err) {
3448             // Do nothing... will run through page names and see if one matches
3449         }
3450     }
3451
3452     var i;
3453     for (i=0; i<this.numLeafs; i++) {
3454         if (this.getPageNum(i) == pageNum) {
3455             indices.push(i);
3456         }
3457     }
3458     
3459     return indices;
3460 }
3461
3462 // getPageName(index)
3463 //________
3464 // Returns the name of the page as it should be displayed in the user interface
3465 GnuBook.prototype.getPageName = function(index) {
3466     return 'Page ' + this.getPageNum(index);
3467 }
3468
3469 // updateLocationHash
3470 //________
3471 // Update the location hash from the current parameters.  Call this instead of manually
3472 // using window.location.replace
3473 GnuBook.prototype.updateLocationHash = function() {
3474     var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3475     window.location.replace(newHash);
3476     
3477     // This is the variable checked in the timer.  Only user-generated changes
3478     // to the URL will trigger the event.
3479     this.oldLocationHash = newHash;
3480 }
3481
3482 // startLocationPolling
3483 //________
3484 // Starts polling of window.location to see hash fragment changes
3485 GnuBook.prototype.startLocationPolling = function() {
3486     var self = this; // remember who I am
3487     self.oldLocationHash = window.location.hash;
3488     
3489     if (this.locationPollId) {
3490         clearInterval(this.locationPollID);
3491         this.locationPollId = null;
3492     }
3493     
3494     this.locationPollId = setInterval(function() {
3495         var newHash = window.location.hash;
3496         if (newHash != self.oldLocationHash) {
3497             if (newHash != self.oldUserHash) { // Only process new user hash once
3498                 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3499                 
3500                 // Queue change if animating
3501                 if (self.animating) {
3502                     self.autoStop();
3503                     self.animationFinishedCallback = function() {
3504                         self.updateFromParams(self.paramsFromFragment(newHash));
3505                     }                        
3506                 } else { // update immediately
3507                     self.updateFromParams(self.paramsFromFragment(newHash));
3508                 }
3509                 self.oldUserHash = newHash;
3510             }
3511         }
3512     }, 500);
3513 }
3514
3515 // canSwitchToMode
3516 //________
3517 // Returns true if we can switch to the requested mode
3518 GnuBook.prototype.canSwitchToMode = function(mode) {
3519     if (mode == this.constMode2up) {
3520         // check there are enough pages to display
3521         // $$$ this is a workaround for the mis-feature that we can't display
3522         //     short books in 2up mode
3523         if (this.numLeafs < 6) {
3524             return false;
3525         }
3526     }
3527     
3528     return true;
3529 }
3530
3531 // searchHighlightVisible
3532 //________
3533 // Returns true if a search highlight is currently being displayed
3534 GnuBook.prototype.searchHighlightVisible = function() {
3535     if (this.constMode2up == this.mode) {
3536         if (this.searchResults[this.twoPage.currentIndexL]
3537                 || this.searchResults[this.twoPage.currentIndexR]) {
3538             return true;
3539         }
3540     } else { // 1up
3541         if (this.searchResults[this.currentIndex()]) {
3542             return true;
3543         }
3544     }
3545     return false;
3546 }
3547
3548 // getPageBackgroundColor
3549 //--------
3550 // Returns a CSS property string for the background color for the given page
3551 // $$$ turn into regular CSS?
3552 GnuBook.prototype.getPageBackgroundColor = function(index) {
3553     if (index >= 0 && index < this.numLeafs) {
3554         // normal page
3555         return this.pageDefaultBackgroundColor;
3556     }
3557     
3558     return '';
3559 }
3560
3561 // _getPageWidth
3562 //--------
3563 // Returns the page width for the given index, or first or last page if out of range
3564 GnuBook.prototype._getPageWidth = function(index) {
3565     // Synthesize a page width for pages not actually present in book.
3566     // May or may not be the best approach.
3567     // If index is out of range we return the width of first or last page
3568     index = GnuBook.util.clamp(index, 0, this.numLeafs - 1);
3569     return this.getPageWidth(index);
3570 }
3571
3572 // _getPageHeight
3573 //--------
3574 // Returns the page height for the given index, or first or last page if out of range
3575 GnuBook.prototype._getPageHeight= function(index) {
3576     index = GnuBook.util.clamp(index, 0, this.numLeafs - 1);
3577     return this.getPageHeight(index);
3578 }
3579
3580 // _getPageURI
3581 //--------
3582 // Returns the page URI or transparent image if out of range
3583 GnuBook.prototype._getPageURI = function(index, reduce, rotate) {
3584     if (index < 0 || index >= this.numLeafs) { // Synthesize page
3585         return this.imagesBaseURL + "/transparent.png";
3586     }
3587     
3588     return this.getPageURI(index, reduce, rotate);
3589 }
3590
3591 // Library functions
3592 GnuBook.util = {
3593     clamp: function(value, min, max) {
3594         return Math.min(Math.max(value, min), max);
3595     },
3596
3597     getIFrameDocument: function(iframe) {
3598         // Adapted from http://xkr.us/articles/dom/iframe-document/
3599         var outer = (iframe.contentWindow || iframe.contentDocument);
3600         return (outer.document || outer);
3601     },
3602     
3603     decodeURIComponentPlus: function(value) {
3604         // Decodes a URI component and converts '+' to ' '
3605         return decodeURIComponent(value).replace(/\+/g, ' ');
3606     },
3607     
3608     encodeURIComponentPlus: function(value) {
3609         // Encodes a URI component and converts ' ' to '+'
3610         return encodeURIComponent(value).replace(/%20/g, '+');
3611     }
3612     // The final property here must NOT have a comma after it - IE7
3613 }