﻿var ContentSlider = Class.create({
    
    initialize: function()
    {
        this.items = new Array();
        this.contentElement = new Element('div', {'id': 'ContentSliderBody'});
        
        this.offset = 0;
        this.currentIndex = 0;
        this.visibleItems = 4;
        this.contentWidth = 206;
        
        var _self = this;
        this.automoveExecutor = new PeriodicalExecuter(function(){ _self.automove(); }, 5);
        this.automoveDirection = 1;
    },
    
    addItem: function(src)
    {
        this.items.push(new ContentSliderItem(src));
    },
    
    render: function(targetelement)
    {
        var _self = this;
        
        this.items.each(function(item)
        {
            var itemwrapper = new Element('div', {'id': 'ContentSliderItem'});
            itemwrapper.update('<span>' + item.src + '</span>');
            _self.contentElement.appendChild(itemwrapper);
        });
        
        var wrapper = new Element('div', {'id': 'ContentSliderWrapper'});
        wrapper.appendChild(this.contentElement);
        
        $(targetelement).appendChild(wrapper);
    },
    
    getMovement: function()
    {
        return this.contentWidth * this.visibleItems
    },
    
    automove: function()
    {
        if(this.currentIndex + 1 == Math.ceil(this.items.length / this.visibleItems))
        {
            this.automoveDirection = -1;
        }
        else if(this.currentIndex == 0)
        {
            this.automoveDirection = 1;
        }
        
        if(this.automoveDirection == 1)
        {
            this.moveForward();
        }
        else
        {
            this.moveBackward();
        }
    },
    
    moveForward: function()
    {
        if(this.currentIndex + 1 < Math.ceil(this.items.length / this.visibleItems))
        {
            this.offset = this.offset - this.getMovement();
            this.currentIndex++;
            this.move();
        }
    },
    
    moveBackward: function()
    {
        if(this.currentIndex > 0)
        {
            this.offset = this.offset + this.getMovement();
            this.currentIndex--;
            this.move();
        }
    },
    
    move: function()
    {
        new Effect.Move(this.contentElement, { x: this.offset, y: 0, mode: 'absolute', duration: 0.5 });
    },
    
    onClick_MoveForward: function()
    {
        this.automoveExecutor.stop();
        this.moveForward();
    },
    
    onClick_MoveBackward: function()
    {
        this.automoveExecutor.stop();
        this.moveBackward();
    }

});

var ContentSliderItem = Class.create({

    initialize: function(src)
    {
        this.src = src;
    }

});