ux/Lightbox.js
[roojs1] / ux / Lightbox.js
1 /* <script type="text/javascript">
2 // -----------------------------------------------------------------------------------
3 // Roo lightbox - based on..
4 //
5 //      Lightbox v2.04
6 //      by Lokesh Dhakar - http://www.lokeshdhakar.com
7 //      Last Modification: 2/9/08
8 //
9 //      For more information, visit:
10 //      http://lokeshdhakar.com/projects/lightbox2/
11 //
12 //      Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
13 //      - Free for use in both personal and commercial projects
14 //              - Attribution requires leaving author name, author link, and the license info intact.
15 //      
16 //  Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
17 //              Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous.
18 //
19 // -----------------------------------------------------------------------------------
20 /*
21
22     Table of Contents
23     -----------------
24     Configuration
25
26     Lightbox Class Declaration
27     - initialize()
28     - updateImageList()
29     - start()
30     - changeImage()
31     - resizeImageContainer()
32     - showImage()
33     - updateDetails()
34     - updateNav()
35     - enableKeyboardNav()
36     - disableKeyboardNav()
37     - keyboardAction()
38     - preloadNeighborImages()
39     - end()
40     
41     Function Calls
42     - document.observe()
43    
44 */
45 Roo.namespace('Roo.ux'); 
46  
47 Roo.ux.Lightbox = function(cfg) {
48     Roo.apply(this,cfg);
49     this.initialize();
50 }
51
52 Roo.apply(Roo.ux.Lightbox.prototype,  
53 {
54     // optiosn..
55     /**
56      * @cfg fileLoadingImage {string} loading image
57      */
58     fileLoadingImage:        '/lightbox/images/loading.gif',     
59     /**
60      * @cfg fileBottomNavCloseImage {string} close image
61      */
62     fileBottomNavCloseImage: '/lightbox/images/closelabel.gif',
63     /**
64      * @cfg overlayOpacity {number} controls transparency of shadow overlay
65      */
66     overlayOpacity: 0.8,   
67     /**
68      * @cfg fileLoadingImage {boolean} toggles resizing animations
69      */
70     animate: true,          
71     /**
72      * @cfg resizeSpeed {number} controls the speed of the image 
73      * resizing animations (1=slowest and 10=fastest)
74      */
75     resizeSpeed: 9,
76     /**
77      * @cfg borderSize {number} if you adjust the padding in the CSS, 
78      * you will need to update this variable
79      */
80     borderSize: 10,
81     /**
82      * @cfg labelImage {string} When grouping images this is used to write: Image # of #.
83      * Change it for non-english localization
84      */
85         labelImage: "Image",
86         /**
87      * @cfg labelOf {string}  When grouping images this is used to write: Image # of #.
88      */
89     labelOf: "of",
90     
91     
92     
93     
94     /**
95      * List of images
96      */
97     imageArray: [],
98     
99     /**
100      * Current image.
101      * 
102      */
103      
104     activeImage: undefined,
105     
106     /**
107      * initialize() 
108      *  Constructor runs on completion of the DOM loading. Calls updateImageList and then
109      * the function inserts html at the bottom of the page which is used to display the shadow 
110      *  overlay and the image container.
111      * 
112      * 
113      */
114     initialize: function() {    
115         
116         this.updateImageList();
117         
118         // TBD this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
119         this.resizeSpeed  = Math.min(this.resizeSpeed, 10);
120         this.resizeSpeed  = Math.max(this.resizeSpeed, 1);
121         
122             this.resizeDuration = this.animate ? ((11 - this.resizeSpeed) * 0.15) : 0;
123             this.overlayDuration = this.animate ? 0.2 : 0;  // shadow fade in/out duration
124
125         // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
126         // If animations are turned off, it will be hidden as to prevent a flicker of a
127         // white 250 by 250 box.
128         var size = (this.animate ? 250 : 1) + 'px';
129         var dh = Roo.DomHelper;
130         this.el = dh.append(document.body, {
131                 html: 
132                //   '<div id="overlay"></div>' +
133                   '<div id="lightbox">' +
134                   '   <div id="outerImageContainer">' +
135                   '       <div id="imageContainer">' +
136                   '           <img id="lightboxImage">' +
137                   '           <div style="" id="hoverNav">' +
138                   '               <a href="#" id="prevLink"></a>' +
139                   '               <a href="#" id="nextLink"></a>' +
140                   '           </div>' +
141                   '           <div id="loading">' +
142                   '               <a href="#" id="loadingLink">&nbsp;</a>' +
143                   '           </div>' +
144                   '       </div>' +
145                   '   </div>' +
146                   '   <div id="imageDataContainer">' +
147                   '       <div id="imageData">' +
148                   '           <div id="imageDetails">' +
149                   '               <span id="caption"></span>' +
150                   '               <span id="numberDisplay"></span>' +
151                   '           </div>' +
152                   '           <div id="bottomNav">' +
153                   '               <div href="#" id="bottomNavClose"></div>' +
154                   '           </div>' +
155                   '       </div>' +
156                   '   </div>' +
157                  '</div>'
158             }, true);
159          
160          
161         
162         var th = this;
163         
164         var ids = 
165             'lightbox outerImageContainer imageContainer ' + 
166             'lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 
167             'imageDataContainer imageData imageDetails caption numberDisplay '
168             'bottomNav bottomNavClose';   
169             
170         Roo.each(ids.split(' '), 
171             function(id){ 
172                 
173                 th[id] = Roo.get(id); 
174                 if (!th[id]) {
175                     return;
176                    }
177                 th[id].setVisibilityMode(Roo.Element.DISPLAY);
178             });
179    
180
181                 //Roo.get('overlay').hide();
182         //Roo.get('overlay').on('click', this.end, this);
183                 Roo.get('lightbox').hide();
184         Roo.get('lightbox').on('click',  function(event) { 
185                 if (event.getTarget().id == 'lightbox') {
186                     this.end(); 
187                 }
188             }, this);
189             
190                 Roo.get('outerImageContainer').setStyle({ width: size, height: size });
191         
192                 Roo.get('prevLink').on('click', 
193             function(event) { 
194                 event.stopEvent(); 
195                 this.changeImage(this.activeImage - 1); 
196             }, this);
197             
198                 Roo.get('nextLink').on('click', 
199             function(event) { 
200                 event.stopEvent(); 
201                 this.changeImage(this.activeImage + 1); 
202             },this);
203             
204                 Roo.get('loadingLink').on('click', 
205             function(event) { 
206                 event.stopEvent(); 
207                 this.end(); 
208             }, this);
209             
210                 Roo.get('bottomNavClose').on('click',  
211             function(event) { 
212                 event.stopEvent(); 
213                 this.end(); 
214             }, this);
215
216        
217     },
218
219     /**
220      * updateImageList()
221      * Loops through anchor tags looking for 'lightbox' references and applies onclick
222      * events to appropriate links. You can rerun after dynamically adding images w/ajax.
223      * 
224      */
225     updateImageList: function() {   
226         this.updateImageList = Roo.emptyFn;
227         
228         Roo.each(Roo.DomQuery.select('a[rel^=lightbox]'), function(e) {
229             this.imageArray.push(Roo.get(e));
230             Roo.get(e).on('click', (function(event, tg, tga,tgb) {
231                
232              
233                 event.stopEvent();
234                 this.start(tgb);
235             }).createDelegate(this, [e], true));
236         }, this)
237         
238     },
239     
240     /**
241     * start()
242     *  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
243     */
244     start: function(imageLink) {
245         /*
246         // hide all the objects that cause problems..
247         $$('select', 'object', 'embed').each(
248             function(node){ 
249             node.style.visibility = 'hidden' }
250         );
251         */
252         // stretch overlay to fill page and fade in
253         //var arrayPageSize = this.getPageSize();
254         Roo.get(document.body).mask(false);
255         Roo.get(document.body)._mask.setHeight(Roo.lib.Dom.getDocumentHeight())        
256         //new Effect.Appear(this.overlay,
257         //    { duration: this.overlayDuration, from: 0.0, to: this.overlayOpacity });
258
259         //this.imageArray = [];
260         var imageNum = 0;       
261         
262         if (imageLink) {
263             imageLink = Roo.get(imageLink);
264             //console.log(imageLink.id);
265             Roo.each(this.imageArray, function (e, i) {
266               //  console.log(e.id);
267                 if (e.id == imageLink.id) {
268                     imageNum = i;
269                 }
270             });
271         }
272         
273         // let's assume the constructor sorts out the list of images..
274         /*
275         if ((imageLink.rel == 'lightbox')){
276             // if image is NOT part of a set, add single image to imageArray
277             this.imageArray.push([imageLink.href, imageLink.title]);         
278         } else {
279             // if image is part of a set..
280             this.imageArray = 
281                 $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
282                 collect(function(anchor){ return [anchor.href, anchor.title]; }).
283                 uniq();
284             
285             while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
286         }
287         */
288         var s = Roo.get(document).getScroll();
289         
290         // calculate top and left offset for the lightbox 
291         // weird.. why / 10?
292         var lightboxTop = s.top + (Roo.lib.Dom.getViewHeight() / 10);
293         var lightboxLeft = s.left
294         this.lightbox.setStyle({ 
295             top: lightboxTop + 'px', 
296             left: lightboxLeft + 'px' ,
297             zIndex : Roo.get(document.body)._mask.getStyle('zIndex') * 1.1
298         })
299         //console.log("show lightbox");
300         this.lightbox.show();
301         
302         
303         
304         this.changeImage(imageNum);
305     },
306
307     //
308     //  changeImage()
309     //  Hide most elements and preload image in preparation for resizing image container.
310     //
311     changeImage: function(imageNum) {   
312         
313         this.activeImage = imageNum; // update global var
314
315         // hide elements during transition
316         if (this.animate) {
317             this.loading.setStyle({
318                 zIndex : Roo.get(document.body)._mask.getStyle('zIndex') * 1.2
319             });
320             this.loading.show();
321             this.loadingLink.setX( (Roo.lib.Dom.getViewWidth() / 2) - 16);
322             //this.loadingLink.show();
323             // center the loading?
324             
325         }
326         
327         this.hoverNav.hide();
328         this.prevLink.hide();
329         this.nextLink.hide();
330                 // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
331         this.imageDataContainer.setStyle({opacity: .0001});
332         this.numberDisplay.hide();
333         
334         var imgPreloader =  Roo.DomHelper.append(document.body, { tag: 'img' } , true);
335         // once image is preloaded, resize image container
336
337         
338         imgPreloader.on('load', function() {
339             this.lightboxImage.dom.src = this.imageArray[this.activeImage].dom.href;
340             
341             this.resizeImageContainer(imgPreloader.getWidth(), imgPreloader.getHeight());
342             imgPreloader.remove();
343         }, this);
344         imgPreloader.dom.src = this.imageArray[this.activeImage].dom.href;
345     },
346
347     //
348     //  resizeImageContainer()
349     //
350     resizeImageContainer: function(imgWidth, imgHeight) {
351
352         // make sure we have some sensible sizes..
353         imgWidth = Math.max(50, imgWidth);
354         imgHeight = Math.max(50, imgHeight);
355         
356         // get current width and height
357         var widthCurrent  = this.outerImageContainer.getWidth();
358         var heightCurrent = this.outerImageContainer.getHeight();
359         
360         //fixme need better calcs.
361         var w = window;
362         var ww = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
363         var wh = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
364         
365         ww -= 150;
366         wh -= 150;
367         // get new width and height
368         var bs =  this.borderSize * 2;
369         
370         var widthNew  =  imgWidth  + bs;
371         var heightNew =  imgHeight + bs;
372         
373         if (widthNew > ww || heightNew > wh) {
374             // bigger than window.
375             // scale here... - bit nasty..
376             var rescale = 1.1 * Math.max( widthNew / ww , heightNew  / wh);
377              //console.log(rescale);
378             imgWidth = Math.floor(imgWidth / rescale);
379             imgHeight = Math.floor(imgHeight / rescale);
380             widthNew  =  imgWidth  + bs;
381             heightNew =  imgHeight + bs;
382                     
383             
384         }
385         
386         this.lightboxImage.set( { width : imgWidth, height : imgHeight });
387         
388         
389         // scalars based on change from old to new
390         var xScale = (widthNew  / widthCurrent)  * 100;
391         var yScale = (heightNew / heightCurrent) * 100;
392
393         // calculate size difference between new and old image, and resize if necessary
394         var wDiff = widthCurrent - widthNew;
395         var hDiff = heightCurrent - heightNew;
396         
397          
398         this.outerImageContainer.animate(
399             { width: {to: widthNew}, height: {to: heightNew} },
400             this.resizeDuration,
401             null, // on complete
402             'easeOut', // easing
403             'run' // effect
404         
405         )        
406        
407         
408         // if new and old image are same size and no scaling transition is necessary, 
409         // do a quick pause to prevent image flicker.
410         var timeout = 0;
411         if ((hDiff == 0) && (wDiff == 0)){
412             timeout = 100;
413             if (Roo.isIE) timeout = 250;   
414         }
415
416         (function(){
417             this.prevLink.setStyle({ height: imgHeight + 'px' });
418             this.nextLink.setStyle({ height: imgHeight + 'px' });
419             this.imageDataContainer.setStyle({ width: widthNew + 'px'}); // the text area..
420             this.showImage();
421         }).defer(timeout / 1000, this);
422     },
423     
424     //
425     //  showImage()
426     //  Display image and begin preloading neighbors.
427     //
428     showImage: function(){
429         
430         this.loading.hide();
431         //this.loadingLink.hide();
432         var _this=  this;
433         this.lightboxImage.animate( 
434             {
435                 opacity : {  to: 1.0 }
436             },
437             this.resizeDuration,
438             function(){ 
439                 _this.updateDetails(); 
440             }
441             
442         );
443         this.preloadNeighborImages();
444     },
445
446     //
447     //  updateDetails()
448     //  Display caption, image number, and bottom nav.
449     //
450     updateDetails: function() {
451     
452         // if caption is not null
453         if (this.imageArray[this.activeImage].dom.title  != ""){
454             this.caption.update(this.imageArray[this.activeImage].dom.title);
455             this.caption.show();
456         }
457         
458         // if image is part of set display 'Image x of x' 
459         if (this.imageArray.length > 1){
460             this.numberDisplay.update(
461                 this.labelImage + ' ' + (this.activeImage + 1) + ' ' + this.labelOf + '  ' + this.imageArray.length)
462             this.numberDisplay.show();
463         }
464         var _this = this;
465         this.imageDataContainer.animate(
466             {
467                 //slide down ?: , from: 0.0, to: 1.0 
468                 opacity :  {  to: 1.0 }
469             },
470             this.resizeDuration,
471             function() {
472                         // update overlay size and update nav
473                         //var arrayPageSize = this.getPageSize();
474                         //this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
475                         _this.updateNav();
476             }
477              
478         );
479     },
480
481     //
482     //  updateNav()
483     //  Display appropriate previous and next hover navigation.
484     //
485     updateNav: function() {
486
487         this.hoverNav.show();               
488
489         // if not first image in set, display prev image button
490         if (this.activeImage > 0) this.prevLink.show();
491
492         // if not last image in set, display next image button
493         if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show();
494         
495         this.enableKeyboardNav();
496     },
497
498     //
499     //  enableKeyboardNav()
500     //
501     enableKeyboardNav: function() {
502         Roo.get(document.body).on('keydown', this.keyboardAction, this); 
503     },
504
505     //
506     //  disableKeyboardNav()
507     //
508     disableKeyboardNav: function() {
509         Roo.get(document.body).un('keydown', this.keyboardAction, this); 
510     },
511
512     //
513     //  keyboardAction()
514     //
515     keyboardAction: function(event) {
516         var keycode = event.keyCode;
517
518         var escapeKey;
519         if (event.DOM_VK_ESCAPE) {  // mozilla
520             escapeKey = event.DOM_VK_ESCAPE;
521         } else { // ie
522             escapeKey = 27;
523         }
524
525         var key = String.fromCharCode(keycode).toLowerCase();
526         
527         if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
528             this.end();
529         } else if ((key == 'p') || (keycode == 37)){ // display previous image
530             if (this.activeImage != 0){
531                 this.disableKeyboardNav();
532                 this.changeImage(this.activeImage - 1);
533             }
534         } else if ((key == 'n') || (keycode == 39)){ // display next image
535             if (this.activeImage != (this.imageArray.length - 1)){
536                 this.disableKeyboardNav();
537                 this.changeImage(this.activeImage + 1);
538             }
539         }
540     },
541
542     //
543     //  preloadNeighborImages()
544     //  Preload previous and next images.
545     //
546     preloadNeighborImages: function(){
547         var preloadNextImage, preloadPrevImage;
548         if (this.imageArray.length > this.activeImage + 1){
549             preloadNextImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
550             preloadNextImage.on('load', function() { preloadNextImage.remove() });
551             preloadNextImage.dom.src = this.imageArray[this.activeImage + 1].dom.href;
552         }
553         if (this.activeImage > 0){
554             preloadPrevImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
555             preloadPrevImage.on('load', function() { preloadPrevImage.remove() });
556             preloadPrevImage.dom.src = this.imageArray[this.activeImage - 1].dom.href;
557         }
558     
559     },
560
561     //
562     //  end()
563     //
564     end: function() {
565         this.disableKeyboardNav();
566         //console.log('lightbox hide');
567         this.lightbox.hide();
568         this.loading.hide();
569         Roo.get(document.body).unmask();
570         // show all the objects that cause problems..
571         //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
572     }
573
574      
575 });
576