/*
 * rater.js
 * Amiel Martin
 * 2009-08-22
 *
 * simble jQuery rating plugin
 */

var Rater = function(me, options){ this.list = me; this.opts = options; };

(function($){
    $.fn.rater = function(options) {
        this.each(function() {
            var rater = new Rater(this, options);
            rater.setup();
        });
    };
    
    $.extend(Rater, {
        rating_classes: [ 'null', 'hover', 'suggested', 'rated' ]
    });
    
    $.extend(Rater.prototype, {
        set_class_upto: function(klass, upto) {
            var me = $(upto),
                list = $(this.list);
            $.each(Rater.rating_classes, function() {
                 list.find('li').removeClass(this);
             });
            while (true) {
                if (me.length == 0) return;
                me.addClass(klass);
                me = me.prev();
            }
        },
        
        setup: function() {
            var t = this,
                $li = $('li', t.list),
                $list = $(t.list),
				beer_id = $list.attr('id').replace(/^[^\d]+(\d+)$/, '$1');
            
            t.set_class_upto('rated', $li.filter('.current_rating'));
            $(this.list).css('opacity', 0.8).hover(function() {
                $(this).stop().fadeTo('fast', 1);
            }, function() {
                $(this).stop().fadeTo('fast', 0.8);
            });
            
            $li.addClass('star').css('cursor', 'pointer').hover(function() {
                t.set_class_upto('hover', this);
            }, function() {
                t.set_class_upto('rated', $li.filter('.current_rating'));
            }).click(function() {
                var my_rating = this.id.replace(/^.+?(\d+)$/, '$1');
                $.post(t.opts.url(my_rating, beer_id));
                $li.removeClass('current_rating');
                $(this).addClass('current_rating');
                t.set_class_upto('rated', this);
            });
        }
    });
})(jQuery);