$(function(){
    $('#gallery div.rating').each(function(){
        var $ratingBox = $(this);
        
        $ratingBox.find('a').click(function(){
            $ratingBox.addClass('loading');
            
            var pictureId = $(this).parents('div.photo').find('#photoId').val();
            var rating = 0;
            if ($(this).hasClass('one-star')) {
                rating = 1;
            } else if ($(this).hasClass('two-stars')) {
                rating = 2;
            } else if ($(this).hasClass('three-stars')) {
                rating = 3;
            } else if ($(this).hasClass('four-stars')) {
                rating = 4;
            } else if ($(this).hasClass('five-stars')) {
                rating = 5;
            }
            
            if ((pictureId > 0) && (rating > 0)) {
                
                random = new Date().getTime();
                params = 'random=' + random + '&pictureId=' + pictureId + '&rating=' + rating;
                $.ajax({
                    type: "GET",
                    timeout: 20000,
                    url: '/ajax/gallerypicturerate/',
                    data: params,
                    async: true,
                    dataType: "xml",
                    success: function(responseXml){
                        if ($(responseXml).find('result').text() == 1) {
                            if ($(responseXml).find('ratingCount').text() != '') {
                                $ratingBox.find('.ratingCount').text($(responseXml).find('ratingCount').text());
                            }
                            if ($(responseXml).find('ratingAvg').text() != '') {
                                $ratingBox.find('.ratingAvg').text($(responseXml).find('ratingAvg').text());
                                $ratingBox.find('.current-rating').css('width', $(responseXml).find('ratingAvg').text() * 20);
                            }
                        } else if ($(responseXml).find('message').text() != '') {
                            alert($(responseXml).find('message').text());
                        }
                        $ratingBox.removeClass('loading');
                    },
                    error: function(){}
                });
                
            }
            
            return false;
        });

    });
});
