$.fn.rating = function(id){
    var originalWidth = $(".stars .rated",this).width();
    var originalText = $.rating.originalText;
    var voted = false;
    var ratings = $.rating.ratings;
    $(".stars",this).hover(function(){
        if ( !voted ) {
            var current = $(this);
            var rate = $(".rated",this);
            var value = 1;
            $(this).css('cursor','pointer');
            $(this).mousemove(function(e){value=$.rating.move(e,current,rate,ratings);});
            $(this).click(function(){
                current.unbind('mousemove');
                voted = true;
                current.parent().children('B').html($.rating.loading);
                var clicked = $(this);
                $.ajax({
                    url: $.rating.url,
                    dataType: "json",
                    type: 'post',
                    data: 'id='+id+"&value="+value,
                    error: function(xhr){voted=false;current.parent().children('B').html($.rating.errorText);clicked.mousemove(function(e){$.rating.move(e,current,rate,ratings);});},
                    success: function(data){
                        current.parent().children('P').html(data.text);
                        current.parent().children('B').html(data.message);
                        $(rate).width( current.width()*data.value/5 );
                        if ( data.result ) {
                            clicked.unbind('click');
                        }
                        else {
                            alert(data.message);
                            clicked.mousemove(function(e){$.rating.move(e,current,rate,ratings);});
                        }
                    }
                });
            });
        }
    },function(){
        if ( !voted ) {
            $(".rated",this).width(originalWidth);
            $(this).unbind( 'click' );
            $(this).parent().children('B').html(originalText);
        }
    });
}
$.rating = {
    ratings: new Array( 'Gyenge', 'Megéri megnézni', 'Egész jó', 'Nagyon szép', 'Profi munka' ),
    originalText: "Hogy tetszik?",
    thankYou: "Köszönjük szavazatodat!",
    loading: "Kis türelmet...",
    errorText: "A feldolgozás során hiba történt, próbáld újra!",
    url: 'ajax/otletek/vote.php',
    move: function(e,current,rate,ratings){
        value = Math.floor( (e.pageX-current.position().left)/current.width()*5+1 );
        $(rate).width( value*current.width()/5 );
        current.parent().children('B').html(ratings[value-1]);
        return value;
    }
}
