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