﻿var VCardImageSlider = Class.create({
    
    initialize: function()
    {
        this.items = new Array();
        this.contentElement = new Element('div', {'id': 'VCardImageSliderContent'});
        
        this.offset = 0;
        this.currentIndex = 0;
        this.visibleItems = 3;
        this.imageWidth = 100;
        
        var _self = this;
        this.automoveExecutor = new PeriodicalExecuter(function(){ _self.automove(); }, 5);
        this.automoveDirection = 1;
    },
    
    addItem: function(src, link)
    {
        this.items.push(new VCardImageSliderItem(src, link));
    },
    
    render: function(targetelement)
    {
        var _self = this;
        
        this.items.each(function(item)
        {
            var itemwrapper = new Element('div', {'id': 'VCardImageSliderItem'});
            itemwrapper.update('<a href="' + item.link + '" onclick="event.cancelBubble=true;" ><img src="' + item.src + '" alt="gleicheliebe.de" /></a>');
            _self.contentElement.appendChild(itemwrapper);
        });
        
        var wrapper = new Element('div', {'id': 'VCardImageSliderWrapper'});
        wrapper.appendChild(this.contentElement);
        
        $(targetelement).appendChild(wrapper);
    },
    
    getMovement: function()
    {
        return this.imageWidth * 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 VCardImageSliderItem = Class.create({

    initialize: function(src, link)
    {
        this.src = src;
        this.link = link;
    }

});
