$(function(){
    /*
    This method replaces the existing ``rating_form`` with a prettier,
    image based one.

    First, it retrieves the currently selected value, then iterates through
    the list of options for rating, creating a new img instance for each one.

    Each img created also has a ``click`` event associated with it.  When the
    img is clicked, the id is parsed through a regex and the value is assumed
    to be the correspondng rating (id look like ``rate-N`` when N is a whole
    number).

    Finally, after extracting the rating from the ID, a hidden field is created
    with the same attribues (i.e, name, id) as the previously removed options
    field and it is popualted with the value of the clicked star and the form
    is submitted.
    */
    $(".rating-form form").each(function(i, form){
        $(form).find("option").each(function(i, option){
            if ($(option).val()){
                $("<img src=\"" + ratings_star_off + "\" alt=\"rate this " + $(option).val() + " stars\" id=\"rate-" + $(option).val() + "\" />")
                    .click(function(e){
                        var rating = e.target.id.match(/\d/gi)[0]
                        $("<input type=\"hidden\" value=\"" + rating + "\" id=\"id_value\" name=\"value\" />")
                            .appendTo($(form));
                        $(form).submit();
                    })
                    .mouseover(function(e){
                        $(form).find("img").each(function(i, elem){
                            $(elem).attr("src", ratings_star_off)
                        });
                        var rating = e.target.id.match(/\d/gi)[0];
                        for (i = 1; i <= rating; i++) {
                            $(form).find("#rate-" + i).attr("src", ratings_star_on)
                        }
                    })
                    .appendTo($(form));
            }
        });
        $(form).find("select").remove();
        //if (!rated || (rated && allow_remove_rating == false)) {
            $(form).find(":submit").remove();            
        //}
    });
});
