(function($) {
    
    $.fn.starRow = function(target_div) {
        var row = $(target_div);
        var row_p = row.offset();
        var voting = true;

        function setStars(score) {
            for(var i = 1; i < 6; i++) {
                var c = Math.round((i * 2) - score);
                var t = $('.star' + i, row);
                if (c === 1) {
                    t.removeClass('emptystar').removeClass('fullstar').addClass('halfstar');
                    continue;
                }
                if (c < 1) {
                    t.removeClass('emptystar').removeClass('halfstar').addClass('fullstar');
                    continue;
                }
                t.removeClass('halfstar').removeClass('fullstar').addClass('emptystar');
            }
        }

        var t = $('input[name=voting]', row).attr('value');
        if (t === 'no') {
            voting = false;
        }

        if (voting) {
            $(window).resize(function() { row_p = row.offset(); });
            
            row.mouseenter(function() {
                $(this).mousemove(function(e) {
                    var pos = (e.pageX - row_p.left) / 16;
                    setStars(pos);
                });
    
                $(this).click(function(e) {
                    var pos = (e.pageX - row_p.left) / 16;
                    $(row).load('/festivalsonline/vote/',
                                { 'film': $('#festival-film-id').attr('value'),
                                  'vote': Math.round(pos) });
                });
            });
            
            row.mouseleave(function() {
                $(this).unbind('mousemove');
                $(this).unbind('click');
                var t = $('input[name=score]', $(this)).attr('value');
                setStars(t);
            });
        }
    }
})(jQuery);
    
    
$(document).ready(function() {
    $('.stars-with-voting').each(function() { $.fn.starRow(this); });
});

