var ImageGallery = new Class({

    Implements: Options,
    
    options: {
        'data': []
    },
    
    zoomCount: 1,
    
    initialize: function (element, options)
    {
        this.setOptions(options);
        
        this.carousel = new ImageGallery.Carousel(element, options)
            .addEvent('click', this.show.bind(this));
        
        this.element = $(element).getParent('div.gallery');
    },
    
    show: function (item)
    {
        var fullimage = $(this.options.fullsizedImageId);
        if(fullimage == false)
        {
        	return false;
       	} 
        
       	
       	if('video' == this.options.data[item.retrieve('origin')].type)
       	{
       		var flashvars = {
             src: this.options.data[item.retrieve('origin')].full_src
        	};
        	var params = {
    		  allowfullscreen : true 
    		};
        	var so = swfobject.embedSWF("flash/videoPlayer.swf", this.options.fullsizedImageId, "462", "320", "9.0.0", "expressInstall.swf", flashvars, params);
       	}
       	else
       	{
	       	fullimage.src = this.options.data[item.retrieve('origin')].full_src;
       	}
       	
       	
       	var div_caption = $(this.options.captionArea);
       	var div_text = this.options.data[item.retrieve('origin')].caption 
       	if('' != this.options.data[item.retrieve('origin')].copyright)
       	{
       		div_text += '<br />Copyright: '+this.options.data[item.retrieve('origin')].copyright;
       	}
       	if(this.options.data[item.retrieve('origin')].download_link)
       	{
       		div_text += '<div id="mediathek"><p>'+this.options.data[item.retrieve('origin')].download_link+'</div></p>';
       	}
       	
       	div_caption.set('html', div_text);
    },
    
    zoom: function (item)
    {
        // fade+destroy the old one
        if ('element' === $type(this.zoomDiv))
        {
	        this.zoomDiv.fade(0);
	        (function ()
	        {
	            this.destroy();
	        }).delay(500, this.zoomDiv);
        }
        
        if (2 < ++this.zoomCount)
        {
            this.div_carousel.disabled = true;
        }
        
        var active = this.div_carousel.getActiveItem();
        var opt = this.options.data[active?active.retrieve('origin'):item.retrieve('origin')];
        if ('video' === opt.type)
        {
            var div = this.createZoomLayerVideo(opt);
        }
        else
        {
            var div = this.createZoomLayer(opt).inject(this.zoomDiv, 'after');
        }
        
        this.zoomDiv = div;
    },
    
    showAd: function ()
    {
        if (2 >= this.zoomCount)
        {
            return;
        }
        
        this.div_carousel.disabled = false;
        this.zoomCount = 0;
        
        // fade+destroy the old one
        if ('element' === $type(this.zoomDiv))
        {
            this.zoomDiv.fade(0);
            (function ()
            {
                this.destroy();
            }).delay(500, this.zoomDiv);
        }
        
        var div = new Element('div', {'class': 'zoom'}).setStyle('opacity', 0).inject(this.zoomDiv, 'after');
        new Element('iframe', {
            'src': this.options.adv,
            'frameborder': 0,
            'scrolling': 'no',
            'allowtransparency': 'true'
        }).inject(div).addEvent('load', function ()
        {
            this.fade(1);
        }.bind(div));
        
        this.zoomDiv = div;
    },
    
    createZoomLayer: function (opt)
    {
        var div = new Element('div', {'class': 'zoom'}).setStyle('opacity', 0);
        var container = new Element('div', {'class': 'container'}).inject(div);
        
        new Asset.image(opt.full_src, {
	        'onload': function ()
	        {
                this.fade(1);
	        }.bind(div)
        }).inject(container)
            .addEvent('click', this.div_carousel.scroll.bindWithEvent(this.div_carousel, 1));
        
        var cr = new Element('div', {'class': 'copyright'}).inject(div);
        if (opt.copyright && '' != opt.copyright)
        {
            cr.appendText('Copyright: ' + opt.copyright);
        }
        
        if (opt.caption && '' != opt.caption)
        {
            new Element('div', {'class': 'caption'}).inject(div).appendText(opt.caption);
        }
        
        return div;
    },
    
    createZoomLayerVideo: function (opt)
    {
        var zd;
        if (this.zoomDiv && (zd = $(this.zoomDiv)))
        {
            if (zd.destroy)
            {
                zd.destroy();
            }
            else
            {
                // silly ie fix
                zd.parentNode.removeChild(zd);
            }
        }

	this.div.addClass('video');
        
        var id = 'video_' + $random(1000, 9999);
        var div = new Element('div', {'class': 'zoom'}).inject(this.div);

        // the layer for the flash movie
        new Element('div', {'id': id, 'class': 'pre-video'}).inject(div);
        
        var flashvars = {
            file: opt.full_src,
            image: opt.preview_src,
            width: 400,
            height: 320,
            preroll: escape('http://ad.doubleclick.net/adx/90elf.smartclip/;ptile=1;sz=400x320;dcmt=text/html;ord=' + new Date().getTime())
        };
        var params = {
            allowScriptAccess: 'always',
            allowFullScreen: 'true'
        };
        swfobject.embedSWF("flash/jwplayer.swf", id, "400", "320", "9.0.0", "flash/TeamLineup/expressInstall.swf", flashvars, params);
        
        var cr = new Element('div', {'class': 'copyright'}).inject(div);
        if (opt.copyright && '' != opt.copyright)
        {
            cr.appendText('Copyright: ' + opt.copyright);
        }
        
        if (opt.caption && '' != opt.caption)
        {
            new Element('div', {'class': 'caption'}).inject(div).appendText(opt.caption);
        }
        
        this.zoomCount = 0;
        
        return div;
    },
    
    hide: function ()
    {
        if (this.div) this.div.fade(0);
        if (this.gallery) this.gallery.fade(0);
        if (this.modal) this.modal.fade(0);
        
        (function ()
        {
            if (this.div) this.div.destroy();
            if (this.modal) this.modal.destroy();
            if (this.gallery) this.gallery.destroy();
            
            delete this.div;
            delete this.modal;
            delete this.gallery;
        }).delay(500, this);
    }

});



