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