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