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