


var ImageScrubber= new Class({
    Implements: [Options],
    options: {
        reset: true
    },
    initialize: function(element, url, options) {
        this.setOptions(options);
        this.element = $(element);
        this.url = url;
        this.size = this.element.getStyle('width').toInt();
        this.bound = {
            'setup': this.setup.bind(this),
            'swap': this.swapImage.bind(this)
        };
        this.loadData();
    },
    showIndicator: function() {
        new Element('span', {
            'class': 'indicator',
            'styles': {
                'width': this.size,
                'height': this.element.getStyle('height').toInt(),
                'display': 'block'
            }
        }).inject(this.element).fade('show');
    },
    loadData: function() {
        new Request.JSON({
            method: 'get',
            url: this.url,
            onComplete: function(obj) {
                if($defined(obj)) {
                    this.element.empty();
                    this.showIndicator();
                    this.imageList = obj;
                    this.images = new Asset.images(this.imageList.map(function(t, i) {
                            return t.image;}), {
                        onComplete: this.bound.setup
                    });
                }
            }.bind(this)
        }).send();
    },
    setup: function() {
        this.element.empty();
        this.position = this.element.getPosition();
        this.ratio = (this.size / this.images.length).round().limit(1, this.size);
        this.offset = (this.ratio / 2).round();
        this.images[0].inject(this.element);
        this.element.addEvent('mousemove', this.bound.swap);

	
        if(this.options.reset)
            this.element.addEvent('mouseleave', function(event) {
                this.setImage(0);
            }.bind(this));
        this.oldIndex = 0;
    },
    setImage: function(index) {
        this.element.empty();
        var anchor = new Element('a', {
            'href': this.imageList[index].link
        });
        this.images[index].inject(anchor);
        anchor.inject(this.element);
        this.oldIndex = index;
    },
    swapImage: function(event) {
        var relX = ((event.client.x - this.position.x) - this.offset).limit(0, this.size);
        var index = (relX / this.ratio).round().limit(0, this.images.length - 1);
        if(index != this.oldIndex) this.setImage(index);
    }
});
