var GalleryScroller = new Class({
    Implements: [Options, Events],
    options: {
        'btPrev': null,
        'btNext': null,
        'btSteps': 1,
        'btDelay': 100,
        'btPeriod': 50
    },

    initialize: function(el, opts) {
        this.setOptions(opts);
        this.element = document.id(el) || document.getElement(el);
        this.step = 0;
        var klass = this;
        var initButton = function(bt, dir) {
            bt.addEvent('mousedown', function(e) {
                e.stop();
                $clear(this.retrieve('period'));
                klass.set(klass.step + klass.options.btSteps * dir);
                this.store('delay', (function() {
                    this.store('period', (function() {
                        klass.set(klass.step + klass.options.btSteps * dir);
                    }).periodical(klass.options.btPeriod));
                }).delay(klass.options.btDelay, this));
            }).addEvent('mouseup', function(e) {
                e.stop();
                $clear(this.retrieve('delay'));
                $clear(this.retrieve('period'));
            });
        };
        this.btPrev = document.id(this.options.btPrev);
        if(this.btPrev) {
            initButton(this.btPrev, -1);
        }
        this.btNext = document.id(this.options.btNext);
        if(this.btNext) {
            initButton(this.btNext, 1);
        }
    },
    set: function(steps) {
        this.step = steps.limit(0, this.element.getScrollSize().x);
        this.element.scrollTo(this.step);
        return this;
    }
});

window.addEvent('domready', function() {
    var gallery = document.getElement('.gallery-list');
    var notInCache = gallery.getElements('img').filter( function(img) {
        return (img.getHeight()<203);
    });
    var init = function() {
    	var galleryWidth = 0;
    	var btLeft = document.getElement('.arrow-left');
    	var btRight = document.getElement('.arrow-right');
	    gallery.getChildren().each( function(item) {
	    	galleryWidth+=item.getWidth()+item.getStyle('margin-left').toInt()+item.getStyle('margin-right').toInt();
	    });
	    gallery.setStyle('width', galleryWidth);
	    
	    if(gallery.getParent().getScrollSize().x<=gallery.getParent().getWidth()){
	    	new Elements([btLeft,btRight]).fade('hide');
	    }
		var scroller = new GalleryScroller(gallery.getParent(), {
		    'btPrev': btLeft,
		    'btNext': btRight,
		    'btSteps': 15,
		    'btPeriod': 20,
		    'btDelay': 0
		});
    };
    if(notInCache.length) {
        new Group(notInCache).addEvent('load', init);
    } else {
        init();
    }
});

