;(function( $, _ , window, document, undefined ){

    var Podium = function(options){
        this.options = options;
    };

    Podium.prototype = {

        defaults: {
            // The podium container element id
            container_id: '#podium',
            // The refresh delay of the podium
            refresh_delay: 300000, // each 5 minutes
            // The number of trainee to display on the podium
            trainee_nb_display: 3
        },

        init: function() {
            // Underscore template "Mustache style"
            _.templateSettings = {
                interpolate: /\{\{(.+?)\}\}/g
            };

            // Extends the default config with the provided options
            this.config = $.extend( {}, this.defaults, this.options );

            // Underscore template to display a trainee/score item
            this.trainee_score_template = _.template($('#trainee-score-template').html());

            // Container element
            this.$container = $(this.config.container_id);

            // Initialize the podium refresh interval
            var self = this;
            window.setInterval(
                self.render(),
                self.config.refresh_delay
            )

            return this;
        },

        fetch: function() {

            var deferred = $.Deferred();

            // Fetching the challenge data
            $.get(this.config.challenge_data_url, function(data){
                deferred.resolve(data);
            });

            return deferred;
        },

        render: function() {

            var self = this;
            // First, fetch the latest data from the provided url
            this.fetch().then(function(score_items){

                // Clean the existing scores items
                self.$container.empty()

                // Order by score
                score_items = _.sortBy(score_items, function(score_item) { return -score_item.score; })
                // Get Only the number of item we want to show
                score_items = score_items.slice(0, self.config.trainee_nb_display);

                // Append each rendered template to the container
                _.each(score_items, function(score_item, index){
                    // Add the position to the score_item
                    score_item['position'] = index + 1;
                    if (!score_item['trainee']['photo']){
                        score_item['trainee']['photo'] = '/static/trainings/images/avatar.jpg';
                    }
                    self.$container.append(
                        self.trainee_score_template(score_item)
                    );
                });
            });
        },

    };

    Podium.defaults = Podium.prototype.defaults;
    window.Podium = Podium;

})( jQuery, _, window, document );