ImageGallery.Carousel = new Class({
    
    Implements: [Options, Events],
    
    options: {
        'position': 0,
        'container': '',
        'scrollLeft': 'scroll_left',
        'scrollRight': 'scroll_right',
        'step': 5,
        'itemWidth': 85,
        'markActiveItem': false,
        'amount': false,
        'items': false,
        'scrollX': 0
    },
    
    initialize: function (element, options)
    {
        this.setOptions(options);
        
        this.options.scrollLeft  = $(this.options.scrollLeft)
            .addEvent('click', this.scroll.bindWithEvent(this, -this.options.step));
        this.options.scrollRight = $(this.options.scrollRight)
            .addEvent('click', this.scroll.bindWithEvent(this,  this.options.step));
        
        this.element = $(element);
        this.options.container = ($(this.options.container) || this.element.getParent());
        
        this.scrollFx = new Fx.Scroll(this.options.container);
        this.scrollFx.set(this.options.scrollX, 0);
        
        var children = this.element.getElements('li');
        
        if (!this.options.amount)
        {
            this.options.amount = children.length;
        }
        
        if (!this.options.items)
        {
            this.options.items = {};
	        $each(children, function (item, idx)
	        {
	            if (false === item.retrieve('origin', false))
	            {
	                item.store('origin', idx);
	            }
	            
	            this.options.items[idx] = item;
	        }, this);
        }
        
        $each(this.options.items, function (item, idx)
        {
            this.options.items[idx].addEvent('click', this.fire.bindWithEvent(this, item));
        }, this);
        
        if (4 < this.options.amount && this.options.markActiveItem)
        {
            this.getActiveItem().fade(0.7);
        }
    },
    
    fire: function (event, item)
    {
		new Event(event).stop();
		
        // scrolling is in progress
        if (this.disabled)
        {
            this.fireEvent('scrollDisabled');
            return;
        }
		
		// auto-scroll the clicked item into the middle
		var active = this.getActiveItem();
		if (4 < this.options.amount && active !== item && active.retrieve('origin') !== item.retrieve('origin'))
		{
            for (var i=this.options.position; this.options.items[i] && item != this.options.items[i]; i++);
            
            this.scroll(null, i - this.options.position - 2);
		}
		else
		{
		    this.fireEvent('afterScroll', item);
		}
		
		this.fireEvent.delay(500, this, ['click', item]);
    },
    
    scroll: function (event, step)
    {
        // we could be called manually
        if (event)
        {
            new Event(event).stop();
        }
        
        // scrolling is in progress
        if (this.disabled || 5 > this.options.amount)
        {
            if (this.disabled)
            {
                this.fireEvent('scrollDisabled');
            }
            
            return;
        }
        
        // we don't want to be interrupted
        this.disabled = true;
        
        if (this.options.markActiveItem)
        {
            this.getActiveItem().fade(1);
        }
        
        this.options.position += step;
        
        var scrollX = this.options.container.getScroll().x + (step * this.options.itemWidth);
        
        /**
         * scroll to the right
         */
        if (0 < step)
        {
            var len;
            if (5 > (len = this.options.items[this.options.position - 1].getAllNext('li').length))
	        {
	            var pos = this.element.getLast('li').retrieve('origin');
	            
	            /**
	             * insert new items at the end
	             */
	            var item;
	            for (var i=len; i<5; i++)
	            {
	                // wrap if we reach the end
	                if (++pos === this.options.amount)
	                {
	                    pos = 0;
	                }
	                
	                // extend our element so that the new items will fit
	                this.element.setStyle('width', this.options.itemWidth + this.element.getSize().x);
	                
	                // insert at the end and push onto item stack
	                this.options.items[this.options.position + i] = item = this.options.items[pos].clone().store('origin', pos).inject(this.element);
	                item.addEvent('click', this.fire.bindWithEvent(this, item));
	            }
	        }
        }
        /**
         * scroll to the left
         */
        else if (0 > this.options.position && !this.options.items[this.options.position])
        {
            /**
             * extend our element so that the new items will fit
             */
            this.element.setStyle('width', this.element.getSize().x + (this.options.itemWidth * Math.abs(step)));
            
            var pos = this.element.getFirst('li').retrieve('origin');
            
            var item;
            for (var i=Math.abs(step); i--;)
            {
                if (0 > --pos)
                {
                    pos = (this.options.amount - 1);
                }
                
                this.options.items[this.options.position + i] = item = this.options.items[pos].clone().store('origin', pos).inject(this.element.getFirst('li'), 'before');
                item.addEvent('click', this.fire.bindWithEvent(this, item));
                
                // we need fixiate the current scrolling width
                this.scrollFx.set(this.options.container.getScroll().x + this.options.itemWidth, 0);
            }
            
            scrollX = 0; 
        }
        
        /**
         * scroll into the desired direction
         */
        this.scrollFx.start(scrollX, 0).chain(function ()
        {
            delete this.disabled;
            
            if (this.options.markActiveItem)
            {
                this.getActiveItem().fade(0.7);
            }
            
            this.fireEvent('afterScroll');
        }.bind(this));
    },
    
    getActiveItem: function ()
    {
        if (4 < this.options.amount)
        {
            return this.options.items[this.options.position + 2];
        }
    }
    
});

