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