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         imgPreloader.on('load', function() {
433             
434             this.lightboximage.dom.src = this.imageArray[this.activeImage].dom.href;
435             
436             this.resizeimagecontainer(imgPreloader.getWidth(), imgPreloader.getHeight());
437             imgPreloader.remove();
438         }, this);
439         imgPreloader.dom.src = this.imageArray[this.activeImage].dom.href;
440     },
441
442     
443     
444     //
445     //  resizeImageContainer()
446     //
447     resizeImageContainer: function(imgWidth, imgHeight) {
448
449         // make sure we have some sensible sizes..
450         imgWidth = Math.max(50, imgWidth);
451         imgHeight = Math.max(50, imgHeight);
452         
453         // get current width and height
454         var widthCurrent  = this.outerimagecontainer.getWidth();
455         var heightCurrent = this.outerimagecontainer.getHeight();
456         
457         //fixme need better calcs.
458         var w = window;
459         var ww = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
460         var wh = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
461         
462         ww -= 150;
463         wh -= 150;
464         // get new width and height
465         var bs =  this.borderSize * 2;
466         
467         var widthNew  =  imgWidth  + bs;
468         var heightNew =  imgHeight + bs;
469         
470         if (widthNew > ww || heightNew > wh) {
471             // bigger than window.
472             // scale here... - bit nasty..
473             var rescale = 1.1 * Math.max( widthNew / ww , heightNew  / wh);
474              //console.log(rescale);
475             imgWidth = Math.floor(imgWidth / rescale);
476             imgHeight = Math.floor(imgHeight / rescale);
477             widthNew  =  imgWidth  + bs;
478             heightNew =  imgHeight + bs;
479                     
480             
481         }
482         
483         this.lightboximage.set( { width : imgWidth, height : imgHeight });
484         
485         
486         // scalars based on change from old to new
487         var xScale = (widthNew  / widthCurrent)  * 100;
488         var yScale = (heightNew / heightCurrent) * 100;
489
490         // calculate size difference between new and old image, and resize if necessary
491         var wDiff = widthCurrent - widthNew;
492         var hDiff = heightCurrent - heightNew;
493         
494          
495         this.outerimagecontainer.animate(
496             { width: {to: widthNew}, height: {to: heightNew} },
497             this.resizeDuration,
498             null, // on complete
499             'easeOut', // easing
500             'run' // effect
501         
502         )        
503        
504         
505         // if new and old image are same size and no scaling transition is necessary, 
506         // do a quick pause to prevent image flicker.
507         var timeout = 0;
508         if ((hDiff == 0) && (wDiff == 0)){
509             timeout = 100;
510             if (Roo.isIE) timeout = 250;   
511         }
512
513         (function(){
514             this.prevlink.setStyle({ height: imgHeight + 'px' });
515             this.nextlink.setStyle({ height: imgHeight + 'px' });
516             this.imagedatacontainer.setStyle({ width: widthNew + 'px'}); // the text area..
517             this.showImage();
518         }).defer(timeout / 1000, this);
519     },
520     
521     //
522     //  showImage()
523     //  Display image and begin preloading neighbors.
524     //
525     showImage: function(){
526         
527         this.loading.hide();
528         //this.loadingLink.hide();
529         var _this=  this;
530         this.lightboximage.animate( 
531             {
532                 opacity : {  to: 1.0 }
533             },
534             this.resizeDuration,
535             function(){ 
536                 _this.updateDetails(); 
537             }
538             
539         );
540         this.preloadNeighborImages();
541     },
542
543     //
544     //  updateDetails()
545     //  Display caption, image number, and bottom nav.
546     //
547     updateDetails: function() {
548     
549         // if caption is not null
550         if (this.imageArray[this.activeImage].dom.title  != ""){
551             this.caption.update(this.imageArray[this.activeImage].dom.title);
552             this.caption.show();
553         }
554         
555         // if image is part of set display 'Image x of x' 
556         if (this.imageArray.length > 1){
557             this.numberdisplay.update(
558                 this.labelImage + ' ' + (this.activeImage + 1) + ' ' + this.labelOf + '  ' + this.imageArray.length)
559             this.numberDisplay.show();
560         }
561         var _this = this;
562         this.imagedatacontainer.animate(
563             {
564                 //slide down ?: , from: 0.0, to: 1.0 
565                 opacity :  {  to: 1.0 }
566             },
567             this.resizeDuration,
568             function() {
569                         // update overlay size and update nav
570                         //var arrayPageSize = this.getPageSize();
571                         //this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
572                         _this.updateNav();
573             }
574              
575         );
576     },
577
578     //
579     //  updateNav()
580     //  Display appropriate previous and next hover navigation.
581     //
582     updateNav: function() {
583
584         this.hovernav.show();               
585
586         // if not first image in set, display prev image button
587         if (this.activeImage > 0) this.prevlink.show();
588
589         // if not last image in set, display next image button
590         if (this.activeImage < (this.imageArray.length - 1)) this.nextlink.show();
591         
592         this.enableKeyboardNav();
593     },
594
595     //
596     //  enableKeyboardNav()
597     //
598     enableKeyboardNav: function() {
599         Roo.get(document.body).on('keydown', this.keyboardAction, this); 
600     },
601
602     //
603     //  disableKeyboardNav()
604     //
605     disableKeyboardNav: function() {
606         Roo.get(document.body).un('keydown', this.keyboardAction, this); 
607     },
608
609     //
610     //  keyboardAction()
611     //
612     keyboardAction: function(event)
613     {
614         var keycode = event.keyCode;
615
616         var escapeKey;
617         if (event.DOM_VK_ESCAPE) {  // mozilla
618             escapeKey = event.DOM_VK_ESCAPE;
619         } else { // ie
620             escapeKey = 27;
621         }
622
623         var key = String.fromCharCode(keycode).toLowerCase();
624         
625         if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
626             this.end();
627         } else if ((key == 'p') || (keycode == 37)){ // display previous image
628             if (this.activeImage != 0){
629                 this.disableKeyboardNav();
630                 this.changeImage(this.activeImage - 1);
631             }
632         } else if ((key == 'n') || (keycode == 39)){ // display next image
633             if (this.activeImage != (this.imageArray.length - 1)){
634                 this.disableKeyboardNav();
635                 this.changeImage(this.activeImage + 1);
636             }
637         }
638     },
639
640     //
641     //  preloadNeighborImages()
642     //  Preload previous and next images.
643     //
644     preloadNeighborImages: function(){
645         var preloadNextImage, preloadPrevImage;
646         if (this.imageArray.length > this.activeImage + 1){
647             preloadNextImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
648             preloadNextImage.on('load', function() { preloadNextImage.remove() });
649             preloadNextImage.dom.src = this.imageArray[this.activeImage + 1].dom.href;
650         }
651         if (this.activeImage > 0){
652             preloadPrevImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
653             preloadPrevImage.on('load', function() { preloadPrevImage.remove() });
654             preloadPrevImage.dom.src = this.imageArray[this.activeImage - 1].dom.href;
655         }
656     
657     },
658
659     //
660     //  end()
661     //
662     end: function() {
663         this.disableKeyboardNav();
664         //console.log('lightbox hide');
665         this.lightbox.hide();
666         this.loading.hide();
667         Roo.get(document.body).unmask();
668         // show all the objects that cause problems..
669         //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
670     }
671
672      
673 });
674