var PictureMoment = new Class({

    current: 0,

    timeout: 5,

    timer: null,

    data: [],

    preloader : null,

    initialize: function(params)
    {
        this.current = 0;
        this.data = params.data;

        $(params.previous).addEvent('click', this.previous.bindWithEvent(this));
        $(params.next).addEvent('click', this.next.bindWithEvent(this));

        this.rate = new Rater('potm_scorebar', {
            'rating': this.data[0].UserScreenshotStat.rating,
            'url': params.url,
            'callback': this.callback.bindWithEvent(this)
        });

        this.rate.setRating(this.data[this.current].UserScreenshotStat.rating);
        this.rate.setId(this.data[this.current].UserScreenshot.id);

        //this.start();
    },

    start: function()
    {
        this.timer = window.setInterval(this.timer.bindWithEvent(this), this.timeout * 1000);
    },

    stop: function()
    {
        window.clearInterval(this.timer);
    },

    // copy of next()
    timer: function()
    {
        var next = this.current < this.data.length - 1 ? this.current + 1 : 0;
        this.preload(next);
    },

    next: function(e)
    {
        this.stop(); // if user clicks on any control, disable auto scroll

        var next = this.current < this.data.length - 1 ? this.current + 1 : 0;
        this.preload(next);
    },

    previous: function(e)
    {
        this.stop(); // if user clicks on any control, disable auto scroll

        var next = this.current > 0 ? this.current - 1 : this.data.length - 1;
        this.preload(next);
    },

    preload: function(n)
    {
        this.current = n;

        var x = this.data[this.current].UserScreenshot.picture_medium;

        this.preloader = new Asset.image(this.data[this.current].UserScreenshot.picture_medium, {
            'onload': this.display.bindWithEvent(this)
        })
    },

    display: function()
    {
        var d = this.data[this.current];

        var rating = new Number(d.UserScreenshotStat.rating);
        var votes = new Number(d.UserScreenshotStat.votes);

        // update rate bar
        this.rate.setId(d.UserScreenshot.id);
        this.rate.setRating(rating);

        rating = rating > 0 ? rating.toFixed(1) : 'N/A';

        $('potm_picture').src = d.UserScreenshot.picture_medium;
        $('potm_desc').set('html', d.UserScreenshot.description);
        $('potm_rating').set('text', rating);
        $('potm_votes').set('text', votes);
        $('potm_link').href = d.UserScreenshot.link;
    },

    callback: function(data)
    {
        $('potm_rating').set('text', data.rating);
        $('potm_votes').set('text', data.votes);

        this.data[this.current].UserScreenshotStat.rating = data.rating;
        this.data[this.current].UserScreenshotStat.votes = data.votes;
    }
});