/**
 *  Utilizes AJAX to cast a vote on an object
 */
function castVote(obj, object_id, object_type, vote){

   data = {"object_id":object_id,"object_type":object_type,"vote":vote};

  login_callback = function(){
    $.ajax({
      url:          SITE_URL+"ajax/vote/castVote",
      data:         data,
      type:         "POST",
      dataType:     "json",
      success:      function(json){
        if ($(obj).is("input[type='button']")) castVoteInputButtonCallback(json);
        else castVoteCallback(json);
      }
    })
  };

  check_login(login_callback);
}

/**
 *  Post-AJAX callback function that handles success messaging and any HTML/DOM
 *  manipulation on the user's page
 */
function castVoteCallback(json){

  if (json.success==true) {
    if (json.payload.vote=='up') {
        if($('li#num_votes_' + json.payload.object_id).length > 0) {
            votes = parseInt($('li#num_votes_' + json.payload.object_id).html()) + 1;
        }
        else if($('li#num_votes_' + json.payload.object_id + '_big').length > 0) {
            votes = parseInt($('li#num_votes_' + json.payload.object_id + '_big').html()) + 1;
        }
    }
    else {
      if($('li#num_votes_' + json.payload.object_id).length > 0) {
            votes = parseInt($('li#num_votes_' + json.payload.object_id).html()) - 1;
        }
        else if($('li#num_votes_' + json.payload.object_id + '_big').length > 0) {
            votes = parseInt($('li#num_votes_' + json.payload.object_id + '_big').html()) - 1;
        }
    }


    if($('li#num_votes_' + json.payload.object_id).length > 0)
        $('li#num_votes_' + json.payload.object_id).html(votes);

    if($('li#num_votes_' + json.payload.object_id + '_big').length > 0)
        $('li#num_votes_' + json.payload.object_id + '_big').html(votes);

    //Check if element exist
    if($('a#vote_up_btn_' + json.payload.object_id).length > 0)
      $('a#vote_up_btn_' + json.payload.object_id).remove();

    //Check if element exist
    if($('a#vote_dn_btn_' + json.payload.object_id).length > 0)
      $('a#vote_dn_btn_' + json.payload.object_id).parent().remove();

    alert('You have successfuly cast your vote.');
  }
  else {
    alert(json.payload.message);
  }
}


/**
 *  Post-AJAX callback function that handles success messaging and any HTML/DOM
 *  manipulation on the user's page
 */
function castVoteInputButtonCallback(json){
  if (json.success==true) {
    if (json.payload.vote=='up')
      votes = parseInt($('input#vote_up_btn_' + json.payload.object_id + '_num').val()) + 1;
    else
      votes = parseInt($('input#vote_up_btn_' + json.payload.object_id + '_num').val()) - 1;

    // Update the vote button
    $('input#vote_up_btn_' + json.payload.object_id).val(votes);
    // Update store value
    $('input#vote_up_btn_' + json.payload.object_id + '_num').val(votes);

    alert('You have successfuly cast your vote.');
  }
  else {
    alert(json.payload.message);
  }
}
