/*
 * Image gallery functionality 
 */

function imageGallery(data){
	
	var gallery = this;
	
	this.identifier = '#gallery_' + data.id;
    this.imageSrcs = data.imageSrcs || [];
    this.imageDescs = data.imageDescs || '';	
	this.indexPos = 0;
    this.mainImageContainer = $$(this.identifier + ' div.mainImage')[0];
    this.mainImage = this.mainImageContainer.getElement('img');	
    this.thumbnails = $$(this.identifier + ' div.thumbnails a');    
    this.tnImages = $$(this.identifier + ' div.thumbnails a img');
    
	this.loadedImages = new Asset.images(this.imageSrcs, {
		onProgress : function(i){			
			
			if (i < gallery.tnImages.length) {
				this.alt = gallery.tnImages[i].alt || "";				
			}			
		},
		onComplete: function() {		    
		    new Fx.Styles(gallery.mainImage, {
				duration: 250,
				wait: false
			}).start({'opacity': [0,1]});
		    gallery.thumbnails[0].addClass("selected");		    
		}
	});
   									
    this.mainImageDimensions = this.mainImage.getSize();
    this.imageCaption = $$(this.identifier + ' .imageCaption p')[0];
    this.tnContainer = $$(this.identifier + ' div.thumbnails')[0];
    this.tnContainerSize = this.tnContainer.getSize().size;	
	this.sliders = [];
	this.cyclers = $$(this.identifier + ' div.cycle');
	
	this.effects = {
        fx: function(el,seconds,unit){
            var seconds = seconds || 500;
            var unit = unit || 'px';
			return new Fx.Styles(el, {
				duration: seconds,
				wait: false,
				'unit': unit
			});		
        },
		
        scroll : new Fx.Scroll(this.tnContainer, {
            wait: false,
            duration: 500,							
            transition: Fx.Transitions.Quad.easeInOut
        }),
	
        fade : function(el,seconds){
            return new Fx.Style(el, 'opacity', {duration: seconds || 1000});							
        }
    }					
	
	this.init = function(){			
	    this.effects.scroll.toLeft();
	    this.addImageSliders();
	    this.addImageCyclers();
	    this.gotoStatus();
	    this.addEvents();       
    }
    
    this.addImageSliders = function(){						    
	    var prevSlider = new Element('div', {'class': 'imageArrow prev'}).inject(this.mainImageContainer,'top');	    
	    var nextSlider = new Element('div', {'class': 'imageArrow next'}).inject(this.mainImageContainer);
	    this.sliders.push(prevSlider.setStyle('height', this.mainImageDimensions.size.y), nextSlider.setStyle('height', this.mainImageDimensions.size.y));
    }
    
    this.addImageCyclers = function(){        
        this.cyclers[0].set({            
            'events': {
                'click': function(){ 
                    gallery.gotoPrevious();
                    gallery.gotoStatus(gallery.indexPos);                
                },
                
                'mouseover': function(){ 
                    this.addClass('onPrevHover');	
                },
                
                'mouseout' : function(){
                    this.removeClass('onPrevHover');	                
                }  
            },
            
            'styles': {
                'height': gallery.tnContainerSize.y
            },
            'title' : 'View previous image'
        });
        
         this.cyclers[1].set({            
            'events': {
                'click': function(){ 
                    gallery.gotoNext();
                    gallery.gotoStatus(gallery.indexPos);                
                },
                
                'mouseover': function(){ 
                    this.addClass('onNextHover');	
                },
                
                'mouseout' : function(){
                    this.removeClass('onNextHover');	                
                }
            },
            
            'styles': {
                'height': gallery.tnContainerSize.y
            },
            'title': 'View next image'
        });        
    }
						
	this.activateImage = function(indexPos){
	    var indexPos = indexPos || this.indexPos;	    
	    this.thumbnails.each(function(item){
	        item.effect('opacity').set(0.25);
	        if (item.hasClass('selected')) {
	            item.removeProperty('class');
	        }
	    });
	    var current = this.thumbnails[indexPos];
	    current.setProperty('class', 'selected');
	    current.effect('opacity').set(1);	    
	    this.loadImage(indexPos);
	    this.loadCaption(this.imageDescs[indexPos] || this.tnImages[indexPos].alt || "");
	    this.gotoStatus();
    }
						
    this.loadImage = function(index){
        var currentImage = this.mainImageContainer.getElement('img');
		this.effects.fx(this.mainImageContainer, 500).start({
				'opacity': [1,0]
		}).chain(function(){
			this.start({				
				'height': [currentImage.height, gallery.loadedImages[index].height]
			});	
					
			gallery.sliders.each(function(item){
	            gallery.effects.fx(item, 500).start({	            
	                'height' : gallery.loadedImages[index].height	        
	            });	    	        
            });						
		}).chain(function() {			
	        gallery.mainImageContainer.replaceChild(gallery.loadedImages[index].setStyle('visibility','visible'), gallery.mainImageContainer.getElement('img') );
			gallery.effects.fx(gallery.mainImageContainer, 250).start({	            
                opacity: [0,1]
            });
		});  	    
    }   								
	
	this.loadCaption = function(text){
	    this.imageCaption.innerHTML = text;  
	}
		
	this.scroll = function(indexPos){
	    this.indexPos = indexPos;
	    var currImage = this.thumbnails[this.indexPos];
	    var posX = currImage.offsetLeft + currImage.offsetWidth;
							
	    if (posX < this.tnContainerSize.x) {
		    if (!this.indexPos) {
			    this.effects.scroll.toLeft();
		    }
		    return;
	    } else {												
		    if (this.thumbnails.length-1 == this.indexPos) {
			    this.effects.scroll.toRight();
			    return;
		    }	
		    
		    this.effects.scroll.scrollTo(posX-this.tnContainerSize.x);						
	    }					
    }
		
    this.gotoStatus = function(indexPos) {	
	    var arrTemp = [].merge(this.cyclers).merge(this.sliders);
	    var current = this.thumbnails[indexPos || this.indexPos];
	    var previous = current.getPrevious();
	    var next = current.getNext();	
	     
	    if (!previous && !next) {
	         arrTemp.each(function(item){
	            gallery.effects.fade(item).start(0);
	        });	 
	    }
	    
	    if (!previous && next){
			this.effects.fade(this.cyclers[0]).start(0);
			this.effects.fade(this.cyclers[1]).start(1);
		    this.effects.fade(this.sliders[0]).start(0);
		    this.effects.fade(this.sliders[1]).start(1);
	    } 
	    
	    if (!next && previous) {
		    this.effects.fade(this.cyclers[0]).start(1);
		    this.effects.fade(this.cyclers[1]).start(0);
		    this.effects.fade(this.sliders[0]).start(1);
		    this.effects.fade(this.sliders[1]).start(0);
	    }
	    
	    if (previous && next) {	
	        arrTemp.each(function(item){
	            gallery.effects.fade(item).set(1);
	        });					
	    }					
    }
		
    this.gotoPrevious = function(){
		var current = this.thumbnails[this.indexPos];					
	    var previous = current.getPrevious();						
	    this.indexPos = (previous) ? this.indexPos-1 : this.indexPos;
	    this.activateImage(this.indexPos);
	    this.scroll(this.indexPos)
    }
		
    this.gotoNext = function(){
		var current = this.thumbnails[this.indexPos];
	    var next = current.getNext();					
	    this.indexPos = (next) ? this.indexPos+1 : this.indexPos;
	    this.activateImage(this.indexPos);
	    this.scroll(this.indexPos)		            
    }
					
    this.addEvents = function(){	    
	    $each(this.thumbnails, function(item, index){						
		    item.addEvent('click', function(e){                 
		        e = new Event(e);
		        if (e.preventDefault) {
			        e.preventDefault();
		        } else {
			        e.returnValue = false;															 
		        }                
			    gallery.scroll(index);							
			    gallery.activateImage(index);
			    gallery.gotoStatus(index);
			    e.stop()
	         });
	    }); 
	  
	    $each(this.sliders, function(item, index){
		    			
		    item.addEvent('click', function(e){																				
			    (!index) ? gallery.gotoPrevious() : gallery.gotoNext();
			    gallery.gotoStatus(gallery.indexPos);						
	        });

		    item.addEvent('mouseover', function(e){	
			    gallery.effects.fx(this,250,"%").set({
				    'background-position' : (!index) ? '0 50' : '100 50'
				});
			});						
			
		    item.addEvent('mouseout', function(e){
			    gallery.effects.fx(this,500,"%").start({
				    'background-position' : (!index) ? '-250 50' : '250 50'
			    });		                
		    });	
					
	    });
    }
}