var Showroom = Class.create ({
    runner: false,
    showroom: undefined,
    initialize: function (elm, delay, start) {
        this.showroom = $(elm);
        this.showroom.down('.left').observe('click', this.scrollLeft.bindAsEventListener(this));
        this.showroom.down('.right').observe('click', this.scrollRight.bindAsEventListener(this));
        if(delay) {
            this.autorun(delay).delay(start);
        }
    },
    scrollRight: function (ev) {
        var elm = ev.element();
        this.runner.stop();
        var presentation = elm.previous('.presentation');
        var pos = presentation.cumulativeScrollOffset().left;
        var max = parseInt(presentation.down('ul').getWidth())-780;
        var speed = 0.5;
        if(pos == max) {
            pos = max;
            var endPos = 0;
            speed = 0.5;
        } else {
            var endPos = pos + 780;
            endPos = (endPos > max) ? max : endPos;
        }
        new Effect.Tween(presentation ,pos, endPos, { duration: speed, transition: Effect.Transitions.sinoidal }, 'scrollLeft')
    },
    scrollLeft: function (ev) {
        var elm = ev.element();
        this.runner.stop();
        var presentation = elm.next('.presentation');
        var pos = presentation.cumulativeScrollOffset().left;
        var max = parseInt(presentation.down('ul').getWidth())-780;
        var speed = 0.5;
        if(pos == 0) {
            var endPos = max;
            speed = 0.5;
        } else {
            var endPos = pos - 780;
            endPos = (endPos < 0) ? 0 : endPos;
        }
        new Effect.Tween(presentation,pos, endPos, { duration: speed, transition: Effect.Transitions.sinoidal }, 'scrollLeft');
    },
    autoScroll: function () {
        var presentation = this.showroom.down('.presentation');
        var pos = presentation.cumulativeScrollOffset().left;
        var max = parseInt(presentation.down('ul').getWidth())-780;
        var speed = 0.5;
        if(pos == max) {
            pos = max;
            var endPos = 0;
            speed = 0.5;
        } else {
            var endPos = pos + 780;
            endPos = (endPos > max) ? max : endPos;
        }
        new Effect.Tween(presentation ,pos, endPos, { duration: speed, transition: Effect.Transitions.sinoidal }, 'scrollLeft')
    },
    autorun: function (delay) {
        this.runner = new PeriodicalExecuter(this.autoScroll.bind(this),delay);
    }
});

document.observe('dom:loaded', function () {
   
   $$('.section').each(function (section) {
        var cols = section.childElements();
        if(cols.size() > 1) {
            var height = cols.max(function (col) { return col.getHeight() }) - 20;
            cols.each(function (col) {
                col.style.height= height + 'px';
            })
        }
        
   })
   
   new Showroom($$('.showroom')[0],7,5);
   
});
