﻿var Scroller = new Class({
    Implements:Options,
    options: {
        visibleItems: 6,
        visibleDisplay: 'inline',
        contentItems: 'img',
        leftScroll: 'div.left',
        rightScroll: 'div.right',
        contentArea: 'div.content'
    },
    
    initialize: function(container, options) {
        this.setOptions(options);
        this.index = 0;
        this.container = container;
        this.left = this.container.getElement(this.options.leftScroll);
        this.right = this.container.getElement(this.options.rightScroll);
        this.content = this.container.getElement(this.options.contentArea);
        this.setupEvents();
    },
    
    setupEvents: function() {
        if (this.content) {
            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(this.options.contentItems) : [];
        
        if (items <= this.options.visibleItems) {
            // all items are shown
            items.each(function(el) {
                el.setStyle('display', this.options.visibleDisplay);
            });
            return;
        }
        
        // adjust index
        this.index += offset;
        if (this.index < 0) this.index = 0;
        if (this.index > items.length - this.options.visibleItems) this.index = items.length - this.options.visibleItems;
        
        // hide/show items
        for (var i=0; i<items.length; i++) {
            items[i].setStyle('display', (i < this.index || i >= (this.index + this.options.visibleItems)) ? 'none' : this.options.visibleDisplay);
        }
    }
});

window.addEvent('domready', function() {
    $(document.body).getElements('div.scrollbox').each(function(el) {
        new Scroller(el);
    });
    $(document.body).getElements('div.scrollbox-8').each(function(el) {
        new Scroller(el, { 'visibleItems': 8 });
    });
    $(document.body).getElements('div.scrollbox-10').each(function(el) {
        new Scroller(el, { 'visibleItems': 10 });
    });
});