use scrollheight , and resize
[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      * Array of images Roo.Elements (which should be images)
90      * properties can be 
91      */
92     imageArray: false,
93     
94     /**
95      * Current image.
96      * 
97      */
98      
99     activeImage: undefined,
100     
101     /**
102      * initialize() 
103      *  Constructor runs on completion of the DOM loading. Calls updateImageList and then
104      * the function inserts html at the bottom of the page which is used to display the shadow 
105      *  overlay and the image container.
106      * 
107      * 
108      */
109     initialize: function() {    
110         
111         this.updateImageList();
112         this.initializeCSS();
113         // TBD this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
114         this.resizeSpeed  = Math.min(this.resizeSpeed, 10);
115         this.resizeSpeed  = Math.max(this.resizeSpeed, 1);
116         
117         this.resizeDuration = this.animate ? ((11 - this.resizeSpeed) * 0.15) : 0;
118         this.overlayDuration = this.animate ? 0.2 : 0;  // shadow fade in/out duration
119
120         // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
121         // If animations are turned off, it will be hidden as to prevent a flicker of a
122         // white 250 by 250 box.
123         var size = (this.animate ? 250 : 1) + 'px';
124         var dh = Roo.DomHelper;
125         this.el = Roo.DomHelper.append(document.body, {
126                 html: 
127                   '<div class="roo-lightbox-overlay"></div>' +
128                   '<div class="roo-lightbox">' +
129                   '   <div class="outer-image-container">' +
130                   '       <div class="image-container">' +
131                   '           <img class="lightbox-image">' +
132                   '           <div style="" class="hover-nav">' +
133                   '               <a href="#" class="prev-link"></a>' +
134                   '               <a href="#" class="next-link"></a>' +
135                   '           </div>' +
136                   '           <div class="loading">' +
137                   '               <a href="#" class="loading-link">&nbsp;</a>' +
138                   '           </div>' +
139                   '       </div>' +
140                   '   </div>' +
141                   '   <div class="image-data-container">' +
142                   '       <div class="image-data">' +
143                   '           <div class="image-details">' +
144                   '               <span class="caption"></span>' +
145                   '               <span class="number-display"></span>' +
146                   '           </div>' +
147                   '           <div class="bottom-nav">' +
148                   '               <div href="#" class="bottom-nav-close"></div>' +
149                   '           </div>' +
150                   '       </div>' +
151                   '   </div>' +
152                  '</div>'
153             }, true);
154          
155          
156         
157         var th = this;
158         
159         var ids = 'roo-lightbox outer-image-container image-container ' + 
160             'lightbox-image hover-nav prev-link next-link loading loading-link ' + 
161             'image-data-container image-data image-details caption number-display ' +
162             'bottom-nav bottom-nav-close roo-lightbox-overlay';   
163             
164         Roo.each(ids.split(' '), 
165             function(id){ 
166                 var vid = id.replace(/\-/g,'');
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': '999'
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.onResize();
361         if (!this.resizer) {
362             this.resizer = Roo.EventManager.onWindowResize(this.onResize, this, true);;
363         }
364         
365         
366         this.overlay.fadeIn({
367                 endOpacity: this.overlayOpacity, 
368                 easing: 'easeOut',
369                 duration: this.overlayDuration
370         });
371          
372         //this.imageArray = [];
373         var imageNum = 0;       
374         
375         if (imageLink) {
376             imageLink = Roo.get(imageLink);
377             //console.log(imageLink.id);
378             Roo.each(this.imageArray, function (e, i) {
379               //  console.log(e.id);
380                 if (e.id == imageLink.id) {
381                     imageNum = i;
382                 }
383             });
384         }
385          
386         // let's assume the constructor sorts out the list of images..
387         /*
388         if ((imageLink.rel == 'lightbox')){
389             // if image is NOT part of a set, add single image to imageArray
390             this.imageArray.push([imageLink.href, imageLink.title]);         
391         } else {
392             // if image is part of a set..
393             this.imageArray = 
394                 $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
395                 collect(function(anchor){ return [anchor.href, anchor.title]; }).
396                 uniq();
397             
398             while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
399         }
400         */
401         var s = Roo.get(document).getScroll();
402          // calculate top and left offset for the lightbox 
403         // weird.. why / 10?
404         
405         //var lightboxTop = s.top + (Roo.lib.Dom.getViewHeight() / 10);
406         var lightboxTop = (Roo.lib.Dom.getViewHeight() / 10) + document.body.scrollTop;
407         var lightboxLeft = s.left;
408         this.lightbox.setStyle({ 
409             top: lightboxTop + 'px', 
410             left: lightboxLeft + 'px' ,
411             zIndex : 1000
412         });
413         //console.log("show lightbox");
414         this.lightbox.show();
415         
416         
417         this.changeImage(imageNum);
418     },
419
420     onResize : function()
421     {
422         this.overlay.setHeight(Roo.lib.Dom.getDocumentHeight()) ;
423         this.overlay.setWidth(Roo.lib.Dom.getDocumentWidth());
424     },
425     //
426     //  changeImage()
427     //  Hide most elements and preload image in preparation for resizing image container.
428     //
429     changeImage: function(imageNum) {   
430         
431         this.activeImage = imageNum; // update global var
432
433         // hide elements during transition
434         if (this.animate) {
435             this.loading.setStyle({
436                 zIndex :1200
437             });
438             this.loading.show();
439             this.loadinglink.setX( (Roo.lib.Dom.getViewWidth() / 2) - 16);
440             //this.loadingLink.show();
441             // center the loading?
442             
443         }
444         
445         this.hovernav.hide();
446         this.prevlink.hide();
447         this.nextlink.hide();
448                 // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
449         this.imagedatacontainer.setStyle({opacity: .0001});
450         this.numberdisplay.hide();
451         
452         var imgPreloader =  Roo.DomHelper.append(document.body, { tag: 'img' } , true);
453         // once image is preloaded, resize image container
454
455         imgPreloader.on('load', function() {
456             
457             this.lightboximage.dom.src = this.imageArray[this.activeImage].srcfull  ||  this.imageArray[this.activeImage].href || 
458                 this.imageArray[this.activeImage].dom.href || this.imageArray[this.activeImage].dom.src;
459             
460             this.resizeImageContainer(this.imageArray[this.activeImage].dom.lwidth || imgPreloader.getWidth(),
461                                       this.imageArray[this.activeImage].dom.lheight || imgPreloader.getHeight());
462             imgPreloader.remove();
463         }, this);
464         Roo.log(this.imageArray[this.activeImage]);
465         imgPreloader.dom.src = this.imageArray[this.activeImage].srcfull || this.imageArray[this.activeImage].href || 
466             this.imageArray[this.activeImage].dom.href ||  this.imageArray[this.activeImage].dom.src;
467     },
468
469     
470     
471     //
472     //  resizeImageContainer()
473     //
474     resizeImageContainer: function(imgWidth, imgHeight) {
475
476         // make sure we have some sensible sizes..
477         imgWidth = Math.max(50, imgWidth);
478         imgHeight = Math.max(50, imgHeight);
479         
480         // get current width and height
481         var widthCurrent  = this.outerimagecontainer.getWidth();
482         var heightCurrent = this.outerimagecontainer.getHeight();
483         
484         //fixme need better calcs.
485         var w = window;
486         var ww = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
487         var wh = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
488         
489         ww -= 150;
490         wh -= 150;
491         
492         // get new width and height
493         var bs =  this.borderSize * 2;
494         
495         var widthNew  =  imgWidth  + bs;
496         var heightNew =  imgHeight + bs;
497         
498         if (widthNew > ww || heightNew > wh) {
499             // bigger than window.
500             // scale here... - bit nasty..
501             var rescale = 1.1 * Math.max( widthNew / ww , heightNew  / wh);
502              //console.log(rescale);
503             imgWidth = Math.floor(imgWidth / rescale);
504             imgHeight = Math.floor(imgHeight / rescale);
505             widthNew  =  imgWidth  + bs;
506             heightNew =  imgHeight + bs;
507                     
508             
509         }
510         
511         this.lightboximage.set( { width : imgWidth, height : imgHeight });
512         
513         
514         // scalars based on change from old to new
515         var xScale = (widthNew  / widthCurrent)  * 100;
516         var yScale = (heightNew / heightCurrent) * 100;
517
518         // calculate size difference between new and old image, and resize if necessary
519         var wDiff = widthCurrent - widthNew;
520         var hDiff = heightCurrent - heightNew;
521         
522          
523         this.outerimagecontainer.animate(
524             { width: {to: widthNew}, height: {to: heightNew} },
525             this.resizeDuration,
526             null, // on complete
527             'easeOut', // easing
528             'run' // effect
529         
530         );  
531        
532         
533         // if new and old image are same size and no scaling transition is necessary, 
534         // do a quick pause to prevent image flicker.
535         var timeout = 0;
536         if ((hDiff == 0) && (wDiff == 0)){
537             timeout = 100;
538             if (Roo.isIE) {
539                 timeout = 250;
540             }
541         }
542
543         (function(){
544             this.prevlink.setStyle({ height: imgHeight + 'px' });
545             this.nextlink.setStyle({ height: imgHeight + 'px' });
546             this.imagedatacontainer.setStyle({ width: widthNew + 'px'}); // the text area..
547             this.showImage();
548         }).defer(timeout / 1000, this);
549     },
550     
551     //
552     //  showImage()
553     //  Display image and begin preloading neighbors.
554     //
555     showImage: function(){
556         
557         this.loading.hide();
558         //this.loadingLink.hide();
559         var _this=  this;
560         this.lightboximage.animate( 
561             {
562                 opacity : {  to: 1.0 }
563             },
564             this.resizeDuration,
565             function(){ 
566                 _this.updateDetails(); 
567             }
568             
569         );
570         this.preloadNeighborImages();
571     },
572
573     //
574     //  updateDetails()
575     //  Display caption, image number, and bottom nav.
576     //
577     updateDetails: function() {
578     
579         // if caption is not null
580         if (this.imageArray[this.activeImage].dom.title  != ""){
581             this.caption.update(this.imageArray[this.activeImage].dom.title);
582             this.caption.show();
583         }
584         
585         // if image is part of set display 'Image x of x' 
586         if (this.imageArray.length > 1){
587             this.numberdisplay.update(
588                 this.labelImage + ' ' + (this.activeImage + 1) + ' ' + this.labelOf + '  ' + this.imageArray.length);
589             this.numberdisplay.show();
590         }
591         var _this = this;
592         this.imagedatacontainer.animate(
593             {
594                 //slide down ?: , from: 0.0, to: 1.0 
595                 opacity :  {  to: 1.0 }
596             },
597             this.resizeDuration,
598             function() {
599                         // update overlay size and update nav
600                         //var arrayPageSize = this.getPageSize();
601                         //this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
602                         _this.updateNav();
603             }
604              
605         );
606     },
607
608     //
609     //  updateNav()
610     //  Display appropriate previous and next hover navigation.
611     //
612     updateNav: function() {
613
614         this.hovernav.show();               
615
616         // if not first image in set, display prev image button
617         if (this.activeImage > 0) {
618             this.prevlink.show();
619         }
620
621         // if not last image in set, display next image button
622         if (this.activeImage < (this.imageArray.length - 1)) {
623             this.nextlink.show();
624         }
625         
626         this.enableKeyboardNav();
627     },
628
629     //
630     //  enableKeyboardNav()
631     //
632     enableKeyboardNav: function() {
633         Roo.get(document.body).on('keydown', this.keyboardAction, this); 
634     },
635
636     //
637     //  disableKeyboardNav()
638     //
639     disableKeyboardNav: function() {
640         Roo.get(document.body).un('keydown', this.keyboardAction, this); 
641     },
642
643     //
644     //  keyboardAction()
645     //
646     keyboardAction: function(event)
647     {
648         var keycode = event.keyCode;
649
650         var escapeKey;
651         if (event.DOM_VK_ESCAPE) {  // mozilla
652             escapeKey = event.DOM_VK_ESCAPE;
653         } else { // ie
654             escapeKey = 27;
655         }
656
657         var key = String.fromCharCode(keycode).toLowerCase();
658         
659         if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
660             this.end();
661         } else if ((key == 'p') || (keycode == 37)){ // display previous image
662             if (this.activeImage != 0){
663                 this.disableKeyboardNav();
664                 this.changeImage(this.activeImage - 1);
665             }
666         } else if ((key == 'n') || (keycode == 39)){ // display next image
667             if (this.activeImage != (this.imageArray.length - 1)){
668                 this.disableKeyboardNav();
669                 this.changeImage(this.activeImage + 1);
670             }
671         }
672     },
673
674     //
675     //  preloadNeighborImages()
676     //  Preload previous and next images.
677     //
678     preloadNeighborImages: function(){
679         var preloadNextImage, preloadPrevImage;
680         if (this.imageArray.length > this.activeImage + 1){
681             preloadNextImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
682             preloadNextImage.on('load', function() { preloadNextImage.remove() });
683             preloadNextImage.dom.src = this.imageArray[this.activeImage + 1].href ||
684                     this.imageArray[this.activeImage + 1].dom.href || this.imageArray[this.activeImage + 1 ].dom.src;;
685         }
686         if (this.activeImage > 0){
687             preloadPrevImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
688             preloadPrevImage.on('load', function() { preloadPrevImage.remove() });
689             preloadPrevImage.dom.src = this.imageArray[this.activeImage - 1].href || 
690                    this.imageArray[this.activeImage - 1].dom.href || this.imageArray[this.activeImage - 1].dom.src;
691         }
692     
693     },
694
695     //
696     //  end()
697     //
698     end: function() {
699         this.disableKeyboardNav();
700         //console.log('lightbox hide');
701         this.lightbox.hide();
702         this.loading.hide();
703         this.overlay.hide();
704         Roo.get(document.body).unmask();
705         // show all the objects that cause problems..
706         //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
707     }
708
709      
710 });
711