var Carousel = new Class({
    Implements: Chain,

    'initialize': function (element){
        this.element = $(element);
        this.children = this.element.getChildren();
        this.offset = parseInt(this.element.getStyle('margin-left'));
        this.tween = new Fx.Tween(this.element, {
            'property': 'margin-left',
            'onComplete': this.callChain.bind(this)
        });
    },

    'rotateNext': function(){
        var first = this.children[0],
            last = this.children.getLast();
        
        first.inject(last, 'after');
        this.children.push(this.children.shift());
        return this.callChain();
    },

    'rotatePrevious': function (){
        var first = this.children[0],
            last = this.children.getLast();

        last.inject(first, 'before');
        this.children.unshift(this.children.pop());
        return this.callChain();
    },

    'toPrevious': function (){
        this.chain(
            function (){
                var target = this.offset - this.children.getLast().getDimensions().x;
                this.tween.set(target);
                return this.callChain();
            },
            this.rotatePrevious,
            this.tweenPrevious
        );

        return this.callChain();
    },

    'toNext': function (){
        this.chain(
            this.tweenNext,
            this.rotateNext,
            this.resetMargin
        );

        return this.callChain();
    },

    'tweenNext': function (){
        var target = this.offset - this.children[0].getDimensions().x;
        this.tween.start(target);
    },

    'tweenPrevious': function (){
        this.tween.start(this.offset);
    },

    'resetMargin': function (){
        this.tween.set(this.offset);
        return this.callChain();
    }
});

window.addEvent('domready', function(){
    var container = $('ProductCarousel');
    if (container) {
        var carousel = new Carousel(container.getElement('ul.carousel'));

        container.getElement('.previous').addEvent('click', function (e) {
            e.stop();
            carousel.toPrevious();
        });

        container.getElement('.next').addEvent('click', function (e) {
            e.stop();
            carousel.toNext();
        });
    }
});


