if (typeof(snapvine) == "undefined") snapvine = function() {};
if (typeof(snapvine.common) == "undefined") snapvine.common = function() {};

snapvine.common.rating = function() {};

snapvine.common.rating.vote = function(box_guid, rating)
{
    $.ajax({
      type: 'GET',
      url: '/post/rate_via_ajax',
      data: 'box_guid=' + box_guid + '&rating=' + rating,
      dataType: 'json',
      error: function()
      {
        alert('Your rating could not be saved.');
      },
      success: function(json)
      {
        if (json.status == 'success')
        {
          snapvine.common.rating.update_rating(json.box_guid, json.new_rating, json.new_num_votes);
        }
        else
        {
          alert(json.error_msg);
        }
      }
    });
};

snapvine.common.rating.update_rating = function(box_guid, new_rating, new_num_votes)
{
    var rating_div = document.getElementById('rating_' + box_guid);
    if (rating_div)
    {
        rating_div.className = 'rated rating stars' + Math.round(new_rating);
    }
    
    var num_votes = document.getElementById('votes_' + box_guid);
    if (num_votes)
    {
      if (new_num_votes < 5)
      {
        num_votes.innerHTML = '(less than 5 votes)';
      }
      else
      {
        num_votes.innerHTML = '(' + new_num_votes + ' votes)';
      }
    }
};

snapvine.common.rating.hover = function(link_element, rating)
{
    var old_star_value = link_element.parentNode.className.split(' ')[1];
    link_element.id = old_star_value;
    
    link_element.parentNode.className = 'rating stars' + rating;
}

snapvine.common.rating.clearhover = function(link_element)
{
    if (!link_element.parentNode.className.match(/rated/))
    {
        link_element.parentNode.className = 'rating ' + link_element.id;
    }
}
