
Drupal.behaviors.voteUpDown = function() {
  currentScore = $('.updown-widget').children('.updown-score').children('.updown-current-score');
  voteElement = $('.updown-widget').find('.updown-vote');
  voteUndoElement = $('.updown-widget').find('.updown-voteundo');

  // clicking on the '+' or '-' buttons
  voteElement.find('a.thumbUp').click(function() {
	  if( $(this).hasClass('voted') || $(this).hasClass('votingDisabled') ) {  
	  	return false;
	  }
	  else{
	    $.get($(this).attr('href'), function(data) {
	      data = Drupal.parseJson(data);
	      $("#updown-widget-" + data.content_type +"-"+ data.content_id)
	        .find('.updown-plus-score')
	        .html(data.plus_score.toString())
	        .end()
	        .find('.updown-vote')
	        .find('.updown-voteup a').each(function(){
	        	$(this).attr('href', data.vote_full)
	        	disableVoteUp($(this))        	
	         })
	        .end();
	       });
	  }
	  return false;
  });
  
  // clicking on the '+' or '-' buttons
  voteElement.find('a.thumbDown').click(function() {
	  if( $(this).hasClass('voted') || $(this).hasClass('votingDisabled') ) {  
	  		return false;
	  }
	  else{
	    $.get($(this).attr('href'), function(data) {
	      data = Drupal.parseJson(data);
	      $("#updown-widget-" + data.content_type +"-"+ data.content_id)
	        .find('.updown-minus-score')
	        .html(data.minus_score.toString())
	        .end()        
	        .find('.updown-votedown a').each(function(){
	        	$(this).attr('href', data.vote_none)
	        	disableVoteDown($(this))
	         })        
	        .end();
	       });
	  }
	  return false;
  });

  // clicking on the 'undo' button
  voteUndoElement.find('a.thumbUp').click(function() {
    $.get($(this).attr('href'), function(data) {
      data = Drupal.parseJson(data);
      $("#updown-widget-" + data.content_type +"-"+ data.content_id)
        .find('.updown-current-score')
        .html(data.score.toString())
        .end()
        .find('.updown-vote')
        .find('.updown-voteup a').attr('href', data.vote_full)
        .end()
        .find('.updown-votedown a').attr('href', data.vote_none)
        .end()
        .show()
        .parents("#updown-widget-" + data.content_type +"-"+ data.content_id)
        .find(".updown-voteundo")
        .hide()
        .find('a')
        .attr('href', data.vote_undo);
    });
    // disable the normal link
    return false;
  });
};


function disableVoteUp(currentWidget) {
	currentWidget.addClass('voted');
	var container = currentWidget.parent().parent().parent().attr('id');
	$('#'+container+' a.thumbDown').addClass('votingDisabled');
	$('#'+container+' a.thumbDown').attr('href', 'javascript:void(0)');
}

function disableVoteDown(currentWidget) {
	currentWidget.addClass('voted');
	var container = currentWidget.parent().parent().parent().attr('id');
	$('#'+container+' a.thumbUp').addClass('votingDisabled');
	$('#'+container+' a.thumbUp').attr('href', 'javascript:void(0)');
}
