$(document).ready(function(){
  $('div.link span.score').each(function(){
    vote = parseInt($(this).siblings('.vote').text());
    img_up_class = (vote == 1) ? ' selected' : '';
    img_dn_class = (vote == -1) ? ' selected' : '';
    $(this)
      .before('<span class="vote up' + img_up_class + '"></span>')
      .after('<span class="vote down' + img_dn_class + '"></span>');
  });

  $('span.vote').live('click', function(){
    link = $(this);
    link.removeClass('selected');
    link.siblings('.vote').removeClass('selected');
    linkID = link.siblings('code').text();
    score = (link.hasClass('up')) ? 1 : -1;
    url = 'link/vote/' + linkID + '/' + score;
    $.get(url, [], function(data){
      if (data == 'login')
      {
        alert('You must log in to vote');
        return;
      }
      data = data.split('-');
      if (data[0] == 'voted'){
        if (data[1] == 'same')
          score *= -1;
        else if (data[1] == 'rev'){ // reverse a previous vote
          score *= 2;
          link.addClass('selected');
        }
        else if (data[1] == 'new'){
          link.addClass('selected');
        }
        link.siblings('span.score').text(parseInt(link.siblings('span.score').text(), 10) + score);
      }
    });
  });
});