window.console = window.console ? window.console : {log: function(m) { alert(m); }};

(function($) {
    var SnowmanRatingWidget = function($input) {
        this.$input = $input;
        this.rewriteMarkup();
    }

    SnowmanRatingWidget.prototype.rewriteMarkup = function() {
        this.$snowmen_container = $('<div></div>');
        this.$snowmen_container.addClass('snowmen-container');

        for(var i=0; i<5; i++) {
            this.$snowmen_container.append($('<span class="snowman"></span>'));
        }
        
        this.$input.after(this.$snowmen_container);
        this.$input.hide();

        if(!this.$input.val()) {
            this.$input.val(0.0);
        }
        
        this.setSnowmenFromValue(parseFloat(this.$input.val()));

        // Set up hover behavior
        var self = this;
        this.update_snowmen_hover_interval = null;
        $('body').bind('mousemove', function(e) {
            self.mouse_x = e.clientX;
            self.mouse_y = e.clientY;
        });

        this.$snowmen_container.hover(function() {
            self.update_snowmen_hover_interval = setInterval(function() {
                self.setSnowmenFromValue(self.getValueFromCursor());
            }, 50);
        }, function() {
            clearInterval(self.update_snowmen_hover_interval);
            self.setSnowmenFromValue(self.$input.val());            
        });

        this.$snowmen_container.click(function() {
            var val = self.getValueFromCursor();
            self.setSnowmenFromValue(val);
            self.setInputValue(val);
            self.$input.val(val);
            clearInterval(self.update_snowmen_hover_interval);
        });
    }

    SnowmanRatingWidget.prototype.setInputValue = function(val) {
        this.$input.val(val);
    }
    
    SnowmanRatingWidget.prototype.getValueFromCursor = function() {
        var offset = 10;
        var left_pos = this.mouse_x - this.$snowmen_container.position().left + offset;
        var snowman_fraction = left_pos / this.$snowmen_container.width();
        var val = Math.round(snowman_fraction * 10) * 0.5;
        return val;
    }
    
    SnowmanRatingWidget.prototype.setSnowmenFromValue = function(val) {
        var half_snowman_count = Math.ceil(val / 0.5);
        var full_snowmen = Math.floor(half_snowman_count / 2);
        var has_half = half_snowman_count % 2 == 1;

        // Re-set all snowmen to 'empty'
        this.$snowmen_container.find('.snowman').removeClass('half').removeClass('full');
        
        for(var i=0; i<full_snowmen; i++) {
            this.$snowmen_container.find('.snowman').eq(i).addClass('full');
        }

        if(has_half) {
            this.$snowmen_container.find('.snowman').eq(full_snowmen).addClass('half');
        }
    }

    // Init
    $(function() {
        $('.snowman_rating_widget').each(function() {
            new SnowmanRatingWidget($(this));
        });
    })
    
})(jQuery);
