﻿var Scroller = new Class({
    initialize: function() {
        this.index = 0;
        this.container = $('gallery-container');
        if (this.container) {
            this.left = $('scroll-left');
            this.right = $('scroll-right');
            this.content = $('gallery');
            this.setupEvents();
        }
        this.hideRightImages();
    },
    
    hideRightImages: function() {
        var items = this.content ? this.content.getElements('a') : [];
        if (items.length > 0) {
            var right = this.container.getCoordinates().right;
            var visible = true;
            items.each(function(el) {
                if (!visible || el.getCoordinates().right > right) {
                    visible = false;
                    el.setStyle('display', 'none');
                }
            });
        }
    },
    
    setupEvents: function() {
        if (this.left) this.left.addEvent('click', function() { this.scroll(-1); }.bind(this));
        if (this.right) this.right.addEvent('click', function() { this.scroll(1); }.bind(this));
    },
    
    scroll: function(offset) {
        var items = this.content ? this.content.getElements('a') : [];
        
        if (items <= 6) {
            // all items are shown
            items.each(function(el) {
                el.setStyle('display', 'inline');
            });
            return;
        }
        
        // adjust index
        this.index += offset;
        if (this.index < 0) this.index = 0;
        if (this.index >= items.length) this.index = items.length - 1;
        
        // hide/show items
        for (var i=0; i<items.length; i++) {
            items[i].setStyle('display', i < this.index ? 'none' : 'inline');
        }
        this.hideRightImages();
    }
});

window.addEvent('load', function() {
    new Scroller();
});
