var temp_entry_txt = '';
var qvote_help = null;
function setEntryStatus(type_specific_id, status) {
  if (status == 'finalist') text = 'This action will select the entry as a finalist and cause it to move into final voting. Are you sure you want to do this?';
  else text = 'This action will cause the entry to go back to the qualification phase as a non-finalist. Are you sure you want to do this?';
  if (confirm(text)) {
    set_entry_status(type_specific_id, status);
  }
}
function removeEntryFromQualification(type_specific_id, contest_id, contest_target_language_id, source_language, target_language) {
  if (confirm('Are you sure you want to disqualify this entry? If you do, it will be shown at the bottom of the page and will be visible only to admins and the author.')) {
    remove_entry_from_qualification(type_specific_id, contest_id, contest_target_language_id, source_language, target_language);
  }
}
function restoreEntryToContest(type_specific_id) {
  if ((confirm('This action will cause the entry to be put back into contention. Are you sure you want to do this?'))) {
    un_remove_entry_from_qualification(type_specific_id);
  }
}
function removeEntryFromContest(type_specific_id) {
  if ((confirm('Are you sure you want to remove this entry? If you do, it will disappear from the page.'))) {
    remove_entry_from_contest(type_specific_id);
  }
}
function hideFullText(div_counter) {
  $("#source_text_full_" + div_counter).hide();
  $("#source_text_sub_" + div_counter).show();
}
function fullTextDetails(contest_id, contest_entry_id, phase_force) {
  if (phase_force == undefined) {
    phase_force = '';
  }
  msgWindow = window.open("/?sp=contests&float=1&view=full_details&contest_id=" + contest_id + "&contest_entry_id=" + contest_entry_id + phase_force, "SourceTextDetails", "toolbar=0,location=0,directories=0,status=0,menubar=0,resizable=yes,scrollbars=1,width=550,height=460");
  msgWindow.focus();
}
function fullTextWindow(contest_text_id, sub_contest_text_id, phase_force) {
  if (phase_force == undefined) {
    phase_force = '';
  }
  msgWindow = window.open("/?float=1&sp=contests&view=full_text&contest_text_id=" + contest_text_id + phase_force, "SourceTextDetails" + sub_contest_text_id, "toolbar=0,location=0,directories=0,status=0,menubar=0,resizable=yes,scrollbars=1,width=550,height=460");
  msgWindow.focus();
}
function showContestText(contest_text_id, div_counter, source_contest_text_id) {
  $("#main_lang_" + contest_text_id).hide();
  $("#winners_div_" + contest_text_id).hide();
  $("#source_text_full_" + div_counter).hide();
  $("#source_text_sub_" + div_counter).show();
  $("#winners_div_" + source_contest_text_id).show();
  $("#main_lang_" + source_contest_text_id).show();
}
function vv(name_obj, new_value) {
  obj = document.getElementById(name_obj);
  if (obj != null) { obj.value = new_value; return true;}
  return false;
}
var bvote_help = null;
function showPartner(eid, name, photo_name, div_id) {
  obj = document.getElementById("layerPartner["+div_id+"]");
  if (obj != null) {
   photo_html_out = "";
   if (photo_name != "") photo_html_out = "<td valign=top><div class=phsd><img src=\""+photo_name+"\" width=60></div></td>";
   remove_link_html_out = "[<a href=\"javascript:removePartner("+div_id+");\">remove</a>]";
   obj.innerHTML = "<table border=0><tr>"+photo_html_out+"<td valign=top><input type=hidden id=partner_ids["+div_id+"] name=partner_ids["+div_id+"] value=\""+eid+"\"><a href=\"/profile/"+eid+"\">"+name+"</a><br>"+remove_link_html_out+"";
  }
}
function removePartner(div_id) {
  obj = document.getElementById("layerPartner["+div_id+"]");
  if (obj != null) {
    out = "<table><tr><td valign=top></td><td valign=top>";
    out += "</font>";
    out += "  Did you work with a partner on this contest entry? If so, identify your partner now: [<a href=\"javascript:msgWindow = window.open(\'/?sp=event/contest_select_user&float=y&inputid="+div_id+"\', \'msgWindow\', \'toolbar=0,location=0,directories=0,status=0,menubar=0,resizable=0,scrollbars=1,width=300,height=400\'); msgWindow.focus();\">Search</a>]</font>";
    out += "</td></tr></table>";
    obj.innerHTML =out;
  }
}
function nl2br(str) {
 return str.replace(/\n/g,"<br>");
}
function br2nl(str) {
  if ($.browser.msie) {
   str = str.replace(/<BR>/g,"\n");
   str = str.replace(/<br>/g,"\n");
   str = str.replace(/<Br>/g,"\n");
   return  str;
  }
  else return str.replace(/<br>/g,"");
}
function makeFormNote(eid) {
  out = '<form action="/?sp=contests' + phase_force + '&sp_mode=' + sp_mode + '&sp_sub_mode=view_language&ctlid=' + ctlid + '&submit=add_note&contest_entry_id=' + eid + '#' + eid + '" method="POST">';
  out += '<textarea style="overflow:auto;width:460px;" rows="4" cols="67" name="note" id="note"></textarea>';
  out += '<br>Note: <select name="to"><option value="public" selected>to all</option><option value="contestant">to contestant only</option><option value="staff">to staff only</option></select>';
  out += '&nbsp;&nbsp;<input type="submit" name="add_note" value="Add note">';
  out += '&nbsp;&nbsp;<input type="button" name="cancel_note" value="Cancel" onclick="cancelFormNote(' + eid + ');">';
  out += '</form>';
  $("#e_" + eid).html(out);
}
function editNote(nid, eid) {
  $("#note_options_" + nid).css("visibility", "hidden");
  note = $("#nn_" + nid).html();
  out = '';
  out += '<form action="/?sp=contests' + phase_force + '&sp_mode=' + sp_mode + '&sp_sub_mode=view_language&ctlid=' + ctlid + '&submit=save_note&contest_entry_id=' + eid + '&contest_note_id=' + nid + '#' + eid + '" method="POST">';
  out += '<input type=hidden id="cancel_' + nid + '" value="' + escape(note) + '"><textarea style="overflow:auto;width:455px;" rows="4"  name="note" id="note">' + br2nl(note) + '</textarea>';
  out += '<br><input type="submit" name="save_note" value="Save">';
  out += '&nbsp;&nbsp;<input type="button" name="cancel_note" value="Cancel" onclick="cancelFormEditNote(' + nid + ', ' + eid + ');">';
  out += '</form>';
  $("#nn_" + nid).html(out);
}
function cancelFormEditNote(nid, eid) {
  $("#note_options_" + nid).css("visibility", "visible");
  note = $("#nn_" + nid).html(unescape($("#cancel_" + nid).val()));
}
function cancelFormNote(eid) {
  out = '<input type="button" name="add_note" value="Add note" onclick="makeFormNote(' + eid + ');">';
  container = $('e_' + eid).html(out);
}
function editFeedback(fid, eid) {
  $("#feedback_options_" + fid).hide();
  feedback = $("#ff_" + fid).html();
  out = '<form action="/?sp=contests' + phase_force + '&sp_mode=' + sp_mode + '&sp_sub_mode=' + sp_sub_mode + '&ctlid=' + ctlid + '&submit=save_feedback&contest_feedback_id=' + fid + '#feedback_' + fid + '" method="POST">';
  out += '<input type="hidden" id="cancel_feedback_' + fid + '" value="' + escape(feedback) + '"><textarea style="overflow:auto" rows="4" cols="80" name="feedback" id="feedback">' + br2nl(feedback) + '</textarea>';
  out += '<br><input type="submit" name="save_feedback" value="Save">';
  out += '&nbsp;&nbsp;<input type=button name="cancel_feedback" value="Cancel" onclick="cancelFormEditFeedback(' + fid + ', ' + eid + ');">';
  out += '</form>';
  $("#ff_" + fid).html(out);
  autoResize("feedback", "#ff_" + fid);
}
function cancelFormEditFeedback(fid, eid) {
  $("#feedback_options_" + fid).show();
  $("#ff_"+fid).html(unescape($("#cancel_feedback_" + fid).val()));
}
function autoResize(box_name, container) {
  box_size = $("#" + box_name).width();
  max_width = $("#" + container).width();
  while (box_size < max_width)
  $("#" + box_name).attr("cols", Number($("#" + box_size).attr("cols")) + Number(1));
}
function vTargetLanguage(dropdown, button) {
   btn = document.getElementById(button);
   btn.disabled = dropdown.options[0].selected;
}
$(document).ready(function() {
  $("span[id^='selected_text_']").each(function() {
    $(this).bind("mouseenter",function(){
      span_id = $(this).attr("id").replace("selected_text_", "");
      params = span_id.split("_");
      if (!existSelectedText()) {
        showHighLightedText(params[0], params[1], $(this).html() , params[2]);
      }
    });
  });
  $("span[id^='selected_text_']").each(function() {
    $(this).bind("mouseout", function(){
      span_id = $(this).attr("id").replace("selected_text_", "");
      if (!existSelectedText() && tmp_entry_text.length > 0) {
        $("#ta_target" + params[0]).html(tmp_entry_text);
      }
    });
  });
});
function showAgreementForm(opinion, agreement, contest_entry_tag_id, is_own_entry, contest_entry_id) {
  var agree_form = '';
  agree_form += '<span style="font-size:10px;"><b>Comment (optional)</b> <br>Subject to vetting by site staff.</span><br>';
  agree_form += '<input type="text" id="agreement_comment_' + contest_entry_tag_id + '" value="" ';
  agree_form += 'onKeyDown="textCounter(this,document.getElementById(\'agree_' + (agreement == 'disagree' ? 'dis' : '') + 'like_counter_' + contest_entry_tag_id + '\'),70)" ';
  agree_form += 'onKeyUp="textCounter(this,document.getElementById(\'agree_' + (agreement == 'disagree' ? 'dis' : '') + 'like_counter_' + contest_entry_tag_id + '\'),70)" ';
  agree_form += '> ';
  agree_form += '<input readonly type="text" id="agree_' + (agreement == 'disagree' ? 'dis' : '') + 'like_counter_' + contest_entry_tag_id + '" size="2" maxlength="2" value="70">';
  agree_form += '<br><span style="font-size:10px;"><b>Link</b></span><br>';
  agree_form += '<input id="reason_link_' + agreement + '_' + contest_entry_tag_id + '" type="text" value="http://" style="width:138px;">';
  agree_form += '<br><input class="brown_button" id="agree_submit" value="' + (agreement == 'agree' ? 'Agree' : 'Disagree') + '" type="button">';
  if (agreement == "agree") {
    $("#div_disagree_" + contest_entry_tag_id).html('');
    if ($("#div_agree_" + contest_entry_tag_id).html() == '') {
      $("#div_agree_" + contest_entry_tag_id).html(agree_form);
      $("#agree_submit").click(function() {
        if (tagAgreeDisagreeSubmit(opinion, agreement, contest_entry_tag_id, (is_own_entry ? '"true"' : '"false"') , contest_entry_id)) {
          this.disabled = true;
        }
      });
    } else {
      $("#div_agree_" + contest_entry_tag_id).html('');
    }
  } else {
    $("#div_agree_" + contest_entry_tag_id).html('');
    if ($("#div_disagree_" + contest_entry_tag_id).html() == '') {
      $("#div_disagree_" + contest_entry_tag_id).html(agree_form);
      $("#agree_submit").click(function() {
        if (tagAgreeDisagreeSubmit(opinion, agreement, contest_entry_tag_id, (is_own_entry ? '"true"' : '"false"') , contest_entry_id)) {
          this.disabled = true;
        }
      });
    } else {
      $("#div_disagree_" + contest_entry_tag_id).html('');
    }
  }
}
function callShowTagWindow(uniq_id, type_specific_id, can_qualify_only_quality) {
  var twice_or_more = "";
  $("#lb_" + uniq_id).click(function() {
    var str = getSelText(type_specific_id);
    twice_or_more = getOccurrences(str, type_specific_id, uniq_id, 1, can_qualify_only_quality);
    if (twice_or_more && twice_or_more.length < 2) {
      showTagWindow(type_specific_id, 1, str, uniq_id, can_qualify_only_quality, twice_or_more[0]);
    }
  });
  $("#db_" + uniq_id).click(function() {
    var str = getSelText(type_specific_id);
    twice_or_more = getOccurrences(str, type_specific_id, uniq_id, -1, can_qualify_only_quality);
    if (twice_or_more && twice_or_more.length < 2)
    showTagWindow(type_specific_id, -1, str, uniq_id, can_qualify_only_quality, twice_or_more[0]);
  });
}
function showHighLightedText(contest_entry_id, start, selected_text, ocurrance) {
  tmp_entry_text = $("#ta_target" + contest_entry_id).html();
  highLightSelectedText(contest_entry_id,start,selected_text,ocurrance);
  document.getElementById("ta_target" + contest_entry_id).scrollTop = document.getElementById(contest_entry_id + "_" + ocurrance).offsetTop - document.getElementById("ta_target" + contest_entry_id).offsetHeight + 50;
}
function highLightSelectedText(entry_id, index, selected_text, occurrence) {
    var tmp_txt = $('#ta_target' + entry_id).html();
    tmp_txt = tmp_txt.replace(/<br>/g, "\n");
    tmp_txt = tmp_txt.replace(/<BR>/g, "\n");
    tmp_txt = tmp_txt.replace(/<\/?[^>]+(>|$)/g, "");
    tmp_txt = tmp_txt.replace(/\n/g, "<br>");
    while (tmp_txt.indexOf("&nbsp;") >= 0) {
      tmp_txt = tmp_txt.replace("&nbsp;", " ");
    }
    var txt_array = new Array();
    txt_array = tmp_txt.split(selected_text);
    var final_txt = '';
    for (i=1; i < txt_array.length + 1; i++) {
      if (i == occurrence) {
        final_txt += txt_array[i - 1] + "<span id='" + entry_id + "_" + occurrence + "' style='background:#C8EF68;padding:2 0 2 0;'>" + selected_text + "</span>";
      } else {
        if (i < txt_array.length) {
          final_txt += txt_array[i - 1] + selected_text;
        } else {
          final_txt += txt_array[i - 1];
        }
      }
    }
    $('#ta_target' + entry_id).html('<span class="sm" style="border-bottom: 1px dashed rgb(184, 183, 143);">' + final_txt + '</span>');
    return;
}
// This function hide/show the buttons to vote in final round
function hideVoteOption(not_me, value, ctlid, my_entry_id) {
  $('div.voting_div').each(function(e) {
    var id_string = this.id.toString();
    var id_to_send = id_string.substring(14, id_string.length);
    var obj_header = $('#entry_header_' + id_to_send);
    var name_of_class = obj_header[0].className;
    var undo_button = '<span style="background-color: #BFBFBF;padding:3px;border: 1px solid #6F6F6F;cursor:pointer;" onclick="undoVote(' + id_to_send + ', ' + value + ')">remove this vote</span>';
    if (value == 4) {
      if (this.id != 'voting_option_' + not_me && name_of_class != "headerEntryVotedSecond" && name_of_class != "headerEntryVotedFirst") {
        $(this).html('<span class="buttonEntryVotedSecond" style="cursor:pointer;" onClick="if (confirm(\'Are you sure you want to give 2 points to this entry?\')) {save_final_round_vote(' + id_to_send + ', 2, ' + ctlid + ', ' + my_entry_id + ')}">Vote for your 2nd choice</span>');
      } else {
        $(this).html('');
      }
      $('#entry_header_' + not_me).addClass('headerEntryVotedFirst');
      $('#vote_txt_' + not_me).html('<font style="font-size:12px;font-weight:bold;color:black;">You selected this entry as the best.</font>');
      $('#voting_message_' + not_me).html('<font color="blue">Your vote has been saved</font>');
      setTimeout(function() {$('#voting_message_' + not_me).html("")}, 2000);
    }
    if (value == 2) {
      if (this.id != 'voting_option_' + not_me && name_of_class != "headerEntryVotedSecond" && name_of_class != "headerEntryVotedFirst") {
        $(this).html('<span class="buttonEntryVotedThirth" style="cursor:pointer;" onClick="if (confirm(\'Are you sure you want to give 1 points to this entry?\')) {save_final_round_vote(' + id_to_send + ', 1, ' + ctlid + ', ' + my_entry_id + ')}">Vote for your 3rd choice</span>');
      } else {
        $(this).html('');
      }
      $('#entry_header_' + not_me).addClass('headerEntryVotedSecond');
      $('#vote_txt_' + not_me).html('<font style="font-size:12px;font-weight:bold;color:black;">You selected this entry as 2nd best.</font>');
      $('#voting_message_' + not_me).html('<font color="blue">Your vote has been saved</font>');
      setTimeout(function() {$('#voting_message_' + not_me).html("")}, 2000);
    }
    if (value == 1) {
      $(this).html('');
      $('#entry_header_' + not_me).addClass('headerEntryVotedThirth');
      $('#vote_txt_' + not_me).html('<font style="font-size:12px;font-weight:bold;color:black;">You selected this entry as 3rd best.</font>');
      $('#voting_message_' + not_me).html('<font color="blue">Your vote has been saved</font>');
      setTimeout(function() {$('#voting_message_' + not_me).html("")}, 2000);
    }
    $('#none_is_good').html('');
  });
}
// This function is a callback when user undo a vote
function undoVote(id_div, value) {
  $('div.voting_div').each(function(e) {
    var obj_header = $('#entry_header_' + id_div);
    var name_of_class = obj_header[0].className;
    if (value == 4) {
      if (this.id != 'voting_option_' + not_me && name_of_class != "headerEntryVotedSecond" && name_of_class != "headerEntryVotedFirst") {
        $(this).html('<span class="buttonEntryVotedSecond" style="cursor:pointer;" onclick="hideVoteOption(' + id_to_send + ', 2);">Vote for your 2nd choice</span>');
      } else {
        $(this).html(undo_button);
      }
      $('#entry_header_' + not_me).addClass('headerEntryVotedFirst');
      $('#vote_txt_' + not_me).html('<font style="font-size:12px;font-weight:bold;color:black;">You selected this entry as the best.</font>');
      $('#voting_message_' + not_me).html('<font color="blue">Your vote has been saved</font>');
      setTimeout(function() {$('#voting_message_' + not_me).html("")}, 2000);
    }
    if (value == 2) {
      if (this.id != 'voting_option_' + not_me && name_of_class != "headerEntryVotedSecond" && name_of_class != "headerEntryVotedFirst") {
        $(this).html('<span class="buttonEntryVotedThirth" style="cursor:pointer;" onclick="hideVoteOption(' + id_to_send + ', 1);">Vote for your 3rd choice</span>');
      } else {
        $(this).html(undo_button);
      }
      $('#entry_header_' + not_me).addClass('headerEntryVotedSecond');
      $('#vote_txt_' + not_me).html('<font style="font-size:12px;font-weight:bold;color:black;">You selected this entry as 2nd best.</font>');
      $('#voting_message_' + not_me).html('<font color="blue">Your vote has been saved</font>');
      setTimeout(function() {$('#voting_message_' + not_me).html("")}, 2000);
    }
    if (value == 1) {
      $(this).html(undo_button);
      $('#entry_header_' + not_me).addClass('headerEntryVotedThirth');
      $('#vote_txt_' + not_me).html('<font style="font-size:12px;font-weight:bold;color:black;">You selected this entry as 3rd best.</font>');
      $('#voting_message_' + not_me).html('<font color="blue">Your vote has been saved</font>');
      setTimeout(function() {$('#voting_message_' + not_me).html("")}, 2000);
    }
  });
}
function ltrim(s) {
  return s.replace(/^\s+/, "");
}
function rtrim(s) {
  return s.replace(/\s+$/, "");
}
function trim(s) {
  return rtrim(ltrim(s));
}
var div_id_entry;
function getOccurrences(txt, div_id, uniq_id, opt, only_has_quality) {
  var original = $('#ta_target' + div_id).html();
  original = original.replace(/<br>/g, "\n");
  original = original.replace(/<\/?[^>]+(>|$)/g, "");
  original = original.replace(/\n/g, "<br>");
  var contador = 0;
  txt = trim(txt.toString());
  var pos_array = new Array();
  var otro = txt.toString();
  var acum = 0;
  if (opt == 1) {
    style = 'class="hl_tag_good"';
  } else {
    style = 'class="hl_tag_bad"';
  }
  var html_string = '';
  if (original && txt) {
    if (otro) {
      while (original.indexOf(otro) > -1) {
        acum = acum + original.indexOf(otro);
        if (contador > 0) {
          acum = acum + otro.length;
        }
        pos_array[contador] = acum;
        html_string += original.substring(0, original.indexOf(otro)) + '<span ' + style + '><a onClick="$(\'#repeated_linked_text_target' + div_id + '\').hide();$(\'#repeated_linked_text_target' + div_id + '\').css(\'background-color\', \'\');showTagWindow(' + div_id + ', ' + opt + ', \'' + txt + '\', \'' + uniq_id + '\', \'' + only_has_quality + '\', ' + acum + ', ' + (contador + 1) + ')">' + original.substring(original.indexOf(otro), original.indexOf(otro) + otro.length) + '</a></span>';
        original = original.substring(original.indexOf(otro) + otro.length, original.length);
        contador++ ;
      }
      html_string += original;
    }
    if (contador > 1) {
      header = "<div title='close window' onClick='$(\"#repeated_linked_text_target" + div_id + "\").hide();' style='text-align:right;cursor:pointer;'><img src='/images/contests/hide_cross_brown.gif'></div>";
      header += "<div style='font-size:11px;'><b>" + txt + "</b> is repeated <b>" + contador + "</b> times in this text. Please, select one by clicking on it</div><br>";
      html_string = '<span class="sm" style="border-bottom: 1px dashed rgb(184, 183, 143);">' + html_string + '</span>';
      $('#repeated_linked_text_target' + div_id).html(header + html_string);
      $('#repeated_linked_text_target' + div_id).css("display", "block");
      $('#repeated_linked_text_target' + div_id).css("background", "#F8F7F1");
      $('#repeated_linked_text_target' + div_id).show();
      return pos_array;
    } else return pos_array;
  }
}
function getSelText(div_id) {
  var txt = "";
  if (div_id) {
    div_id_entry = div_id;
  } else {
    div_id = div_id_entry;
  }
  if (window.getSelection) {
    userSelection = window.getSelection();
    txt = userSelection;
  }
  else if (document.getSelection) {
    userSelection = document.getSelection();
    txt = userSelection;
  }
  else if (document.selection) {
    userSelection = document.selection.createRange();
    txt = userSelection.text;
  }
  else return;
  var original = $('#ta_target' + div_id).html();
  if (original) {
    var selected = escape(txt);
    original = original.replace(/<br>/g, "\n"); // exchange html spaces
    original = original.replace(/<BR>/g, "\n");
    while (original.indexOf("&nbsp;") >= 0) {
      original = original.replace("&nbsp;", " "); // remove html spaces
    }
    original = original.replace(/\n/g, "<br>");
    original = escape(original.toString());
    is_allow_text =  original.search(selected);
    if (is_allow_text == -1) {
      txt = "";
      return txt.toString();
    }
  }
  var varleng = txt.toString();
  varleng = varleng.length;
  document.aform.selectedtext.value = txt;
  if (txt &&  varleng>200) {
    if (div_id) {
      alert("Please select 200 characters or less");
    }
    txt = "";
    return txt.toString();
  }
  return txt.toString();
}
function callbackRating(param, data) {
  $('#qvote_message' + param).html(data).show();
  setTimeout(function() {
    $('#qvote_message' + param).hide();
  }, 3000);
}
function show_not_allow_to_vote_lower_message(val) {
  alert('To be able to assign a rating < 3 you should provide a reason (dislike tag).');
}
function textCounter(field, cntfield, maxlimit) {
  if (field.value.length > maxlimit) // if too long...trim it!
  field.value = field.value.substring(0, maxlimit);
  else
  cntfield.value = maxlimit - field.value.length;
}
function showTagWindow(entry_id, tag, txt, unq_id, perm, position, occurrence) {
  showLoadingDiv("tag_window_" + unq_id);
  if (typeof(show_opt) != 'undefined') {
    if (show_opt == 'q') {
      perm=1;
    }
  }
  if (typeof(occurrence) == 'undefined') occurrence = 1;
  $("#tag_window_" + unq_id).show("normal");
  $.ajax({
    url: "/ajax/ajax_contests.php?action=tag_entry_frm&",
    data: "&entry_id=" + entry_id + "&tag=" + tag + "&unq_id=" + unq_id + "&txt=" + txt + "&hidefullopt=" + perm + "&position=" + position + "&occurrence=" + occurrence,
    type: "POST",
    timeout: 5000,
    error: function() {
      alert("Error.");
    },
    success: function(html) {
      $("#tag_window_" + unq_id).html(html);
      $("#tag_window_" + unq_id).show("normal");
    }
  });
}
function closeTagWindow(unq_id) {
  $("#tag_window_" + unq_id).hide("normal");
}
function acceptSelection(opt) {
  accept = opt;
}
function hideShowCommentInput(combo) {
  if (combo.options[combo.selectedIndex].value == "Other")
  $("#comment_div").show();
  else
  $("#comment_div").hide();
}
function showLoadingDiv(id) {
  var html = "";
  html += "<div class=\"p_shadow\" style=\"position:relative;\"><div class=\"tag_window\" style=\"width:150px;\">";
  html += "<img src=\"/images/wikiwords/loading.gif\"> <b>Loading</b>";
  html += "</div></div>";
  $("#" + id).html(html);
}
function toggleAllTagsWindow(entry_id, only_has_quality, design_type, finished_pair) {
  if (!design_type) design_type = "";
  if (typeof(finished_pair) == 'undefined') finished_pair = 0;
  showLoadingDiv("view_all_tags_container");
  $.ajax({
    url: "/ajax/ajax_contests.php?action=show_all_tags&",
    data: "entry_id=" + entry_id + "&view_opt=" + only_has_quality + "&design_type=" + design_type + "&finished_pair=" + finished_pair,
    type: "POST",
    success: function(html) {
      $("#view_all_tags_container_" + entry_id).html(html);
      $("#view_all_tags_container_" + entry_id).show("normal");
      if (html.length > 0) {
        $("#view_tags_link_div_" + entry_id).show();
        $("#view_tags_link_" + entry_id).hide();
      }
      // Update the sections that should be highlighted
    }
  });
}
function submitFormAjax(frm_id, unq_id, entry_id, txt, reason, only_has_quality) {
  var inputs = [];
  var data;
  $("#" + frm_id + " input").each(function() {
    if (this.name == "selected_txt" && 0) {
      // var txt = this.value;
    } else {
      if (this.name != "") {
        inputs.push(this.name + "=" + escape(this.value));
        data += "&" + this.name + "=" + this.value;
      }
    }
  });
  data += "&reason=" + reason;
  showLoadingDiv("tag_window_" + unq_id);
  $.ajax({
    url: "/ajax/ajax_contests.php?action=tag_entry_save",
    type: "POST",
    data: data,
    timeout: 5000,
    error: function() {
      alert("Error.");
    },
    success: function(html) {
      $("#tag_window_" + unq_id).html(html);
      $("#tag_window_" + unq_id).show("normal");
      // Update the sections that should be highlighted
      updateEntryHighlightedText(entry_id, unq_id);
      toggleAllTagsWindow(entry_id, only_has_quality);
      setTimeout("$(\'#tag_saved_message\').remove();", 1000);
    }
  });
  return false;
}
function getCheckedValue(radioObj) {
  if (!radioObj) {
    return "";
  }
  var radioLength = radioObj.length;
  if (radioLength == undefined) {
    if (radioObj.checked) {
      return radioObj.value;
    } else {
      return "";
    }
  }
  for (var i = 0; i < radioLength; i++ ) {
    if (radioObj[i].checked) {
      return radioObj[i].value;
    }
  }
  return "";
}
function updateEntryHighlightedText(entry_id, unq_id) {
  showLoadingDiv("ta_" + unq_id);
  $.ajax({
    url: "/ajax/ajax_contests.php?action=update_entry_display&",
    data: "&entry_id=" + entry_id,
    type: "POST",
    timeout: 5000,
    error: function() {
      alert("Error.");
    },
    success: function(html) {
      $("#ta_" + unq_id).html(html);
    }
  });
}
function remove_entry_from_qualification(entry_id, contest_id, ctlid, source_lang, target_lang) {
  $.ajax({
    url: "/ajax/ajax_contests.php",
    data: "action=remove_entry_from_qualification&entry_id=" + entry_id + "&contest_id=" + contest_id + "&ctlid=" + ctlid + "&source_lang=" + source_lang + "&target_lang=" + target_lang,
    type: "POST",
    timeout: 5000,
    error: function() {
      alert("Error.");
    },
    success: function(back) {
      if (back == "OK") {
        window.location.reload();
      } else {
        alert('Error.');
      }
    }
  });
}
function un_remove_entry_from_qualification(entry_id) {
   $.ajax({
    url: "/ajax/ajax_contests.php",
    data: "action=un_remove_entry_from_qualification&entry_id=" + entry_id,
    type: "POST",
    timeout: 5000,
    error: function() {
      alert("Error.");
    },
    success: function(back) {
      if (back == "OK") {
        window.location.reload();
      } else {
        alert('Error.');
      }
    }
  });
}
function check_last_user_dislike_and_vote(entry_id) {
  var can_remove = false;
  $.ajax({
    url: "/ajax/ajax_contests.php",
    data: "action=check_last_dislike_and_lower_vote&entry_id=" + entry_id,
    async: false,
    type: "POST",
    error: function() {
      alert("Error.");
    },
    success: function(result) {
      if (result == "can_remove") {
        can_remove = true;
      } else {
        can_remove = false;
      }
    }
  });
  return can_remove;
}
function remove_entry_from_contest(entry_id) {
  $.ajax({
    url: "/ajax/ajax_contests.php",
    data: "action=remove_entry_from_contest&entry_id=" + entry_id,
    type: "POST",
    timeout: 5000,
    error: function() {
      alert("Error.");
    },
    success: function(back) {
      if (back == "OK") {
        window.location.reload();
      } else {
        alert('Error.');
      }
    }
  });
}
function showAgreementWindow(tag_id, entry_id) {
  $.ajax({
    url: "/ajax/ajax_contests.php",
    data: "action=make_agreement_windows&tag_id=" + tag_id + "&entry_id=" + entry_id,
    type: "POST",
    timeout: 5000,
    error: function() {
      alert("Error.");
    },
    success: function(data) {
      $('#tag_window_target' + entry_id).html(data);
      $('#tag_window_target' + entry_id).show();
    }
  });
}
function ToggleUserVisibility(entry_id, entity_id) {
$.ajax({
    url: "/ajax/ajax_contests.php",
    data: "action=toogle_user_visibility&entity_id=" + entity_id + "&entry_id=" + entry_id,
    type: "POST",
    timeout: 5000,
    error: function() {
      alert("Error.");
    },
    success: function(data) {
      if (data == "error") {
        alert("Error");
      } else {
        $('#user_visibility_status' + entry_id).html(data);
      }
    }
  });
}
function set_entry_status(entry_id, option) {
var status = option;
$.ajax({
    url: "/ajax/ajax_contests.php",
    data: "action=set_entry_status&entry_id=" + entry_id + "&status=" + status,
    type: "POST",
    timeout: 5000,
    error: function() {
      alert("Error.");
    },
    success: function(data) {
      if (data == "error") alert("Error");
      if (status == "finalist" && data == "OK") {
        $("#status_mark_" + entry_id).html("<span style='color:green;font-size:12px;'>Finalist</span>");
        $("#finalist_action_container_" + entry_id).html("<a style='cursor:pointer;' onclick='if (confirm(\"This action will cause the entry to go back to the qualification phase as a non-finalist. Are you sure you want to do this?\")) set_entry_status(\"" + entry_id + "\", \"\");'>back to qualif.</a>");
      }
      if (status== "" && data == "OK") {
        $("#status_mark_" + entry_id).html("");
        $("#finalist_action_container_" + entry_id).html("<a style='cursor:pointer;' onclick='if (confirm(\"This action will select the entry as a finalist and cause it to move into final voting. Are you sure you want to do this?\")) set_entry_status(\"" + entry_id + "\", \"finalist\");'>send to finals</a>");
      }
    }
  });
}
function save_final_round_vote(entry_id, value, ctlid, my_entry_id) {
  $.ajax({
    url: "/ajax/ajax_contests.php",
    data: "action=save_bvote&entry_id=" + entry_id + "&option=" + value + "&ctlid=" + ctlid,
    type: "POST",
    timeout: 5000,
    error: function() {
      alert('An error occured when attempting to save your best entry vote; if this error persists, please submit a support request.');
    },
    success: function(data) {
      if (data == "OK") {
        hideVoteOption(entry_id, value, ctlid, my_entry_id);
        $("#clear_my_votes").show();
        if (my_entry_id == entry_id && value == 4) {
           $("#entry_header_" + entry_id).prepend("<div style='display:table;width:460px;font-size:12px;background:#FFFF66;text-align:right;'><b>You selected this entry as the best.</b></div>");
        }
        if (my_entry_id == entry_id && value == 2) {
          $("#entry_header_" + entry_id).prepend("<div style='display:table;width:460px;font-size:12px;background:#E5AFFF;text-align:right;'><b>You selected your own entry as 2nd best.</b></div>");
        }
        if (my_entry_id == entry_id && value == 1) {
          $("#entry_header_" + entry_id).prepend("<div style=/display:table;width:460px;font-size:12px;background:#BBDFB5;text-align:right;'><b>You selected this entry as 3rd best.</b></div>");
        }
      } else {
        if (data == "error") {
          alert("Error, please try again");
        }
      }
    }
  });
}
function add_remove_entry_from_portfolio(entry_id, to_portfolio, contest_id) {
var portfolio_option = to_portfolio;
  $.ajax({
    url: "/ajax/ajax_entry_to_portfolio.php",
    data: "to_portfolio=" + portfolio_option + "&contest_id=" + contest_id + "&entry_id=" + entry_id,
    type: "POST",
    timeout: 5000,
    error: function() {
      alert("Error, please try again");
    },
    success: function(data) {
      if (data == "OK") {
        if (portfolio_option == 'y') {
          $("#portfolio_option_" + entry_id).html("<span onclick='if (confirm(\"Are you sure?\")) add_remove_entry_from_portfolio(" + entry_id + ", \"n\", " + contest_id + ")'>remove from portfolio</span>");
        }
        if (portfolio_option == 'n') {
          $("#portfolio_option_" + entry_id).html("<span onclick='if (confirm(\"Are you sure?\")) add_remove_entry_from_portfolio(" + entry_id + ", \"y\", " + contest_id + ")'>add to portfolio</span>");
        }
      } else {
        alert("Error, please try again");
      }
    }
  });
}
function removeTagComment(tag_id) {
  if (confirm('Are you sure you want to delete this comment?')) {
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_contests.php",
      dataType: "json",
      data: {
        action: "remove_comment",
        tag_id: tag_id
      },
      success: function(json) {
        if (json.is_success) {
          $("#tag_comment_" + tag_id).remove();
        } else {
          alert("Error trying to delete this comment, please try again");
        }
      }
    });
  }
}
function existSelectedText() {
  var txt = '';
  if (window.getSelection) {
    userSelection = window.getSelection();
    txt = userSelection;
  } else if (document.getSelection) {
    userSelection = document.getSelection();
    txt = userSelection;
  } else if (document.selection) {
    userSelection = document.selection.createRange();
    txt = userSelection.text;
  }
  if (txt != '') {
    return true;
  } else {
    return false;
  }
}
function tagAgreeDisagreeSubmit(tag_type, opinion, tag_id, is_own_entry, contest_entry_id) {
  var link_value = $('#reason_link_' + opinion + '_' + tag_id).val();
  var comment = $('#agreement_comment_' + tag_id).val();
  var tag_type_option = (opinion == 'agree' ? '1' : '0');
  var error = false;
  if (link_value != "http://" && link_value.length > 0) {
    if (checkURL(link_value) == false) {
      alert("The link is not valid");
      error = true;
    }
  }
  if (!error) {
    $.ajax({
      url: '/ajax/ajax_contests.php',
      type: 'POST',
      data: {
        action: 'save_agreement',
        option: tag_type_option,
        comment: comment,
        entry_tag_id: tag_id,
        is_my_entry: is_own_entry,
        entry_id: contest_entry_id,
        tag_type: tag_type,
        link: link_value,
        field_name: 'agreement_comment_' + tag_id,
        opinion: opinion,
        from: 'contest.js'
      },
      error: function() {
        alert('Error.');
        return false;
      },
      success: function(result) {
        if (result.length > 0) {
          $("#agreement_div_" + tag_id).html(result);
          return true;
        } else {
          alert('Error. Please try again.');
          return false;
        }
      }
    });
  }
}
function removeTagVerify(entry_id, tag_id, type) {
  if (type == "dislike" && !check_last_user_dislike_and_vote(entry_id)) {
    alert('You cannot remove this tag because a reason is required for assigning ratings less than 3');
    return false;
  }
  if (confirm('Are you sure you want to delete this tag?')) {
    $('#td_' + tag_id).load('/ajax/ajax_contests.php?action=remove_tag&tag_id=' + tag_id);
    updateEntryHighlightedText(entry_id, 'target' + entry_id);
  }
}
