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