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