ux/Lightbox.js
[roojs1] / ux / Lightbox.js
1 /* <script type="text/javascript">
2 // -----------------------------------------------------------------------------------
3 // Roo lightbox - based on..
4 //
5 //      Lightbox v2.04
6 //      by Lokesh Dhakar - http://www.lokeshdhakar.com
7 //      Last Modification: 2/9/08
8 //
9 //      For more information, visit:
10 //      http://lokeshdhakar.com/projects/lightbox2/
11 //
12 //      Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
13 //      - Free for use in both personal and commercial projects
14 //              - Attribution requires leaving author name, author link, and the license info intact.
15 //      
16 //  Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
17 //              Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous.
18 //
19 // -----------------------------------------------------------------------------------
20 /*
21
22     Table of Contents
23     -----------------
24     Configuration
25
26     Lightbox Class Declaration
27     - initialize()
28     - updateImageList()
29     - start()
30     - changeImage()
31     - resizeImageContainer()
32     - showImage()
33     - updateDetails()
34     - updateNav()
35     - enableKeyboardNav()
36     - disableKeyboardNav()
37     - keyboardAction()
38     - preloadNeighborImages()
39     - end()
40     
41     Function Calls
42     - document.observe()
43    
44 */
45 Roo.namespace('Roo.ux'); 
46  
47 Roo.ux.Lightbox = function(cfg) {
48     this.imageArray = [];
49     Roo.apply(this,cfg);
50     this.initialize();
51 }
52
53 Roo.apply(Roo.ux.Lightbox.prototype,  
54 {
55     // optiosn..
56     /**
57      * @cfg fileLoadingImage {string} loading image
58      */
59     fileLoadingImage:        '/lightbox/images/loading.gif',     
60     /**
61      * @cfg fileBottomNavCloseImage {string} close image
62      */
63     fileBottomNavCloseImage: '/lightbox/images/closelabel.gif',
64     /**
65      * @cfg overlayOpacity {number} controls transparency of shadow overlay
66      */
67     overlayOpacity: 0.8,   
68     /**
69      * @cfg fileLoadingImage {boolean} toggles resizing animations
70      */
71     animate: true,          
72     /**
73      * @cfg resizeSpeed {number} controls the speed of the image 
74      * resizing animations (1=slowest and 10=fastest)
75      */
76     resizeSpeed: 9,
77     /**
78      * @cfg borderSize {number} if you adjust the padding in the CSS, 
79      * you will need to update this variable
80      */
81     borderSize: 10,
82     /**
83      * @cfg labelImage {string} When grouping images this is used to write: Image # of #.
84      * Change it for non-english localization
85      */
86         labelImage: "Image",
87         /**
88      * @cfg labelOf {string}  When grouping images this is used to write: Image # of #.
89      */
90     labelOf: "of",
91     
92     
93     
94     
95     /**
96      * List of images
97      */
98     imageArray: false,
99     
100     /**
101      * Current image.
102      * 
103      */
104      
105     activeImage: undefined,
106     
107     /**
108      * initialize() 
109      *  Constructor runs on completion of the DOM loading. Calls updateImageList and then
110      * the function inserts html at the bottom of the page which is used to display the shadow 
111      *  overlay and the image container.
112      * 
113      * 
114      */
115     initialize: function() {    
116         
117         this.updateImageList();
118         this.initializeCSS();
119         // TBD this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
120         this.resizeSpeed  = Math.min(this.resizeSpeed, 10);
121         this.resizeSpeed  = Math.max(this.resizeSpeed, 1);
122         
123             this.resizeDuration = this.animate ? ((11 - this.resizeSpeed) * 0.15) : 0;
124             this.overlayDuration = this.animate ? 0.2 : 0;  // shadow fade in/out duration
125
126         // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
127         // If animations are turned off, it will be hidden as to prevent a flicker of a
128         // white 250 by 250 box.
129         var size = (this.animate ? 250 : 1) + 'px';
130         var dh = Roo.DomHelper;
131         this.el = dh.append(document.body, {
132                 html: 
133                //   '<div id="overlay"></div>' +
134                   '<div class="lightbox">' +
135                   '   <div class="outer-image-container">' +
136                   '       <div class="image-container">' +
137                   '           <img class="lightbox-image">' +
138                   '           <div style="" class="hover-nav">' +
139                   '               <a href="#" class="prev-link"></a>' +
140                   '               <a href="#" class="next-link"></a>' +
141                   '           </div>' +
142                   '           <div class="loading">' +
143                   '               <a href="#" class="loading-link">&nbsp;</a>' +
144                   '           </div>' +
145                   '       </div>' +
146                   '   </div>' +
147                   '   <div class="image-data-container">' +
148                   '       <div class="image-data">' +
149                   '           <div class="image-details">' +
150                   '               <span class="caption"></span>' +
151                   '               <span class="number-display"></span>' +
152                   '           </div>' +
153                   '           <div class="bottom-nav">' +
154                   '               <div href="#" class="bottom-nav-close"></div>' +
155                   '           </div>' +
156                   '       </div>' +
157                   '   </div>' +
158                  '</div>'
159             }, true);
160          
161          
162         
163         var th = this;
164         
165         var ids = 
166             'lightbox outerImageContainer imageContainer ' + 
167             'lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 
168             'imageDataContainer imageData imageDetails caption numberDisplay '
169             'bottomNav bottomNavClose';   
170             
171         Roo.each(ids.split(' '), 
172             function(id){ 
173                 
174                 th[id] = Roo.get(id); 
175                 if (!th[id]) {
176                     return;
177                    }
178                 th[id].setVisibilityMode(Roo.Element.DISPLAY);
179             });
180    
181
182                 //Roo.get('overlay').hide();
183         //Roo.get('overlay').on('click', this.end, this);
184                 Roo.get('lightbox').hide();
185         Roo.get('lightbox').on('click',  function(event) { 
186                 if (event.getTarget().id == 'lightbox') {
187                     this.end(); 
188                 }
189             }, this);
190             
191                 Roo.get('outerImageContainer').setStyle({ width: size, height: size });
192         
193                 Roo.get('prevLink').on('click', 
194             function(event) { 
195                 event.stopEvent(); 
196                 this.changeImage(this.activeImage - 1); 
197             }, this);
198             
199                 Roo.get('nextLink').on('click', 
200             function(event) { 
201                 event.stopEvent(); 
202                 this.changeImage(this.activeImage + 1); 
203             },this);
204             
205                 Roo.get('loadingLink').on('click', 
206             function(event) { 
207                 event.stopEvent(); 
208                 this.end(); 
209             }, this);
210             
211                 Roo.get('bottomNavClose').on('click',  
212             function(event) { 
213                 event.stopEvent(); 
214                 this.end(); 
215             }, this);
216
217        
218     },
219
220     initializeCSS: function() {    
221         if (typeof(Roo.ux.Lightbox.css) != 'undefined') {
222             return;
223         }
224         Roo.ux.Lightbox.css = Roo.util.CSS.createStyleSheet( {
225             '.roo-lightbox' : {
226                 position: 'absolute',
227                 left: 0,
228                 width: '100%',
229                 'text-align': 'center',
230                 'line-height': 0,
231             },
232             '.roo-lightbox a img' : { border: 'none'  },
233             '.roo-lightbox .outer-image-container' : {
234                 position: 'relative'; 
235                 'background-color': '#fff'; 
236                 width: '250px',
237                 height: '250px',
238                 margin: '0 auto'
239             },
240             
241             '.roo-lightbox image-container'  :{ padding: '10px'  }
242
243             '.roo-lightbox .loading' { 
244             position:'absolute; 
245                 top:'40%',
246                 left:'0%',
247                 height:'25%',
248                 width:'100%',
249                 text-align:'center',
250                 line-height:'0'
251             
252             }
253             '.roo-lightbox loading a' : { 
254                 background:'url(../images/loading.gif) 0 0 no-repeat; 
255                 display:'block',
256                 width:'32px',
257                 height:'32px',
258                 cursor:'pointer'
259             }
260             '.roo-lightbox bottom-nav-close' : {
261                 background:'url(../images/close.gif) 0 0 no-repeat', 
262                 height:'26px',
263                 width:'26px',
264                 cursor:'pointer'
265             }
266             '.roo-lightbox .hoverNav' :{ 
267                 position:'absolute', 
268                 top:'0', 
269                 left:'0', 
270                 height:'100%', 
271                 width:'100%', 
272                 'z-index':'10'
273             }
274             '.roo-lightbox .image-container>.hover-nav' :{ left:'0' },
275             '.roo-lightbox .hover-nav a' :{ outline:'none'},
276
277             '.roo-lightbox .prev-link, .roo-lightbox .next-link' : { 
278                 width:'49%', 
279                 height:'100%', 
280                 'background-image':'url(data:image/gif;base64,AAAA)', 
281                 display:'block' 
282             },
283             '.roo-lightbox .prev-link' : { left:'0','float':'left'},
284             '.roo-lightbox .next-link' : { right:'0','float':'right'},
285             '.roo-lightbox .prev-link:hover, .roo-lightbox .prev-link:visited:hover ' :{ 
286                     background:'url(../images/prevlabel.gif) left 15% no-repeat'
287             },
288             '.roo-lightbox .next-link:hover, .roo-lightbox .next-link:visited:hover ' :{ 
289                 background:'url(../images/nextlabel.gif) right 15% no-repeat'
290             },
291
292             '.roo-lightbox .image-data-container' : { 
293                 font: '10px Verdana, Helvetica, sans-serif',
294                 background-color: #fff; 
295                 margin: 0 auto; 
296                 line-height: 1.4em; 
297                 overflow: auto; 
298                 width: 100% ; 
299             },
300
301             '.roo-lightbox .image-data' : { padding:'0 10px', color: '#666' },
302             '.roo-lightbox .image-data .image-details ' : { width: '70%', 'float': 'left', 'text-align': 'left'}  ,
303             '.roo-lightbox .image-data .caption' : { 'font-weight': 'bold' },
304             '.roo-lightbox .image-data .numberDisplay' : { 'display': 'block', clear: 'left', 'padding-bottom': '1.0em'  } ,   
305             '.roo-lightbox .image-data .bottomNavClose' : {  'float': 'right',  'padding-bottom': '0.7em','outline': 'none'}  
306         });
307     },
308
309
310     
311     /**
312      * updateImageList()
313      * Loops through anchor tags looking for 'lightbox' references and applies onclick
314      * events to appropriate links. You can rerun after dynamically adding images w/ajax.
315      * 
316      */
317     updateImageList: function() {   
318         this.updateImageList = Roo.emptyFn;
319         if (this.imageArray.length) {
320             return;
321         }
322         Roo.each(Roo.DomQuery.select('a[rel^=lightbox]'), function(e) {
323             this.imageArray.push(Roo.get(e));
324             Roo.get(e).on('click', (function(event, tg, tga,tgb) {
325                
326              
327                 event.stopEvent();
328                 this.start(tgb);
329             }).createDelegate(this, [e], true));
330         }, this)
331         
332     },
333     
334     /**
335     * start()
336     *  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
337     */
338     start: function(imageLink) {
339         /*
340         // hide all the objects that cause problems..
341         $$('select', 'object', 'embed').each(
342             function(node){ 
343             node.style.visibility = 'hidden' }
344         );
345         */
346         // stretch overlay to fill page and fade in
347         //var arrayPageSize = this.getPageSize();
348         Roo.get(document.body).mask(false);
349         Roo.get(document.body)._mask.setHeight(Roo.lib.Dom.getDocumentHeight())        
350         //new Effect.Appear(this.overlay,
351         //    { duration: this.overlayDuration, from: 0.0, to: this.overlayOpacity });
352
353         //this.imageArray = [];
354         var imageNum = 0;       
355         
356         if (imageLink) {
357             imageLink = Roo.get(imageLink);
358             //console.log(imageLink.id);
359             Roo.each(this.imageArray, function (e, i) {
360               //  console.log(e.id);
361                 if (e.id == imageLink.id) {
362                     imageNum = i;
363                 }
364             });
365         }
366         
367         // let's assume the constructor sorts out the list of images..
368         /*
369         if ((imageLink.rel == 'lightbox')){
370             // if image is NOT part of a set, add single image to imageArray
371             this.imageArray.push([imageLink.href, imageLink.title]);         
372         } else {
373             // if image is part of a set..
374             this.imageArray = 
375                 $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
376                 collect(function(anchor){ return [anchor.href, anchor.title]; }).
377                 uniq();
378             
379             while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
380         }
381         */
382         var s = Roo.get(document).getScroll();
383         
384         // calculate top and left offset for the lightbox 
385         // weird.. why / 10?
386         var lightboxTop = s.top + (Roo.lib.Dom.getViewHeight() / 10);
387         var lightboxLeft = s.left
388         this.lightbox.setStyle({ 
389             top: lightboxTop + 'px', 
390             left: lightboxLeft + 'px' ,
391             zIndex : Roo.get(document.body)._mask.getStyle('zIndex') * 1.1
392         })
393         //console.log("show lightbox");
394         this.lightbox.show();
395         
396         
397         
398         this.changeImage(imageNum);
399     },
400
401     //
402     //  changeImage()
403     //  Hide most elements and preload image in preparation for resizing image container.
404     //
405     changeImage: function(imageNum) {   
406         
407         this.activeImage = imageNum; // update global var
408
409         // hide elements during transition
410         if (this.animate) {
411             this.loading.setStyle({
412                 zIndex : Roo.get(document.body)._mask.getStyle('zIndex') * 1.2
413             });
414             this.loading.show();
415             this.loadingLink.setX( (Roo.lib.Dom.getViewWidth() / 2) - 16);
416             //this.loadingLink.show();
417             // center the loading?
418             
419         }
420         
421         this.hoverNav.hide();
422         this.prevLink.hide();
423         this.nextLink.hide();
424                 // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
425         this.imageDataContainer.setStyle({opacity: .0001});
426         this.numberDisplay.hide();
427         
428         var imgPreloader =  Roo.DomHelper.append(document.body, { tag: 'img' } , true);
429         // once image is preloaded, resize image container
430
431         
432         imgPreloader.on('load', function() {
433             
434             this.lightboxImage.dom.src = this.imageArray[this.activeImage].dom.href;
435             
436             this.resizeImageContainer(imgPreloader.getWidth(), imgPreloader.getHeight());
437             imgPreloader.remove();
438         }, this);
439         imgPreloader.dom.src = this.imageArray[this.activeImage].dom.href;
440     },
441
442     //
443     //  resizeImageContainer()
444     //
445     resizeImageContainer: function(imgWidth, imgHeight) {
446
447         // make sure we have some sensible sizes..
448         imgWidth = Math.max(50, imgWidth);
449         imgHeight = Math.max(50, imgHeight);
450         
451         // get current width and height
452         var widthCurrent  = this.outerImageContainer.getWidth();
453         var heightCurrent = this.outerImageContainer.getHeight();
454         
455         //fixme need better calcs.
456         var w = window;
457         var ww = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
458         var wh = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
459         
460         ww -= 150;
461         wh -= 150;
462         // get new width and height
463         var bs =  this.borderSize * 2;
464         
465         var widthNew  =  imgWidth  + bs;
466         var heightNew =  imgHeight + bs;
467         
468         if (widthNew > ww || heightNew > wh) {
469             // bigger than window.
470             // scale here... - bit nasty..
471             var rescale = 1.1 * Math.max( widthNew / ww , heightNew  / wh);
472              //console.log(rescale);
473             imgWidth = Math.floor(imgWidth / rescale);
474             imgHeight = Math.floor(imgHeight / rescale);
475             widthNew  =  imgWidth  + bs;
476             heightNew =  imgHeight + bs;
477                     
478             
479         }
480         
481         this.lightboxImage.set( { width : imgWidth, height : imgHeight });
482         
483         
484         // scalars based on change from old to new
485         var xScale = (widthNew  / widthCurrent)  * 100;
486         var yScale = (heightNew / heightCurrent) * 100;
487
488         // calculate size difference between new and old image, and resize if necessary
489         var wDiff = widthCurrent - widthNew;
490         var hDiff = heightCurrent - heightNew;
491         
492          
493         this.outerImageContainer.animate(
494             { width: {to: widthNew}, height: {to: heightNew} },
495             this.resizeDuration,
496             null, // on complete
497             'easeOut', // easing
498             'run' // effect
499         
500         )        
501        
502         
503         // if new and old image are same size and no scaling transition is necessary, 
504         // do a quick pause to prevent image flicker.
505         var timeout = 0;
506         if ((hDiff == 0) && (wDiff == 0)){
507             timeout = 100;
508             if (Roo.isIE) timeout = 250;   
509         }
510
511         (function(){
512             this.prevLink.setStyle({ height: imgHeight + 'px' });
513             this.nextLink.setStyle({ height: imgHeight + 'px' });
514             this.imageDataContainer.setStyle({ width: widthNew + 'px'}); // the text area..
515             this.showImage();
516         }).defer(timeout / 1000, this);
517     },
518     
519     //
520     //  showImage()
521     //  Display image and begin preloading neighbors.
522     //
523     showImage: function(){
524         
525         this.loading.hide();
526         //this.loadingLink.hide();
527         var _this=  this;
528         this.lightboxImage.animate( 
529             {
530                 opacity : {  to: 1.0 }
531             },
532             this.resizeDuration,
533             function(){ 
534                 _this.updateDetails(); 
535             }
536             
537         );
538         this.preloadNeighborImages();
539     },
540
541     //
542     //  updateDetails()
543     //  Display caption, image number, and bottom nav.
544     //
545     updateDetails: function() {
546     
547         // if caption is not null
548         if (this.imageArray[this.activeImage].dom.title  != ""){
549             this.caption.update(this.imageArray[this.activeImage].dom.title);
550             this.caption.show();
551         }
552         
553         // if image is part of set display 'Image x of x' 
554         if (this.imageArray.length > 1){
555             this.numberDisplay.update(
556                 this.labelImage + ' ' + (this.activeImage + 1) + ' ' + this.labelOf + '  ' + this.imageArray.length)
557             this.numberDisplay.show();
558         }
559         var _this = this;
560         this.imageDataContainer.animate(
561             {
562                 //slide down ?: , from: 0.0, to: 1.0 
563                 opacity :  {  to: 1.0 }
564             },
565             this.resizeDuration,
566             function() {
567                         // update overlay size and update nav
568                         //var arrayPageSize = this.getPageSize();
569                         //this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
570                         _this.updateNav();
571             }
572              
573         );
574     },
575
576     //
577     //  updateNav()
578     //  Display appropriate previous and next hover navigation.
579     //
580     updateNav: function() {
581
582         this.hoverNav.show();               
583
584         // if not first image in set, display prev image button
585         if (this.activeImage > 0) this.prevLink.show();
586
587         // if not last image in set, display next image button
588         if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show();
589         
590         this.enableKeyboardNav();
591     },
592
593     //
594     //  enableKeyboardNav()
595     //
596     enableKeyboardNav: function() {
597         Roo.get(document.body).on('keydown', this.keyboardAction, this); 
598     },
599
600     //
601     //  disableKeyboardNav()
602     //
603     disableKeyboardNav: function() {
604         Roo.get(document.body).un('keydown', this.keyboardAction, this); 
605     },
606
607     //
608     //  keyboardAction()
609     //
610     keyboardAction: function(event) {
611         var keycode = event.keyCode;
612
613         var escapeKey;
614         if (event.DOM_VK_ESCAPE) {  // mozilla
615             escapeKey = event.DOM_VK_ESCAPE;
616         } else { // ie
617             escapeKey = 27;
618         }
619
620         var key = String.fromCharCode(keycode).toLowerCase();
621         
622         if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
623             this.end();
624         } else if ((key == 'p') || (keycode == 37)){ // display previous image
625             if (this.activeImage != 0){
626                 this.disableKeyboardNav();
627                 this.changeImage(this.activeImage - 1);
628             }
629         } else if ((key == 'n') || (keycode == 39)){ // display next image
630             if (this.activeImage != (this.imageArray.length - 1)){
631                 this.disableKeyboardNav();
632                 this.changeImage(this.activeImage + 1);
633             }
634         }
635     },
636
637     //
638     //  preloadNeighborImages()
639     //  Preload previous and next images.
640     //
641     preloadNeighborImages: function(){
642         var preloadNextImage, preloadPrevImage;
643         if (this.imageArray.length > this.activeImage + 1){
644             preloadNextImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
645             preloadNextImage.on('load', function() { preloadNextImage.remove() });
646             preloadNextImage.dom.src = this.imageArray[this.activeImage + 1].dom.href;
647         }
648         if (this.activeImage > 0){
649             preloadPrevImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
650             preloadPrevImage.on('load', function() { preloadPrevImage.remove() });
651             preloadPrevImage.dom.src = this.imageArray[this.activeImage - 1].dom.href;
652         }
653     
654     },
655
656     //
657     //  end()
658     //
659     end: function() {
660         this.disableKeyboardNav();
661         //console.log('lightbox hide');
662         this.lightbox.hide();
663         this.loading.hide();
664         Roo.get(document.body).unmask();
665         // show all the objects that cause problems..
666         //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
667     }
668
669      
670 });
671