/*
  rating stuff
*/

Event.observe(window, 'load', function() {
  $$('.rating-form').each(function(rating_form){
    // update to display the correct current rating
    backToRating(rating_form);
    
    // attach the control events
    Event.observe(rating_form.down('.rating-control'), 'mouseout', function() { backToRating(rating_form); } );
    Event.observe(rating_form.down('.rating-control'), 'mousemove', function(e) { ratingPositionChange(e, rating_form); });
  });
});

function calculate_rating(e) {
  // figures out which star they are on in the midst of a mouse event
  return Math.round(10*((e.pageX-e.target.cumulativeOffset()[0])/76));
}

function ratingPositionChange(e, rating_form) {
  // figure out the new rating
  var new_rating = calculate_rating(e);
  // update the form
  $(rating_form).down('.new-rating').value = new_rating;
  // update the image
  e.target.src = '/images/ratings/userrating-'+(new_rating*5).toString()+'.gif';
}

function backToRating(rating_form) {
  var rating_image = rating_form.down('.rating-control');
  var new_rating = rating_form.down('.current-rating').value;
  rating_image.src = '/images/ratings/rating-'+(new_rating*5).toString()+'.gif';
}

function rating_onSubmit(rating_form, e) {

}
function rating_onSuccess(t, rating_form) {
  var result = t.responseJSON;

  if (result.success) {
    // update the form with the new value
    rating_form.down('.current-rating').value = result.rating;

    // update display to reflect the new rating
    backToRating(rating_form);

    // let them know it worked
    display_notification('Your rating has been saved. You can rate an item multiple times, only your latest vote counts.');
  } else {
    rating_onFailure(t)
  }
}
function rating_onFailure(t) {
  // let them know it didn't work
  display_notification('There was an issue saving the rating');
}
