var NewsGallery = Class.create({
    
    initialize: function(idPrefix, items, current) 
    {
        this.idPrefix = idPrefix;
        this.items    = items;
        
        this.currentIndex = current;
        
        if (items.length && (items.length > 0)) {
            Event.observe(document, 'dom:loaded', this.onLoad.bindAsEventListener(this));
        }
    },

    _preloadImages: function()
    {
        for (var i = 0; i < this.items.length; i++) {
            var e = new Element('div');
            e.setStyle({'display': 'none'}).update(this.items[i].html);
            document.body.appendChild(e);
        }
    },
    
    onLoad: function(event) 
    {
        this.prevButton = $(this.idPrefix + 'previous');
        this.nextButton = $(this.idPrefix + 'next');
        this.image      = $(this.idPrefix + 'image');
        this.sourceText = $(this.idPrefix + 'source');
        this.titleText  = $(this.idPrefix + 'title');
        this.posText    = $(this.idPrefix + 'pos');
        
        this.prevButton.href = 'JavaScript:void(0);';
        this.nextButton.href = 'JavaScript:void(0);';
        this.image.href      = 'JavaScript:void(0);';
        
        this.prevButton.observe('click', this.previousImage.bindAsEventListener(this));
        this.nextButton.observe('click', this.nextImage.bindAsEventListener(this));
        this.image.observe('click', this.nextImage.bindAsEventListener(this));
        
        this._preloadImages();
    },
    
    setImage: function() 
    {
        if (!this.items.length || (this.items.length < 1)) {
            return;
        }
        
        var item = this.items[this.currentIndex];
        if (item) {
            this.image.innerHTML      = item.html;
            this.sourceText.innerHTML = item.source;
            this.titleText.innerHTML  = item.title;
            
            var posText = 'Bild ' + (this.currentIndex + 1) + ' von ' + this.items.length;
            this.posText.innerHTML = posText;
            
            if (item.source == '') {
                this.sourceText.parentNode.style.display = 'none';
            } else {
                this.sourceText.parentNode.style.display = 'block';
            }
        }
    },
    
    nextImage: function(event)
    {
        this.currentIndex++;
        
        if (this.currentIndex >= this.items.length) {
            this.currentIndex = 0;
        }
        
        this.setImage();
    },
    
    previousImage: function(event)
    {
        this.currentIndex--;
        if (this.currentIndex < 0) {
            this.currentIndex = this.items.length - 1;
            if (this.currentIndex < 0) {
                this.currentIndex = 0;
            }
        }
        
        this.setImage();
    }
        
});
