var ratingControlValues = [ 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 5.0, 5.0 ];
var ratingControlHalfStarValues = [ 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0 ];

function ratingControlShowValue(value, ratingControl) {
    var imgs = $("img", ratingControl);
    var basepath = imgs.attr("src");
    var l = basepath.lastIndexOf("/");
    basepath = basepath.substring(0, l + 1);
    
    var n = value * 2 - 1;
    var i = 0;
    
    imgs.each(function() {
        $(this).attr("src", basepath + "star-" + ( i % 2 == 0 ? "left" : "right" ) + "-" + (i <= n ? "on" : "off") + ".gif");
        i++;
    });
}

function ratingControlSubmitValue(value, postID, ratingControl) {
    $(ratingControl).unbind("mouseleave");
    $("img", ratingControl).unbind("mouseenter").unbind("click").css("cursor", "default");
    ratingControlShowValue(value, ratingControl);
    
    $.post(basePath + "ajax/posts/rate.aspx", { value: value, postId: postID }, function(data) {
        var rating = data.response.rating;
        var newTitle = data.response.title;
        setTimeout(function() {
            ratingControlShowValue(rating, ratingControl);
            $(ratingControl).attr("title", newTitle);
        }, 5000);
    }, "json"); 
    
}

function setupRatingControl(root) {
    $( (root ? root + " " : "") + "span.ratingControl").each(function() {
        var ratingControl = this;
        var postID = $("input.post", ratingControl).attr("value");
        if (postID) {
            var useHalfStars = $(ratingControl).hasClass("halfstars");
            var value = $("input.value", ratingControl).attr("value");
            $(ratingControl).mouseleave(function() {
                ratingControlShowValue(value, ratingControl);
            });
            $("img", ratingControl).each(function() {
                var position = $("img", ratingControl).index(this);
                var newValue = useHalfStars ? ratingControlHalfStarValues[position] : ratingControlValues[position];
                $(this).mouseenter(function() {
                    ratingControlShowValue(newValue, ratingControl);
                });
                $(this).click(function() {
                    ratingControlSubmitValue(newValue, postID, ratingControl);
                });
            }).css("cursor", "pointer");
        }
    });
}