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     /**
58      * @cfg overlayOpacity {number} controls transparency of shadow overlay
59      */
60     overlayOpacity: 0.8,   
61     /**
62      * @cfg animate {boolean} toggles resizing animations
63      */
64     animate: true,          
65     /**
66      * @cfg resizeSpeed {number} controls the speed of the image 
67      * resizing animations (1=slowest and 10=fastest)
68      */
69     resizeSpeed: 9,
70     /**
71      * @cfg borderSize {number} if you adjust the padding in the CSS, 
72      * you will need to update this variable
73      */
74     borderSize: 10,
75     /**
76      * @cfg labelImage {string} When grouping images this is used to write: Image # of #.
77      * Change it for non-english localization
78      */
79         labelImage: "Image",
80         /**
81      * @cfg labelOf {string}  When grouping images this is used to write: Image # of #.
82      */
83     labelOf: "of",
84     
85     
86     
87     
88     /**
89      * List of images
90      */
91     imageArray: false,
92     
93     /**
94      * Current image.
95      * 
96      */
97      
98     activeImage: undefined,
99     
100     /**
101      * initialize() 
102      *  Constructor runs on completion of the DOM loading. Calls updateImageList and then
103      * the function inserts html at the bottom of the page which is used to display the shadow 
104      *  overlay and the image container.
105      * 
106      * 
107      */
108     initialize: function() {    
109         
110         this.updateImageList();
111         this.initializeCSS();
112         // TBD this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
113         this.resizeSpeed  = Math.min(this.resizeSpeed, 10);
114         this.resizeSpeed  = Math.max(this.resizeSpeed, 1);
115         
116             this.resizeDuration = this.animate ? ((11 - this.resizeSpeed) * 0.15) : 0;
117             this.overlayDuration = this.animate ? 0.2 : 0;  // shadow fade in/out duration
118
119         // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
120         // If animations are turned off, it will be hidden as to prevent a flicker of a
121         // white 250 by 250 box.
122         var size = (this.animate ? 250 : 1) + 'px';
123         var dh = Roo.DomHelper;
124         this.el = Roo.DomHelper.append(document.body, {
125                 html: 
126                   '<div class="roo-lightbox-overlay"></div>' +
127                   '<div class="roo-lightbox">' +
128                   '   <div class="outer-image-container">' +
129                   '       <div class="image-container">' +
130                   '           <img class="lightbox-image">' +
131                   '           <div style="" class="hover-nav">' +
132                   '               <a href="#" class="prev-link"></a>' +
133                   '               <a href="#" class="next-link"></a>' +
134                   '           </div>' +
135                   '           <div class="loading">' +
136                   '               <a href="#" class="loading-link">&nbsp;</a>' +
137                   '           </div>' +
138                   '       </div>' +
139                   '   </div>' +
140                   '   <div class="image-data-container">' +
141                   '       <div class="image-data">' +
142                   '           <div class="image-details">' +
143                   '               <span class="caption"></span>' +
144                   '               <span class="number-display"></span>' +
145                   '           </div>' +
146                   '           <div class="bottom-nav">' +
147                   '               <div href="#" class="bottom-nav-close"></div>' +
148                   '           </div>' +
149                   '       </div>' +
150                   '   </div>' +
151                  '</div>'
152             }, true);
153          
154          
155         
156         var th = this;
157         
158         var ids = 'roo-lightbox outer-image-container image-container ' + 
159             'lightbox-image hover-nav prev-link next-link loading loading-link ' + 
160             'image-data-container image-data image-details caption number-display ' +
161             'bottom-nav bottom-nav-close roo-lightbox-overlay';   
162             
163         Roo.each(ids.split(' '), 
164             function(id){ 
165                 var vid = id.replace(/\-/g,'');
166                 Roo.log(id);
167                 th[vid] = th.el.child('.'+id); 
168                 if (!th[vid]) {
169                     return;
170                 }
171                 
172                 th[vid].setVisibilityMode(Roo.Element.DISPLAY);
173             });
174         this.lightbox = this.roolightbox;
175
176         this.overlay = this.roolightboxoverlay;
177         this.overlay.hide();
178          
179                 this.lightbox.hide();
180         this.lightbox.on('click',  function(event) { 
181                  if (Roo.get(event.getTarget()).hasClass('roo-lightbox')) {
182                     this.end(); 
183                 }
184             }, this);
185             
186                 this.outerimagecontainer.setStyle({ width: size, height: size });
187         
188                 this.prevlink.on('click', 
189             function(event) { 
190                 event.stopEvent(); 
191                 this.changeImage(this.activeImage - 1); 
192             }, this);
193             
194                 this.nextlink.on('click', 
195             function(event) { 
196                 event.stopEvent(); 
197                 this.changeImage(this.activeImage + 1); 
198             },this);
199             
200                 this.loadinglink.on('click', 
201             function(event) { 
202                 event.stopEvent(); 
203                 this.end(); 
204             }, this);
205             
206                 this.bottomnavclose.on('click',  
207             function(event) { 
208                 event.stopEvent(); 
209                 this.end(); 
210             }, this);
211
212         this.overlay.on('click',  
213             function(event) { 
214                 event.stopEvent(); 
215                 this.end(); 
216             }, this);
217
218     },
219
220     initializeCSS: function() {    
221         if (typeof(Roo.ux.Lightbox.css) != 'undefined') {
222             return;
223         }
224         var rootURL = Roo.BLANK_IMAGE_URL.replace(/\/gray\/s\.gif$/, '');
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('+ rootURL  + '/ux/lightbox/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('+ rootURL  + '/ux/lightbox/close.gif) 0 0 no-repeat', 
264                 height:'26px',
265                 width:'26px',
266                 cursor:'pointer'
267             },
268             '.roo-lightbox .hover-nav' :{ 
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('+ rootURL  + '/ux/lightbox/prevlabel.gif) left 15% no-repeat'
289             },
290             '.roo-lightbox .next-link:hover, .roo-lightbox .next-link:visited:hover ' :{ 
291                 background:'url('+ rootURL  + '/ux/lightbox/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 .number-display' : { 'display': 'block', clear: 'left', 'padding-bottom': '1.0em'  } ,   
307             '.roo-lightbox .image-data .bottom-nav-close' : {  'float': 'right',  'padding-bottom': '0.7em','outline': 'none'} ,
308             '.roo-lightbox-overlay' : {
309                 'background-color': 'black',
310                 height: '500px',
311                 left: '0px',
312                 position: 'absolute',
313                 top: '0px',
314                 width: '100%',
315                 'z-index': '90'
316             }
317         });
318     },
319
320
321     
322     /**
323      * updateImageList()
324      * Loops through anchor tags looking for 'lightbox' references and applies onclick
325      * events to appropriate links. You can rerun after dynamically adding images w/ajax.
326      * 
327      */
328     updateImageList: function() {   
329         this.updateImageList = Roo.emptyFn;
330         if (this.imageArray.length) {
331             return;
332         }
333         Roo.each(Roo.DomQuery.select('a[rel^=lightbox]'), function(e) {
334             this.imageArray.push(Roo.get(e));
335             Roo.get(e).on('click', (function(event, tg, tga,tgb) {
336                
337              
338                 event.stopEvent();
339                 this.start(tgb);
340             }).createDelegate(this, [e], true));
341         }, this)
342         
343     },
344     
345     /**
346     * start()
347     *  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
348     */
349     start: function(imageLink) {
350         /*
351         // hide all the objects that cause problems..
352         $$('select', 'object', 'embed').each(
353             function(node){ 
354             node.style.visibility = 'hidden' }
355         );
356         */
357         // stretch overlay to fill page and fade in
358         //var arrayPageSize = this.getPageSize();
359         
360         this.overlay.setHeight(Roo.lib.Dom.getDocumentHeight()) ;
361         this.overlay.setWidth(Roo.lib.Dom.getDocumentWidth());
362         this.overlay.fadeIn({
363                 endOpacity: this.overlayOpacity, 
364                 easing: 'easeOut',
365                 duration: this.overlayDuration
366         });
367          
368         //this.imageArray = [];
369         var imageNum = 0;       
370         
371         if (imageLink) {
372             imageLink = Roo.get(imageLink);
373             //console.log(imageLink.id);
374             Roo.each(this.imageArray, function (e, i) {
375               //  console.log(e.id);
376                 if (e.id == imageLink.id) {
377                     imageNum = i;
378                 }
379             });
380         }
381         
382         // let's assume the constructor sorts out the list of images..
383         /*
384         if ((imageLink.rel == 'lightbox')){
385             // if image is NOT part of a set, add single image to imageArray
386             this.imageArray.push([imageLink.href, imageLink.title]);         
387         } else {
388             // if image is part of a set..
389             this.imageArray = 
390                 $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
391                 collect(function(anchor){ return [anchor.href, anchor.title]; }).
392                 uniq();
393             
394             while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
395         }
396         */
397         var s = Roo.get(document).getScroll();
398         
399         // calculate top and left offset for the lightbox 
400         // weird.. why / 10?
401         var lightboxTop = s.top + (Roo.lib.Dom.getViewHeight() / 10);
402         var lightboxLeft = s.left
403         this.lightbox.setStyle({ 
404             top: lightboxTop + 'px', 
405             left: lightboxLeft + 'px' ,
406             zIndex : 1000
407         })
408         //console.log("show lightbox");
409         this.lightbox.show();
410         
411         
412         
413         this.changeImage(imageNum);
414     },
415
416     //
417     //  changeImage()
418     //  Hide most elements and preload image in preparation for resizing image container.
419     //
420     changeImage: function(imageNum) {   
421         
422         this.activeImage = imageNum; // update global var
423
424         // hide elements during transition
425         if (this.animate) {
426             this.loading.setStyle({
427                 zIndex :1200
428             });
429             this.loading.show();
430             this.loadinglink.setX( (Roo.lib.Dom.getViewWidth() / 2) - 16);
431             //this.loadingLink.show();
432             // center the loading?
433             
434         }
435         
436         this.hovernav.hide();
437         this.prevlink.hide();
438         this.nextlink.hide();
439                 // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
440         this.imagedatacontainer.setStyle({opacity: .0001});
441         this.numberdisplay.hide();
442         
443         var imgPreloader =  Roo.DomHelper.append(document.body, { tag: 'img' } , true);
444         // once image is preloaded, resize image container
445
446         imgPreloader.on('load', function() {
447             
448             this.lightboximage.dom.src = this.imageArray[this.activeImage].dom.href || this.imageArray[this.activeImage].dom.src;
449             
450             this.resizeImageContainer(imgPreloader.getWidth(), imgPreloader.getHeight());
451             imgPreloader.remove();
452         }, this);
453         imgPreloader.dom.src = this.imageArray[this.activeImage].dom.href || this.imageArray[this.activeImage].dom.src;
454     },
455
456     
457     
458     //
459     //  resizeImageContainer()
460     //
461     resizeImageContainer: function(imgWidth, imgHeight) {
462
463         // make sure we have some sensible sizes..
464         imgWidth = Math.max(50, imgWidth);
465         imgHeight = Math.max(50, imgHeight);
466         
467         // get current width and height
468         var widthCurrent  = this.outerimagecontainer.getWidth();
469         var heightCurrent = this.outerimagecontainer.getHeight();
470         
471         //fixme need better calcs.
472         var w = window;
473         var ww = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
474         var wh = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
475         
476         ww -= 150;
477         wh -= 150;
478         // get new width and height
479         var bs =  this.borderSize * 2;
480         
481         var widthNew  =  imgWidth  + bs;
482         var heightNew =  imgHeight + bs;
483         
484         if (widthNew > ww || heightNew > wh) {
485             // bigger than window.
486             // scale here... - bit nasty..
487             var rescale = 1.1 * Math.max( widthNew / ww , heightNew  / wh);
488              //console.log(rescale);
489             imgWidth = Math.floor(imgWidth / rescale);
490             imgHeight = Math.floor(imgHeight / rescale);
491             widthNew  =  imgWidth  + bs;
492             heightNew =  imgHeight + bs;
493                     
494             
495         }
496         
497         this.lightboximage.set( { width : imgWidth, height : imgHeight });
498         
499         
500         // scalars based on change from old to new
501         var xScale = (widthNew  / widthCurrent)  * 100;
502         var yScale = (heightNew / heightCurrent) * 100;
503
504         // calculate size difference between new and old image, and resize if necessary
505         var wDiff = widthCurrent - widthNew;
506         var hDiff = heightCurrent - heightNew;
507         
508          
509         this.outerimagecontainer.animate(
510             { width: {to: widthNew}, height: {to: heightNew} },
511             this.resizeDuration,
512             null, // on complete
513             'easeOut', // easing
514             'run' // effect
515         
516         )        
517        
518         
519         // if new and old image are same size and no scaling transition is necessary, 
520         // do a quick pause to prevent image flicker.
521         var timeout = 0;
522         if ((hDiff == 0) && (wDiff == 0)){
523             timeout = 100;
524             if (Roo.isIE) timeout = 250;   
525         }
526
527         (function(){
528             this.prevlink.setStyle({ height: imgHeight + 'px' });
529             this.nextlink.setStyle({ height: imgHeight + 'px' });
530             this.imagedatacontainer.setStyle({ width: widthNew + 'px'}); // the text area..
531             this.showImage();
532         }).defer(timeout / 1000, this);
533     },
534     
535     //
536     //  showImage()
537     //  Display image and begin preloading neighbors.
538     //
539     showImage: function(){
540         
541         this.loading.hide();
542         //this.loadingLink.hide();
543         var _this=  this;
544         this.lightboximage.animate( 
545             {
546                 opacity : {  to: 1.0 }
547             },
548             this.resizeDuration,
549             function(){ 
550                 _this.updateDetails(); 
551             }
552             
553         );
554         this.preloadNeighborImages();
555     },
556
557     //
558     //  updateDetails()
559     //  Display caption, image number, and bottom nav.
560     //
561     updateDetails: function() {
562     
563         // if caption is not null
564         if (this.imageArray[this.activeImage].dom.title  != ""){
565             this.caption.update(this.imageArray[this.activeImage].dom.title);
566             this.caption.show();
567         }
568         
569         // if image is part of set display 'Image x of x' 
570         if (this.imageArray.length > 1){
571             this.numberdisplay.update(
572                 this.labelImage + ' ' + (this.activeImage + 1) + ' ' + this.labelOf + '  ' + this.imageArray.length)
573             this.numberdisplay.show();
574         }
575         var _this = this;
576         this.imagedatacontainer.animate(
577             {
578                 //slide down ?: , from: 0.0, to: 1.0 
579                 opacity :  {  to: 1.0 }
580             },
581             this.resizeDuration,
582             function() {
583                         // update overlay size and update nav
584                         //var arrayPageSize = this.getPageSize();
585                         //this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
586                         _this.updateNav();
587             }
588              
589         );
590     },
591
592     //
593     //  updateNav()
594     //  Display appropriate previous and next hover navigation.
595     //
596     updateNav: function() {
597
598         this.hovernav.show();               
599
600         // if not first image in set, display prev image button
601         if (this.activeImage > 0) this.prevlink.show();
602
603         // if not last image in set, display next image button
604         if (this.activeImage < (this.imageArray.length - 1)) this.nextlink.show();
605         
606         this.enableKeyboardNav();
607     },
608
609     //
610     //  enableKeyboardNav()
611     //
612     enableKeyboardNav: function() {
613         Roo.get(document.body).on('keydown', this.keyboardAction, this); 
614     },
615
616     //
617     //  disableKeyboardNav()
618     //
619     disableKeyboardNav: function() {
620         Roo.get(document.body).un('keydown', this.keyboardAction, this); 
621     },
622
623     //
624     //  keyboardAction()
625     //
626     keyboardAction: function(event)
627     {
628         var keycode = event.keyCode;
629
630         var escapeKey;
631         if (event.DOM_VK_ESCAPE) {  // mozilla
632             escapeKey = event.DOM_VK_ESCAPE;
633         } else { // ie
634             escapeKey = 27;
635         }
636
637         var key = String.fromCharCode(keycode).toLowerCase();
638         
639         if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
640             this.end();
641         } else if ((key == 'p') || (keycode == 37)){ // display previous image
642             if (this.activeImage != 0){
643                 this.disableKeyboardNav();
644                 this.changeImage(this.activeImage - 1);
645             }
646         } else if ((key == 'n') || (keycode == 39)){ // display next image
647             if (this.activeImage != (this.imageArray.length - 1)){
648                 this.disableKeyboardNav();
649                 this.changeImage(this.activeImage + 1);
650             }
651         }
652     },
653
654     //
655     //  preloadNeighborImages()
656     //  Preload previous and next images.
657     //
658     preloadNeighborImages: function(){
659         var preloadNextImage, preloadPrevImage;
660         if (this.imageArray.length > this.activeImage + 1){
661             preloadNextImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
662             preloadNextImage.on('load', function() { preloadNextImage.remove() });
663             preloadNextImage.dom.src = this.imageArray[this.activeImage + 1].dom.href || this.imageArray[this.activeImage + 1 ].dom.src;;
664         }
665         if (this.activeImage > 0){
666             preloadPrevImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
667             preloadPrevImage.on('load', function() { preloadPrevImage.remove() });
668             preloadPrevImage.dom.src = this.imageArray[this.activeImage - 1].dom.href || this.imageArray[this.activeImage - 1].dom.src;
669         }
670     
671     },
672
673     //
674     //  end()
675     //
676     end: function() {
677         this.disableKeyboardNav();
678         //console.log('lightbox hide');
679         this.lightbox.hide();
680         this.loading.hide();
681         this.overlay.hide();
682         Roo.get(document.body).unmask();
683         // show all the objects that cause problems..
684         //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
685     }
686
687      
688 });
689