$(document).ready(function() {

    var scrollTop = function() {
        var st = document.body.scrollTop;
        if (st == 0) {
            if (window.pageYOffset)
                st = window.pageYOffset;
            else
                st = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
        }
        return st + 200;
    }

    /* hide the rating input and thank you widgets */
    $('#rating-input').hide();
    $('#rating-thank-you').hide();

    /* show the rating input */
    $('li#rating-trigger').click(function() {
        $('#rating-input').show();
        $('#rating-input').css({top: scrollTop(), marginLeft: '-' + ($('#rating-input').width()/2) + 'px'});
    });

    /* cancel instead of rating */
    $('a#rating-cancel').click(function() {
        $('#rating-input').hide();
    });

    /* dismiss the thank you widget */
    $('a#rating-close').click(function() {
        $('#rating-thank-you').hide();
    });

    /* set the rating by hovering over stars */
    $('.rating .star')
        .hover(function() {
            var num = parseInt($(this).attr('rel'));
            $('.rating .star').each(function(i) {
                i < num ? $(this).removeClass('empty') : $(this).addClass('empty');
            });
        })
        .each(function(i) {
            $(this).attr('rel', i+1);
        });

    /* cast the vote, and replace the input widget with the thank you widget */
    $('#rating-submit').click(function() {
        var score = 5 - $('.rating .empty').length;

        var episodeId = $(this).attr('rel').split(':')[0];
        var productId = $(this).attr('rel').split(':')[1];
        var voteUrl = '/vote.php?score=' + score + '&episodeId=' + episodeId + '&productId=' + productId;

        $.ajax({
            url: voteUrl, 
            context: document.body,
            success: function() {
                $('#rating-input').hide();
                $('#rating-thank-you').show();
                $('#rating-thank-you').css({top: scrollTop(), marginLeft: '-' + ($('#rating-thank-you').width()/2) + 'px'});
            }
        });
    });
});

