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