$(document).ready(function($) {
  var loading = '<img src="/images/loading-small.gif" alt="oppdaterer" />';
  
  //Preload images to avoid glitches when hovering
  $('<img>').attr('src', '/images/loading-small.gif');
  $('<img>').attr('src', '/images/scores/1-40.png');
  $('<img>').attr('src', '/images/scores/6-40.png');

  //Initialise hover and click actions
  $('#vote-score-6').hover(
    function() {
      highlightVote(6);
    },
    function() {
      fadeVote(6);
    }
  );

  $('#vote-score-6').click(
    function() {
      sendScore(6);
    }
  );

  $('#vote-score-1').hover(
    function() {
      highlightVote(1);
    },
    function() {
      fadeVote(1);
    }
  );

  $('#vote-score-1').click(
    function() {
      sendScore(1);
    }
  );

 //Submit score to remote server and update elements
  function sendScore(score)
  {
    var other = 0;
    if (score == 1)
    {
      other = 6;
    }else {
      other = 1;
    }

    $('#vote-count-'+score).html(loading);
    $('#vote-confirmation').html('');
    $('#vote-score-'+score).addClass('locked');
    $('#vote-score-'+other).removeClass('locked');
    fadeVote(other);
    var slug = $('h1').attr('id');
    $.getJSON('/ajax/vurder-anmeldelse.json',
              { slug: slug, vote: score },
              function (json) {
                updateVotes(json.votes1, json.votes6, score, other);
                $('#vote-confirmation').html(json.message);
              });
  }

  //Update votes and visual feedback
  function updateVotes(votes1, votes6, add, remove)
  {
    $('#vote-count-1').html(votes1);
    $('#vote-count-6').html(votes6);
    highlightVote(add);
    fadeVote(remove);
  }

  //Replace faded image with a clear image
  function highlightVote(score)
  {
    $('#vote-score-'+score).attr('src', '/images/scores/'+score+'-40.png');
  }
  
  //Replace clear image with a faded image
  function fadeVote(score)
  {
    $('#vote-score-'+score+':not(.locked)').attr('src', '/images/scores/'+score+'-40-faded.png');
  }
});