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