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     this.imageArray = [];
49     Roo.apply(this,cfg);
50     this.initialize();
51 }
52
53 Roo.apply(Roo.ux.Lightbox.prototype,  
54 {
55     // optiosn..
56     /**
57      * @cfg fileLoadingImage {string} loading image
58      */
59     fileLoadingImage:        '/lightbox/images/loading.gif',     
60     /**
61      * @cfg fileBottomNavCloseImage {string} close image
62      */
63     fileBottomNavCloseImage: '/lightbox/images/closelabel.gif',
64     /**
65      * @cfg overlayOpacity {number} controls transparency of shadow overlay
66      */
67     overlayOpacity: 0.8,   
68     /**
69      * @cfg fileLoadingImage {boolean} toggles resizing animations
70      */
71     animate: true,          
72     /**
73      * @cfg resizeSpeed {number} controls the speed of the image 
74      * resizing animations (1=slowest and 10=fastest)
75      */
76     resizeSpeed: 9,
77     /**
78      * @cfg borderSize {number} if you adjust the padding in the CSS, 
79      * you will need to update this variable
80      */
81     borderSize: 10,
82     /**
83      * @cfg labelImage {string} When grouping images this is used to write: Image # of #.
84      * Change it for non-english localization
85      */
86         labelImage: "Image",
87         /**
88      * @cfg labelOf {string}  When grouping images this is used to write: Image # of #.
89      */
90     labelOf: "of",
91     
92     
93     
94     
95     /**
96      * List of images
97      */
98     imageArray: false,
99     
100     /**
101      * Current image.
102      * 
103      */
104      
105     activeImage: undefined,
106     
107     /**
108      * initialize() 
109      *  Constructor runs on completion of the DOM loading. Calls updateImageList and then
110      * the function inserts html at the bottom of the page which is used to display the shadow 
111      *  overlay and the image container.
112      * 
113      * 
114      */
115     initialize: function() {    
116         
117         this.updateImageList();
118         this.initializeCSS();
119         // TBD this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
120         this.resizeSpeed  = Math.min(this.resizeSpeed, 10);
121         this.resizeSpeed  = Math.max(this.resizeSpeed, 1);
122         
123             this.resizeDuration = this.animate ? ((11 - this.resizeSpeed) * 0.15) : 0;
124             this.overlayDuration = this.animate ? 0.2 : 0;  // shadow fade in/out duration
125
126         // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
127         // If animations are turned off, it will be hidden as to prevent a flicker of a
128         // white 250 by 250 box.
129         var size = (this.animate ? 250 : 1) + 'px';
130         var dh = Roo.DomHelper;
131         this.el = dh.append(document.body, {
132                 html: 
133                //   '<div id="overlay"></div>' +
134                   '<div class="lightbox">' +
135                   '   <div class="outer-image-container">' +
136                   '       <div class="image-container">' +
137                   '           <img class="lightbox-image">' +
138                   '           <div style="" class="hover-nav">' +
139                   '               <a href="#" class="prev-link"></a>' +
140                   '               <a href="#" class="next-link"></a>' +
141                   '           </div>' +
142                   '           <div class="loading">' +
143                   '               <a href="#" class="loading-link">&nbsp;</a>' +
144                   '           </div>' +
145                   '       </div>' +
146                   '   </div>' +
147                   '   <div class="image-data-container">' +
148                   '       <div class="image-data">' +
149                   '           <div class="image-details">' +
150                   '               <span class="caption"></span>' +
151                   '               <span class="number-display"></span>' +
152                   '           </div>' +
153                   '           <div class="bottom-nav">' +
154                   '               <div href="#" class="bottom-nav-close"></div>' +
155                   '           </div>' +
156                   '       </div>' +
157                   '   </div>' +
158                  '</div>'
159             }, true);
160          
161          
162         
163         var th = this;
164         
165         var ids = 
166             'lightbox outer-image-container image-container ' + 
167             'lightbox-image hover-nav prev-link next-link loading loading-link ' + 
168             'image-data-container image-data image-details caption number-display '
169             'bottom-nav bottom-nav-close';   
170             
171         Roo.each(ids.split(' '), 
172             function(id){ 
173                 var vid = id.replace(/\-/g,'');
174                 th[vid] = this.el.child('.'+id); 
175                 if (!th[vid]) {
176                     return;
177                 }
178                 
179                 th[vid].setVisibilityMode(Roo.Element.DISPLAY);
180             });
181    
182
183                 //Roo.get('overlay').hide();
184         //Roo.get('overlay').on('click', this.end, this);
185                 this.lightbox.hide();
186         this.lightbox.on('click',  function(event) { 
187                 if (Roo.get(event.getTarget()).hasClass('lightbox')) {
188                     this.end(); 
189                 }
190             }, this);
191             
192                 this.outerimagecontainer.setStyle({ width: size, height: size });
193         
194                 this.prevlink.on('click', 
195             function(event) { 
196                 event.stopEvent(); 
197                 this.changeImage(this.activeImage - 1); 
198             }, this);
199             
200                 this.nextlink.on('click', 
201             function(event) { 
202                 event.stopEvent(); 
203                 this.changeImage(this.activeImage + 1); 
204             },this);
205             
206                 this.loadinglink.on('click', 
207             function(event) { 
208                 event.stopEvent(); 
209                 this.end(); 
210             }, this);
211             
212                 this.bottomnavclose.on('click',  
213             function(event) { 
214                 event.stopEvent(); 
215                 this.end(); 
216             }, this);
217
218        
219     },
220
221     initializeCSS: function() {    
222         if (typeof(Roo.ux.Lightbox.css) != 'undefined') {
223             return;
224         }
225         Roo.ux.Lightbox.css = Roo.util.CSS.createStyleSheet( {
226             '.roo-lightbox' : {
227                 position: 'absolute',
228                 left: 0,
229                 width: '100%',
230                 'text-align': 'center',
231                 'line-height': 0,
232             },
233             '.roo-lightbox a img' : { border: 'none'  },
234             '.roo-lightbox .outer-image-container' : {
235                 position: 'relative'; 
236                 'background-color': '#fff'; 
237                 width: '250px',
238                 height: '250px',
239                 margin: '0 auto'
240             },
241             
242             '.roo-lightbox image-container'  :{ padding: '10px'  }
243
244             '.roo-lightbox .loading' { 
245             position:'absolute; 
246                 top:'40%',
247                 left:'0%',
248                 height:'25%',
249                 width:'100%',
250                 text-align:'center',
251                 line-height:'0'
252             
253             }
254             '.roo-lightbox loading a' : { 
255                 background:'url(../images/loading.gif) 0 0 no-repeat; 
256                 display:'block',
257                 width:'32px',
258                 height:'32px',
259                 cursor:'pointer'
260             }
261             '.roo-lightbox bottom-nav-close' : {
262                 background:'url(../images/close.gif) 0 0 no-repeat', 
263                 height:'26px',
264                 width:'26px',
265                 cursor:'pointer'
266             }
267             '.roo-lightbox .hoverNav' :{ 
268                 position:'absolute', 
269                 top:'0', 
270                 left:'0', 
271                 height:'100%', 
272                 width:'100%', 
273                 'z-index':'10'
274             }
275             '.roo-lightbox .image-container>.hover-nav' :{ left:'0' },
276             '.roo-lightbox .hover-nav a' :{ outline:'none'},
277
278             '.roo-lightbox .prev-link, .roo-lightbox .next-link' : { 
279                 width:'49%', 
280                 height:'100%', 
281                 'background-image':'url(data:image/gif;base64,AAAA)', 
282                 display:'block' 
283             },
284             '.roo-lightbox .prev-link' : { left:'0','float':'left'},
285             '.roo-lightbox .next-link' : { right:'0','float':'right'},
286             '.roo-lightbox .prev-link:hover, .roo-lightbox .prev-link:visited:hover ' :{ 
287                     background:'url(../images/prevlabel.gif) left 15% no-repeat'
288             },
289             '.roo-lightbox .next-link:hover, .roo-lightbox .next-link:visited:hover ' :{ 
290                 background:'url(../images/nextlabel.gif) right 15% no-repeat'
291             },
292
293             '.roo-lightbox .image-data-container' : { 
294                 font: '10px Verdana, Helvetica, sans-serif',
295                 background-color: #fff; 
296                 margin: 0 auto; 
297                 line-height: 1.4em; 
298                 overflow: auto; 
299                 width: 100% ; 
300             },
301
302             '.roo-lightbox .image-data' : { padding:'0 10px', color: '#666' },
303             '.roo-lightbox .image-data .image-details ' : { width: '70%', 'float': 'left', 'text-align': 'left'}  ,
304             '.roo-lightbox .image-data .caption' : { 'font-weight': 'bold' },
305             '.roo-lightbox .image-data .numberDisplay' : { 'display': 'block', clear: 'left', 'padding-bottom': '1.0em'  } ,   
306             '.roo-lightbox .image-data .bottomNavClose' : {  'float': 'right',  'padding-bottom': '0.7em','outline': 'none'}  
307         });
308     },
309
310
311     
312     /**
313      * updateImageList()
314      * Loops through anchor tags looking for 'lightbox' references and applies onclick
315      * events to appropriate links. You can rerun after dynamically adding images w/ajax.
316      * 
317      */
318     updateImageList: function() {   
319         this.updateImageList = Roo.emptyFn;
320         if (this.imageArray.length) {
321             return;
322         }
323         Roo.each(Roo.DomQuery.select('a[rel^=lightbox]'), function(e) {
324             this.imageArray.push(Roo.get(e));
325             Roo.get(e).on('click', (function(event, tg, tga,tgb) {
326                
327              
328                 event.stopEvent();
329                 this.start(tgb);
330             }).createDelegate(this, [e], true));
331         }, this)
332         
333     },
334     
335     /**
336     * start()
337     *  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
338     */
339     start: function(imageLink) {
340         /*
341         // hide all the objects that cause problems..
342         $$('select', 'object', 'embed').each(
343             function(node){ 
344             node.style.visibility = 'hidden' }
345         );
346         */
347         // stretch overlay to fill page and fade in
348         //var arrayPageSize = this.getPageSize();
349         Roo.get(document.body).mask(false);
350         Roo.get(document.body)._mask.setHeight(Roo.lib.Dom.getDocumentHeight())        
351         //new Effect.Appear(this.overlay,
352         //    { duration: this.overlayDuration, from: 0.0, to: this.overlayOpacity });
353
354         //this.imageArray = [];
355         var imageNum = 0;       
356         
357         if (imageLink) {
358             imageLink = Roo.get(imageLink);
359             //console.log(imageLink.id);
360             Roo.each(this.imageArray, function (e, i) {
361               //  console.log(e.id);
362                 if (e.id == imageLink.id) {
363                     imageNum = i;
364                 }
365             });
366         }
367         
368         // let's assume the constructor sorts out the list of images..
369         /*
370         if ((imageLink.rel == 'lightbox')){
371             // if image is NOT part of a set, add single image to imageArray
372             this.imageArray.push([imageLink.href, imageLink.title]);         
373         } else {
374             // if image is part of a set..
375             this.imageArray = 
376                 $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
377                 collect(function(anchor){ return [anchor.href, anchor.title]; }).
378                 uniq();
379             
380             while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
381         }
382         */
383         var s = Roo.get(document).getScroll();
384         
385         // calculate top and left offset for the lightbox 
386         // weird.. why / 10?
387         var lightboxTop = s.top + (Roo.lib.Dom.getViewHeight() / 10);
388         var lightboxLeft = s.left
389         this.lightbox.setStyle({ 
390             top: lightboxTop + 'px', 
391             left: lightboxLeft + 'px' ,
392             zIndex : Roo.get(document.body)._mask.getStyle('zIndex') * 1.1
393         })
394         //console.log("show lightbox");
395         this.lightbox.show();
396         
397         
398         
399         this.changeImage(imageNum);
400     },
401
402     //
403     //  changeImage()
404     //  Hide most elements and preload image in preparation for resizing image container.
405     //
406     changeImage: function(imageNum) {   
407         
408         this.activeImage = imageNum; // update global var
409
410         // hide elements during transition
411         if (this.animate) {
412             this.loading.setStyle({
413                 zIndex : Roo.get(document.body)._mask.getStyle('zIndex') * 1.2
414             });
415             this.loading.show();
416             this.loadinglink.setX( (Roo.lib.Dom.getViewWidth() / 2) - 16);
417             //this.loadingLink.show();
418             // center the loading?
419             
420         }
421         
422         this.hovernav.hide();
423         this.prevlink.hide();
424         this.nextlink.hide();
425                 // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
426         this.imagedatacontainer.setStyle({opacity: .0001});
427         this.numberdisplay.hide();
428         
429         var imgPreloader =  Roo.DomHelper.append(document.body, { tag: 'img' } , true);
430         // once image is preloaded, resize image container
431
432         
433         imgPreloader.on('load', function() {
434             
435             this.lightboximage.dom.src = this.imageArray[this.activeImage].dom.href;
436             
437             this.resizeimagecontainer(imgPreloader.getWidth(), imgPreloader.getHeight());
438             imgPreloader.remove();
439         }, this);
440         imgPreloader.dom.src = this.imageArray[this.activeImage].dom.href;
441     },
442
443     //
444     //  resizeImageContainer()
445     //
446     resizeImageContainer: function(imgWidth, imgHeight) {
447
448         // make sure we have some sensible sizes..
449         imgWidth = Math.max(50, imgWidth);
450         imgHeight = Math.max(50, imgHeight);
451         
452         // get current width and height
453         var widthCurrent  = this.outerimagecontainer.getWidth();
454         var heightCurrent = this.outerimagecontainer.getHeight();
455         
456         //fixme need better calcs.
457         var w = window;
458         var ww = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
459         var wh = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
460         
461         ww -= 150;
462         wh -= 150;
463         // get new width and height
464         var bs =  this.borderSize * 2;
465         
466         var widthNew  =  imgWidth  + bs;
467         var heightNew =  imgHeight + bs;
468         
469         if (widthNew > ww || heightNew > wh) {
470             // bigger than window.
471             // scale here... - bit nasty..
472             var rescale = 1.1 * Math.max( widthNew / ww , heightNew  / wh);
473              //console.log(rescale);
474             imgWidth = Math.floor(imgWidth / rescale);
475             imgHeight = Math.floor(imgHeight / rescale);
476             widthNew  =  imgWidth  + bs;
477             heightNew =  imgHeight + bs;
478                     
479             
480         }
481         
482         this.lightboximage.set( { width : imgWidth, height : imgHeight });
483         
484         
485         // scalars based on change from old to new
486         var xScale = (widthNew  / widthCurrent)  * 100;
487         var yScale = (heightNew / heightCurrent) * 100;
488
489         // calculate size difference between new and old image, and resize if necessary
490         var wDiff = widthCurrent - widthNew;
491         var hDiff = heightCurrent - heightNew;
492         
493          
494         this.outerimagecontainer.animate(
495             { width: {to: widthNew}, height: {to: heightNew} },
496             this.resizeDuration,
497             null, // on complete
498             'easeOut', // easing
499             'run' // effect
500         
501         )        
502        
503         
504         // if new and old image are same size and no scaling transition is necessary, 
505         // do a quick pause to prevent image flicker.
506         var timeout = 0;
507         if ((hDiff == 0) && (wDiff == 0)){
508             timeout = 100;
509             if (Roo.isIE) timeout = 250;   
510         }
511
512         (function(){
513             this.prevlink.setStyle({ height: imgHeight + 'px' });
514             this.nextlink.setStyle({ height: imgHeight + 'px' });
515             this.imagedatacontainer.setStyle({ width: widthNew + 'px'}); // the text area..
516             this.showImage();
517         }).defer(timeout / 1000, this);
518     },
519     
520     //
521     //  showImage()
522     //  Display image and begin preloading neighbors.
523     //
524     showImage: function(){
525         
526         this.loading.hide();
527         //this.loadingLink.hide();
528         var _this=  this;
529         this.lightboximage.animate( 
530             {
531                 opacity : {  to: 1.0 }
532             },
533             this.resizeDuration,
534             function(){ 
535                 _this.updateDetails(); 
536             }
537             
538         );
539         this.preloadNeighborImages();
540     },
541
542     //
543     //  updateDetails()
544     //  Display caption, image number, and bottom nav.
545     //
546     updateDetails: function() {
547     
548         // if caption is not null
549         if (this.imageArray[this.activeImage].dom.title  != ""){
550             this.caption.update(this.imageArray[this.activeImage].dom.title);
551             this.caption.show();
552         }
553         
554         // if image is part of set display 'Image x of x' 
555         if (this.imageArray.length > 1){
556             this.numberdisplay.update(
557                 this.labelImage + ' ' + (this.activeImage + 1) + ' ' + this.labelOf + '  ' + this.imageArray.length)
558             this.numberDisplay.show();
559         }
560         var _this = this;
561         this.imagedatacontainer.animate(
562             {
563                 //slide down ?: , from: 0.0, to: 1.0 
564                 opacity :  {  to: 1.0 }
565             },
566             this.resizeDuration,
567             function() {
568                         // update overlay size and update nav
569                         //var arrayPageSize = this.getPageSize();
570                         //this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
571                         _this.updateNav();
572             }
573              
574         );
575     },
576
577     //
578     //  updateNav()
579     //  Display appropriate previous and next hover navigation.
580     //
581     updateNav: function() {
582
583         this.hovernav.show();               
584
585         // if not first image in set, display prev image button
586         if (this.activeImage > 0) this.prevlink.show();
587
588         // if not last image in set, display next image button
589         if (this.activeImage < (this.imageArray.length - 1)) this.nextlink.show();
590         
591         this.enableKeyboardNav();
592     },
593
594     //
595     //  enableKeyboardNav()
596     //
597     enableKeyboardNav: function() {
598         Roo.get(document.body).on('keydown', this.keyboardAction, this); 
599     },
600
601     //
602     //  disableKeyboardNav()
603     //
604     disableKeyboardNav: function() {
605         Roo.get(document.body).un('keydown', this.keyboardAction, this); 
606     },
607
608     //
609     //  keyboardAction()
610     //
611     keyboardAction: function(event)
612     {
613         var keycode = event.keyCode;
614
615         var escapeKey;
616         if (event.DOM_VK_ESCAPE) {  // mozilla
617             escapeKey = event.DOM_VK_ESCAPE;
618         } else { // ie
619             escapeKey = 27;
620         }
621
622         var key = String.fromCharCode(keycode).toLowerCase();
623         
624         if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
625             this.end();
626         } else if ((key == 'p') || (keycode == 37)){ // display previous image
627             if (this.activeImage != 0){
628                 this.disableKeyboardNav();
629                 this.changeImage(this.activeImage - 1);
630             }
631         } else if ((key == 'n') || (keycode == 39)){ // display next image
632             if (this.activeImage != (this.imageArray.length - 1)){
633                 this.disableKeyboardNav();
634                 this.changeImage(this.activeImage + 1);
635             }
636         }
637     },
638
639     //
640     //  preloadNeighborImages()
641     //  Preload previous and next images.
642     //
643     preloadNeighborImages: function(){
644         var preloadNextImage, preloadPrevImage;
645         if (this.imageArray.length > this.activeImage + 1){
646             preloadNextImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
647             preloadNextImage.on('load', function() { preloadNextImage.remove() });
648             preloadNextImage.dom.src = this.imageArray[this.activeImage + 1].dom.href;
649         }
650         if (this.activeImage > 0){
651             preloadPrevImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
652             preloadPrevImage.on('load', function() { preloadPrevImage.remove() });
653             preloadPrevImage.dom.src = this.imageArray[this.activeImage - 1].dom.href;
654         }
655     
656     },
657
658     //
659     //  end()
660     //
661     end: function() {
662         this.disableKeyboardNav();
663         //console.log('lightbox hide');
664         this.lightbox.hide();
665         this.loading.hide();
666         Roo.get(document.body).unmask();
667         // show all the objects that cause problems..
668         //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
669     }
670
671      
672 });
673