$(document).ready(function() {    
    $(".votes a").hover(function() {
        $(this).addClass("select");
        $(this).prevUntil().each( function() {$(this).addClass("select")} );
        $(this).nextUntil().each( function() {$(this).removeClass("select")} );
    }, function() {
        
    });

    $(".votes").hover(function() {

    }, function() {
        var stars = $(this).children("a");

        var pdiv = $(this).parents("div");
        var p_id = pdiv.attr("id").substr(1);

        $.ajax({
                type:'POST',
                dataType:'html',
                data: { party_id:  p_id },
                success:function(data, textStatus) {
                    for (i = 0 ; i < data; i++) {
                        $($(stars).get(i)).addClass("select");
                    }
                    for (i = data ; i < 5; i++) {
                        $($(stars).get(i)).removeClass("select");
                    }
                },
                error:function(textStatus) {
                    $(this).parent("span").children("a").each( function() {$(this).removeClass("select")} );
                },
                url:'/index.php/party/countVote'
        });
    });

    $("span.votes > a").click(function() {
        var stars = $(this).parent("span").children("a");
        var count = stars.filter('.select').length;

        var pdiv = $(this).parents("div");
        var p_id = pdiv.attr("id").substr(1);
        var rateBlock = pdiv.children("dl").
                        children("dd").children("div.ad_to_party").children("span");
        var newRate = 0;

        $.ajax({
                type:'POST',
                dataType:'html',
                data: { party_id:  p_id, rate: count },
                success:function(data, textStatus) {
                    rateBlock.text("Оценка: " + data);
                },
                error:function(textStatus) {
                    var oldText = rateBlock.text();
                    rateBlock.stop(false, false).animate( {opacity: "hide"}, "slow", function() {
                        rateBlock.text('Вы уже голосовали!');
                            rateBlock.animate( {opacity: "show"}, "slow", function() {
                                rateBlock.animate( {opacity: "hide"}, "slow", function() {
                                rateBlock.text( oldText );
                                rateBlock.animate( {opacity: "show"}, "slow" );
                            });
                        });
                    });

                },
                url:'/index.php/party/vote'
        });

        return false;
    });

    $("a[class=fancybox]").fancybox();
});
