var $votingAjaxMananger = $.manageAjax({manageType: 'abortOld', maxReq: 0, blockSameRequest: true});

function bindVoteButtons() {
  $('a.plus, a.minus').livequery('click', function(event) {
    if ($cheddr['block_interactions'] == true)
      return false;
    var $this = $(this);
    var contest_id = location.href.search(/\d+/);
    // Block all buttons
    $this.parent().block({ message: null });
    $this.parent().siblings().block({ message: null});
    var voting_up = false;
    var vote_count_container = $this.parent().parent().parent().find('span.voteCountInner');
    var vote_count = parseInt(vote_count_container.html());
    var post_id = $(this).attr('id').replace(/trigger-entry-/,'').replace(/-(down|up)/,'');
    // Voting up or down?
    if ( $(this).attr('ref') == 'up' ) {
      voting_up = true;
    }
    else {
      voting_up = false;
    }
    
    

    if ($this.parent().parent().find('a.plus-atv').length > 0) {
      
      if (!voting_up) { // Voting down, so remove -atv from class
        vote_count--;
        vote_count--;
        $this.parent().parent().find('a.plus-atv').attr('class','plus');
      }
    } else if ($this.parent().parent().find('a.minus-atv').length > 0) {
      
      if (voting_up) { // Voting up, so remove this active class on down, add 1 vote
        vote_count++;
        vote_count++;
        $this.parent().parent().find('a.minus-atv').attr('class','minus');
      }
    } 
    else { // Not changing a vote
      if (voting_up) {
        vote_count++;
      }
      else {
        vote_count--;
      }
    }

    // Make Active
    $this.attr('class',$this.attr('class')+'-atv')
    // Set Vote Count
    vote_count_container.html(""+vote_count);

    // Determine Post Path
    var url = "/" + contest_id + "/entries/" + post_id + "/vote_" + (voting_up ? 'up' : 'down') + '.json';
    // Call To Server via managed ajax plugin
    $votingAjaxMananger.add({
      dataType: "json",
      type: "POST",
      url: url,
      data: "",
      success: function(data){
        if (data && data.result) {
          // Lastly, unblock controls that are not set active
          $this.parent().parent().find(':not(li.active)').unblock();
          $this.parent().parent().find(':not(li.option-bomb-selected)').unblock();
          $this.parent().parent().find(':not(li.option-super-selected)').unblock();
        }
      }
    });
    return false;
  }); // End LiveQuery for a.vote-entry-button
}

$(function(){
  bindVoteButtons();
}); // End document.ready