/*global $, counter_visible, table_form_input, user_information, cons_time, seconds, update_timer, entries, is_glossary_type, font_size_kudoz */
var helpterm_id = "";
var eid_v = "";
function voteChangeLevel(vote, helpterm_id) {
  var show_buttons = "";
  var description = "";
  var message = "";
  show_buttons = {
    "Yes": 1,
    "No": 0
  }
  if (vote === "easy") {
    message = "Are you sure that this question could be answered by any bilingual person without the aid of a dictionary?";
  } else if (vote === "pro") {
    message = "Are you sure that this question is suitable for a professional translator?";
  } else {
    message = "Invalid level";
    show_buttons = {
      "Close": 0
    }
  }
  description = '<form method="post" id="vote_form"><h2>' + message + '</h2><input type="hidden" name="submit_array[vote_easy_pro]" value="' + vote + '"></form>';
  $.prompt(description, {
    submit: function(v, m) {
      if (v == 1 && (vote === "easy" || vote === "pro")) {
        $("#vote_form").submit();
      }
      return true;
    },
    buttons: show_buttons
  });
}
function peerCommentUnHide(helpterm_reply_id, entity_id) {
  if (confirm("Are you sure?")) {
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_kudoz.php",
      data: {
        action: "unHidePeerComment",
        helpterm_reply_id: helpterm_reply_id,
        eid_v: eid_v,
        peer_entity: entity_id
      },
      success: function () {
        document.location.href = "/kudoz/" + helpterm_id + "#" + helpterm_reply_id;
        document.location.reload();
      }
    });
  }
}
function peerCommentHide(helpterm_reply_id, entity_id, has_comment) {
  var custom_msg_form = '';
  if (has_comment === true) {
    custom_msg_form += 'Reason for making peer comment invisible:<br>';
    custom_msg_form += '<input type="radio" name="reason" class="reason" value="offensive"> Offensive and/or personal rather than linguistic<br>';
    custom_msg_form += '<input type="radio" name="reason" class="reason" value="adult_content"> Adult nature and/or profane<br>';
    custom_msg_form += '<input type="radio" name="reason" class="reason" value="other"> Other <input type="text" size="30" maxlength="100" id="other_reason"><br>';
    custom_msg_form += '<input type="hidden" id="has_comment" value="n">';
    custom_msg_form += '<div>The poster of the comment will be notified of your site name, action and reason.</div>';
  } else {
    custom_msg_form += 'Justification for removing empty agree:<br><br>';
    custom_msg_form += '<input type="text" size="30" maxlength="100" id="other_reason"><br>';
    custom_msg_form += '<input type="hidden" id="reason" value="other">';
    custom_msg_form += '<input type="hidden" id="has_comment" value="y">';
    custom_msg_form += '<div>The poster of the comment will be notified of your site name, action and reason.</div>';
  }
  $.prompt(custom_msg_form, {
    submit: function (v, m) {
      var reason = '';
      var reason_id = '';
      var has_comment = m.children('#has_comment').val();
      if (v === true) {
        if (has_comment === 'y') {
          reason_id = m.children('#reason').val();
          reason = m.children("#other_reason").val();
          if (reason === '' || reason === undefined) {
            alert('Please insert your reason');
            return false;
          }
        } else {
          reason_id = m.children(".reason:checked").val();
          if (reason_id === '' || reason_id === undefined) {
            alert('Please select a reason');
            return false;
          } else {
            if (reason_id === 'other') {
              reason = m.children("#other_reason").val();
              if (reason === '' || reason === undefined) {
                alert('Please insert your reason');
                return false;
              }
            }
          }
        }
      }
      return true;
    },
    callback: function (v, m) {
      if (v === true) {
        var reason = m.children("#other_reason").val();
        var reason_id = '';
        if (m.children('#has_comment').val() === 'y') {
          reason_id = m.children('#reason').val();
        } else {
          reason_id = m.children(".reason:checked").val();
        }
        $.ajax({
          type: "POST",
          url: "/ajax/ajax_kudoz.php",
          data: {
            action: "hidePeerComment",
            helpterm_reply_id: helpterm_reply_id,
            eid_v: eid_v,
            peer_entity: entity_id,
            reason: reason,
            reason_id: reason_id
          },
          success: function () {
            document.location.href = "/kudoz/" + helpterm_id + "#" + helpterm_reply_id;
            document.location.reload();
          }
        });
      }
    },
    buttons: {
      'Hide': true,
      'Cancel': false
    }
  });
}
function rebuttalUnHide(helpterm_reply_id, entity_id) {
  if (confirm("Are you sure?")) {
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_kudoz.php",
      data: {
        action: "unHideRebuttalToPeer",
        helpterm_reply_id: helpterm_reply_id,
        eid_v: eid_v,
        peer_entity: entity_id
      },
      success: function () {
        document.location.href = "/kudoz/" + helpterm_id + "#" + helpterm_reply_id;
        document.location.reload();
      }
    });
  }
}
function rebuttalHide(helpterm_reply_id, entity_id) {
  var custom_msg_form = 'Reason for making reply to peer comment invisible:<br>';
  custom_msg_form += '<input type="radio" name="reason" class="reason" value="offensive"> Offensive and/or personal rather than linguistic<br>';
  custom_msg_form += '<input type="radio" name="reason" class="reason" value="adult_content"> Adult nature and/or profane<br>';
  custom_msg_form += '<input type="radio" name="reason" class="reason" value="other"> Other <input type="text" size="30" maxlength="100" id="other_reason"><br>';
  custom_msg_form += '<div>The poster of the reply to the comment will be notified of your site name, action and reason.</div>';
  $.prompt(custom_msg_form, {
    submit: function (v, m) {
      var reason = '';
      var reason_id = '';
      if (v === true) {
        reason_id = m.children(".reason:checked").val();
        if (reason_id === ''  || reason_id === undefined) {
          alert('Please select a reason');
          return false;
        } else {
          if (reason_id === 'other') {
            reason = m.children("#other_reason").val();
            if (reason === '' || reason === undefined) {
              alert('Please insert your reason');
              return false;
            }
          }
        }
      }
      return true;
    },
    callback: function (v, m) {
      if (v === true) {
        var reason = m.children("#other_reason").val();
        var reason_id = m.children(".reason:checked").val();
        $.ajax({
          type: "POST",
          url: "/ajax/ajax_kudoz.php",
          data: {
            action: "hideRebuttalToPeer",
            helpterm_reply_id: helpterm_reply_id,
            eid_v: eid_v,
            peer_entity: entity_id,
            reason: reason,
            reason_id: reason_id
          },
          success: function () {
            document.location.href = "/kudoz/" + helpterm_id + "#" + helpterm_reply_id;
            document.location.reload();
          }
        });
      }
    },
    buttons: {
      'Hide': true,
      'Cancel': false
    }
  });
}
function removeNote(section, id, note_id) {
  var custom_msg_form = '';
  if (section === "answer") {
    custom_msg_form += "<div align=\'center\'>If you delete this note to the answerer,<br> it cannot be restored. <br>Are you sure?<br></div>";
  } else {
    custom_msg_form += "<div align=\'center\'>If you delete this note,<br>it cannot be restored. <br>Are you sure?<br></div>";
  }
  $.prompt(custom_msg_form, {
    submit: function (v, m) {
      if (v === true) {
        document.location.href = "/kudoz/" + id + "?del_note=" + note_id + "&type=asker_notes";
      } else {
        return true;
      }
    },
    buttons: {
      "Delete": true,
      "Cancel": false
    }
  });
}
function editKudoZAnswer(kudoz_reply_id, field_id, is_glossary_type, type) {
  if ($("#text" + field_id).length === 0) {
    var content = $("#" + field_id).html();
    content = content.replace(/\n/g, "");
    content = content.replace(/<br>/g, "\n");
    var input_type = '';
    if (type === 'input') {
      input_type = '<input type="text" size="50" id="text' + field_id + '" value="' + content + '">';
    } else {
      input_type = '<textarea id="text' + field_id + '" cols="60%" rows="12">' + content + '</textarea>';
    }
    input_type += '<br><input type="button" value="Save Changes" onclick="editKudoZAnswerSave(\'' + kudoz_reply_id + '\', \'' + field_id + '\', \'' + is_glossary_type + '\', \'' + type + '\');">';
    input_type += '<input type="button" value="cancel" onclick="editKudozAnswerCancel(\'' + kudoz_reply_id + '\', \'' + field_id + '\');">';
    $("#" + field_id).html(input_type);
  }
}
function editKudozAnswerCancel(kudoz_reply_id, field_id) {
  if ($("#text" + field_id).length > 0) {
    var content = $("#text" + field_id).val();
    $("#" + field_id).html(content.replace(/\n/g, "<br>"));
  }
}
function editKudoZAnswerSave(kudoz_reply_id, field_id, is_glossary_type) {
  if ($("#text" + field_id).length > 0) {
    var content = $("#text" + field_id).val();
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_kudoz.php",
      data: {
        action: "editKudozAnswer",
        kudoz_reply_id: kudoz_reply_id,
        field: field_id,
        content: content,
        is_glossary_type: is_glossary_type
      },
      success: function (html) {
        $("#text" + field_id).html(html);
      }
    });
    editKudozAnswerCancel(kudoz_reply_id, field_id);
  }
}
function editExample(helpterm_reply, order) {
  var name = $("input#hide_name_example_sentences_" + helpterm_reply + "_" + order).val();
  var link = $("input#hide_link_example_sentences_" + helpterm_reply + "_" + order).val();
  var content = '';
  content += '<table><tr><td>Name</td><td><input type="text" size="50" id="input_name_' + helpterm_reply + '_' + order + '" value="' + name + '"></td></tr>';
  content += '<tr><td>Link</td><td><input type="text" size="50" id="input_link_' + helpterm_reply + '_' + order + '" value="' + link + '"></td></tr>';
  content += '<tr><td><input type="button" value="Save" onclick="saveExample(\'' + helpterm_reply + '\', \'' + order + '\');"></td>';
  content += '<td><input type="button" onclick="closeExample(\'' + helpterm_reply + '\', \'' + order + '\');" value="Cancel"></td></tr></table>';
  $("span#example_sentences_" + helpterm_reply + "_" + order).html(content);
}
function closeExample(helpterm_reply, order) {
  var name = $("input#hide_name_example_sentences_" + helpterm_reply + "_" + order).val();
  var link = $("input#hide_link_example_sentences_" + helpterm_reply + "_" + order).val();
  var content = '<a href="' + link + '" target="_blank">' + name + '<img src="/images/wikiwords/small_grey_arr.gif" border="0"></a>';
  $("span#example_sentences_" + helpterm_reply + "_" + order).html(content);
}
function saveExample(helpterm_reply, order) {
  var name = $("input#hide_name_example_sentences_" + helpterm_reply + "_" + order).val();
  var link = $("input#hide_link_example_sentences_" + helpterm_reply + "_" + order).val();
  var new_name = $("input#input_name_" + helpterm_reply + "_" + order).val();
  var new_link = $("input#input_link_" + helpterm_reply + "_" + order).val();
  if (name !== new_name || link !== new_link) {
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_kudoz.php",
      data: "action=kudozPullEditExample&helpterm_reply=" + helpterm_reply + "&order=" + order + "&name=" + encodeURIComponent(new_name) + "&link=" + encodeURIComponent(new_link),
      success: function (code) {
        if (code !== "") {
          alert(code);
        } else {
          $("input#hide_name_example_sentences_" + helpterm_reply + "_" + order).val(new_name);
          $("input#hide_link_example_sentences_" + helpterm_reply + "_" + order).val(new_link);
          closeExample(helpterm_reply, order);
        }
      }
    });
  } else {
    closeExample(helpterm_reply, order);
  }
}
$("#report_question").click(function () {
  $("#mod_report_options").show();
});
$("#cancel_request_button").click(function () {
  $("#mod_report_options").hide();
  $("#report_preview").hide();
});
$("#preview_request_button").click(function () {
  $("#what_should").html($("#edit_request_for").val());
  $("#please_explain").html($("#edit_request_why").val());
  $("#report_preview").show();
});
$("#send_request_button").click(function () {
  var error = false;
  var request_for = $.trim($("#edit_request_for").val());
  var request_why = $.trim($("#edit_request_why").val());
  if (request_for === "" || request_why === "") {
    error = true;
  }
  if (error === true) {
    alert("Please complete all the fields");
  } else {
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_kudoz.php",
      data: {
        action: "request_ticket",
        eid_v: eid_v,
        request_for: request_for,
        request_why: request_why,
        helpterm_id: helpterm_id
      },
      success: function (ticket_id) {
        alert("Your ticket id is: " + ticket_id);
        $("#mod_report_options").hide();
        $("#request_why").val("");
        $("#request_for").val("");
        $("#report_preview").hide();
      }
    });
  }
});
$("#discussion_counter").click(function () {
  counter_visible = $(this).attr("checked") ? true : false;
  $.ajax({
    type: "POST",
    url: "/ajax/ajax_kudoz.php",
    data: {
      action: 'displayRefreshCounter',
      eid_v: eid_v,
      status: counter_visible
    },
    success: function () {
      if (counter_visible) {
        $("#update_counter_div").show();
      } else {
        $("#update_counter_div").hide();
      }
    }
  });
});
function sendDiscussionNotification(title, text) {
  $.ajax({
    type: "POST",
    url: "/ajax/ajax_kudoz.php",
    data: {
      action: "sendDiscussionNotification",
      eid_v: eid_v,
      helpterm_id: helpterm_id,
      title: title,
      text: text
    }
  });
}
function updateEntries(total_entries) {
  $.ajax({
    type: "POST",
    url: "/ajax/ajax_kudoz.php",
    data: "action=updateDiscussion&eid_v=" + eid_v + "&total_entries=" + total_entries + "&helpterm_id=" + helpterm_id,
    success: function (html) {
      var part = html.split("||");
      var count = part[1];
      var show_entries = false;
      var make_update = 'no';
      if (part[0] === "renew") {
        show_entries = true;
        $("#inner_center").html("");
        entries = parseInt(count, 10);
      } else {
        show_entries = false;
      }
      if (show_entries) {
        var div_scroll = 0;
        var b = 2;
        $("#center_div").show();
        if (count > 0) {
          var a = count;
          for (a = count; a > 0; a--) {
            $("#inner_center").append(part[b]);
            b += 1;
          }
          var actual_height = $("#inner_center").innerHeight();
          if (actual_height > 300) {
            $("#center_div").animate({
              height: "300px"
            }, 500, function () {
              $("#center_div").css("overflow", "auto");
            });
          } else {
            $("#center_div").animate({
              height: actual_height + "px"
            }, 500, function () {
              $("#center_div").css("overflow", "");
            });
          }
          if (div_scroll > 0) {
            document.getElementById("center_div").scrollTop = div_scroll;
          }
        }
        $("#total_entries").text(entries);
        if (update_timer) {
          clearInterval(update_timer);
        }
        seconds = cons_time;
        make_update = 'yes';
      }
      updateCounter(make_update);
    }
  });
}
function updateCounter(make_update) {
  if (seconds < cons_time) {
    var seconds_left = 0;
    var show_second = 0;
    if (seconds === 0) {
      if (counter_visible) {
        $("#update_counter_div").show("slow");
      }
      update_timer = setInterval(updateCounter, 1000);
    }
    seconds += parseInt(1, 10);
    seconds_left = cons_time - seconds;
    if (seconds_left < 10) {
      show_second = "0" + seconds_left;
    } else {
      show_second = seconds_left;
    }
    $("#update_counter").text(show_second);
  } else {
    seconds = 0;
    clearInterval(update_timer);
    if (make_update !== 'yes') {
      updateEntries(entries);
    } else {
      make_update = 'no';
      updateCounter();
    }
  }
}
function viewAllButtons(show_form) {
  var center_div_visibility = $("#center_div").css("display");
  var max_height = $("#center_div").innerHeight() + "px";
  if ($("#center_div").innerHeight() > 300) {
    max_height = "300px";
  }
  $("#center_div").css("height", "1");
  $(".close_discussion_button").show();
  $(".view_all_button").hide();
  $("#center_div").animate({
    height: max_height,
    opacity: 1
  }, 1000, function () {
    if ($("#entry_title").val() === undefined) {
      $("#top_buttons").fadeOut("slow");
      $("#bottom_buttons").show("slow");
      $("#discussion_options_div").show("slow");
      $("#center_div").css("overflow", "auto");
    }
    $("#discussion_options_div").show("slow");
    if (show_form)  {
      $("#add_entry_form").html(table_form_input).slideDown();
      setSubmissionBoxEvents();
    }
    updateCounter();
  });
}
function setSubmissionBoxEvents() {
  $(".entry_close_button").click(function () {
    if (confirm("Are you sure you wish to cancel?")) {
      if (entries > 0) {
        $("#button_box").show();
      }
      else {
        $("#discussion_board").hide("slow");
      }
      $("#submit_entry_button").show();
      $("#add_entry_form").slideUp().html("");
      $("#preview_entry_div").slideUp().html("");
    }
  });
  $("#entry_title").bind("focus", function () {
    $("#entry_title").css("background-color", "#FFFFFF").css("text-align", "left").css("cursor", "").val("").unbind("focus");
  });
  $("#entry_text").bind("focus", function () {
    $("#entry_text").css("background-color", "#FFFFFF").css("text-align", "left").css("cursor", "").val("").unbind("focus");
  });
  $(".entry_preview_button").click(function () {
    var title = $("#entry_title").val();
    var text = $("#entry_text").val();
    if ($.trim(title) === "Title optional (max. of 50 chars)") {
      title = '';
    }
    if (text.lenght > 1200) {
      text = text.subString(0, 1200);
      $("#entry_text").val(text);
    }
    var preview = '<table align=center width="90%"><tr>';
    preview += '<td valign="top" style="background-color:#EFEFC2; border:1px solid #B8B78F" width="150" rowspan=2>' + user_information + '</td>';
    preview += '<td style="background-color:#EFEFC2; border:1px solid #B8B78F"><b>' + title + '</b><br><br>' + text.replace("/([^>])\n/g", "$1<br />\n") + '</td>';
    preview += '</tr></table>';
    $("#preview_entry_div").html(preview).slideDown();
  });
  $(".entry_submit_button").click(function () {
    var title = $("#entry_title").val();
    var text = $("#entry_text").val();
    var error = "";
    if ($.trim(title) === "Title optional (max. of 50 chars)") {
      title = '';
    }
    if ($.trim(text) === "" || $.trim(text) === "Entry text") {
      if (error !== "") {
        error += "\n";
      }
      error += "Please insert a text";
    }
    if (text.lenght > 1200) {
      text = text.subString(0, 1200);
      $("#entry_text").val(text);
    }
    if (error === "") {
      $("#preview_entry_div").html('<div align="center"><img src="/images/wikiwords/loading.gif"> Saving. Please wait...</div>').slideDown();
      $.ajax({
        type: "POST",
        url: "/ajax/ajax_kudoz.php",
        dataType: "json",
        data: {
          action: "addDiscussionEntry",
          eid_v: eid_v,
          text: text,
          title: title,
          helpterm_id: helpterm_id
        },
        success: function (code) {
          $("#preview_entry_div").slideUp().html("");
          if (code.data.status == "ok") {
            $("#button_box").show();
            $("#inner_center").html("");
            $("#add_entry_form").slideUp().html("");
            $("#bottom_buttons").show();
            $("#center_div").animate({opacity: 1}, 200, function () {$("#button_box").show();});
            sendDiscussionNotification(title, text);
            seconds = cons_time;
            if (update_timer) {
              clearInterval(update_timer);
            }
            updateCounter('no');
            if (code.data.update_notification) {
              $("#discussion_notify").attr("checked", "checked");
            }
          } else {
            switch (code.data.status) {
              case 'error': {
                alert("You must be logged in to make a discussion entry.");
                break;
              }
              case 'no_text': {
                alert("Please insert a text");
                break;
              }
              case 'too_long': {
                alert("Text too long. Maximum number of characters allowed: 1200 " + text.lenght);
                break;
              }
            }
          }
        }
      });
    } else {
      alert(error);
    }
  });
}
$(".add_entry_button").click(function () {
  if (entries != 0) {
    $("#button_box").hide();
  }
  if ($("#center_div").css("display") === "none") {
    viewAllButtons(true);
  } else {
    $("#add_entry_form").html(table_form_input).slideDown();
  }
  setSubmissionBoxEvents();
});
function entryRemove(id_val) {
  if (confirm("Are you sure you want to delete your post?")) {
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_kudoz.php",
      data: {
        action: "removeDiscussionEntry",
        note_id: id_val,
        eid_v: eid_v,
        helpterm_id: helpterm_id,
        remove_type: "user"
      },
      success: function (code) {
        eval(code);
        if (error === "n") {
          $("#entry_" + id_val).slideUp("normal", function () {
            $("#entry_" + id_val).remove();
            entries -= parseInt(1, 10);
            $("#total_entries").text(entries);
            var actual_height = $("#inner_center").innerHeight();
            if (actual_height < 300) {
              $("#center_div").animate({
                height: actual_height + "px"
              }, 500, function () {
                if ($("#center_div").innerHeight() < 300) {
                  $("#center_div").css("overflow", "");
                }
              });
            }
          });
        } else {
          alert("Error trying to delete this entry\nTry again later or contact support");
        }
      }
    });
  }
}
// make a popup window for enter a reason note to call a mod
function showCallToModeratorConfirmationBox(mod_entity_id, kudoz_id) {
  var content = '<script>$("div#jqi").css("width","400px");</script>'; // set box width
  content += '<div style="font-size:11px;" class="">';
  content += 'Use this to call the attention of a moderator if ';
  content += '<a href="/rules" target="_black">site rules</a> ';
  content += 'are being broken, or if you need help or guidance regarding this question.';
  content += '<br><br>';
  content += 'Please detail below the rules violation in this case, or your specific need.<br>';
  content += '<form method=post action="/?sp=mailsend&eid_s=' + mod_entity_id + '&prefab=1&kid=' + kudoz_id + '" ';
  content += ' name="call_mod_note_form" id="call_mod_note_form">';
  content += '<textarea id="call_to_mod_reason_note"  onkeydown="textCounter(this,500)" ';
  content += 'name="call_to_mod_reason_note" style="width:370px;height:75px;"></textarea>';
  content += '</form>';
  content += '</div>';
  $.prompt(content, {
    submit: function (v, m) {
      if (v === true) {
        var reason_note = $("#call_to_mod_reason_note").val();
        if (reason_note.length < 10) {
          alert('Details on rules violation are required');
          return false;
        } else {
          document.call_mod_note_form.submit();
        }
      } else {
        return true;
      }
    },
    buttons: {
      'Submit': true,
      'Cancel': false
    }
  });
}
function entryHide(id_val) {
  var custom_msg_form = 'Reason for making discussion entry invisible:<br>';
  custom_msg_form += '<input type="radio" name="reason" class="reason" value="offensive"> Offensive and/or personal rather than linguistic<br>';
  custom_msg_form += '<input type="radio" name="reason" class="reason" value="adult_content"> Adult nature and/or profane<br>';
  custom_msg_form += '<input type="radio" name="reason" class="reason" value="not_linguistic"> Discussion entries should be limited to linguistic points on the term posted<br>';
  custom_msg_form += '<input type="radio" name="reason" class="reason" value="other"> Other <input type="text" size="30" maxlength="100" id="other_reason"><br>';
  custom_msg_form += '<input type="hidden" id="note_id_hidden" value="' + id_val + '">';
  custom_msg_form += '<div>The poster of the entry will be notified of your site name, action and reason.</div>';
  $.prompt(custom_msg_form, {
    submit: function (v, m) {
      if (v === true) {
        var id_val = m.children("#note_id_hidden").val();
        var reason = '';
        var reason_id = m.children(".reason:checked").val();
        if (reason_id === '' || reason_id === undefined) {
          alert('Please select a reason');
          return false;
        } else {
          if (reason_id === 'other') {
            reason = m.children("#other_reason").val();
            if (reason === '' || reason === undefined) {
              alert('Please insert your reason');
              return false;
            }
          }
        }
      }
      return true;
    },
    callback: function (v, m) {
      if (v === true) {
        var reason_id = m.children(".reason:checked").val();
        var reason = m.children("#other_reason").val();
        var id_val = m.children("#note_id_hidden").val();
        $.ajax({
          type: "POST",
          url: "/ajax/ajax_kudoz.php",
          data: {
            action: "removeDiscussionEntry",
            note_id: id_val,
            eid_v: eid_v,
            helpterm_id: helpterm_id,
            reason: reason,
            reason_id: reason_id
          },
          success: function (code) {
            eval(code);
            if (error === "n") {
              $("#remove_" + id_val).removeAttr("title");
              $("#remove_" + id_val).attr("title", 'Click here to make visible this post');
              $("#remove_" + id_val).removeAttr("onclick");
              $("#remove_" + id_val).unbind("click");
              $("#remove_" + id_val).click(function () {
                entryUnhide(id_val);
              });
              var reason_text = [];
              reason_text.adult_content = 'Adult nature and/or profane';
              reason_text.offensive = 'Offensive and/or personal rather than linguistic';
              reason_text.not_linguistic = 'Discussion entries should limit themselves to linguistic points on the term posted';
              reason_text.other = reason;
              $('<div id="removed_by_' + id_val + '" align="right">' + removed_by + '<br>Reason: ' + reason_text[reason_id] + '</div>').insertAfter("#entry_text_" + id_val);
              $('.background_text_' + id_val).attr('style', 'background-color:#8F8F74; border:1px solid #B8B78F');
              var actual_height = $("#inner_center").innerHeight();
              if (actual_height < 300) {
                $("#center_div").animate({
                  height: actual_height + "px"
                }, 500, function () {
                  if ($("#center_div").innerHeight() < 300) {
                    $("#center_div").css("overflow", "");
                  }
                });
              } else {
                $("#center_div").css("overflow", "auto");
              }
            } else {
              alert("Error trying to hide this entry\nTry again later or contact support");
            }
          }
        });
      }
    },
    buttons: {
      'Hide': true,
      'Cancel': false
    }
  });
}
function entryUnhide(id_val) {
  if (confirm("Are you sure you want to make visible this post?")) {
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_kudoz.php",
      data: {
        action: "restoreDiscussionEntry",
        note_id: id_val,
        eid_v: eid_v,
        helpterm_id: helpterm_id
      },
      success: function (code) {
        eval(code);
        if (error === "n") {
          $("#remove_" + id_val).removeAttr("title");
          $("#remove_" + id_val).attr("title", 'Click here to hide this post');
          $("#remove_" + id_val).removeAttr("onclick");
          $("#remove_" + id_val).unbind("click");
          $("#remove_" + id_val).click(function () {
            entryHide(id_val);
          });
          $("#removed_by_" + id_val).remove();
          $(".background_text_" + id_val).attr("style", "background-color:#EFEFC2; border:1px solid #B8B78F;");
          var actual_height = $("#inner_center").innerHeight();
          if (actual_height < 300) {
            $("#center_div").animate({
              height: actual_height + "px"
            }, 500, function () {
              if ($("#center_div").innerHeight() < 300) {
                $("#center_div").css("overflow", "");
              }
            });
          }
        } else {
          alert("Error trying to make visible this entry\nTry again later or contact support");
        }
      }
    });
  }
}
$(".view_all_button").click(function () {
  viewAllButtons(false);
});
$(".close_discussion_button").click(function () {
  if (entries == 0) {
    $("#discussion_board").hide("slow");
  }
  else {
    $("#center_div").animate({
      height: "1px",
      opacity: "0"
    }, "1000", function () {
      $("#center_div").hide();
      $("#center_div").css("height","");
      $(".view_all_button").show();
      if (update_timer) {
        clearInterval(update_timer);
      }
      $("#update_counter_div").fadeOut("slow");
      $("#discussion_options_div").hide("slow");
      $(".close_discussion_button").hide();
      $("#add_entry_form").hide();
      seconds = 0
    });
  }
});
$("#discussion_display").click(function () {
  var display = "hidden";
  if ($(this).attr("checked")) {
    display = "visible";
  }
  $.ajax({
    type: "POST",
    url: "/ajax/ajax_kudoz.php",
    data: "action=changeDiscussionDisplay&eid_v=" + eid_v + "&display=" + display
  });
  $(".close_discussion_button").show();
  $(".view_all_button").hide();
});
$("#discussion_notify").click(function () {
  var notify = "n";
  if ($(this).attr("checked")) {
    notify = "y";
  }
  $.ajax({
    type: "POST",
    url: "/ajax/ajax_kudoz.php",
    data: "action=changeDiscussionNotification&eid_v=" + eid_v + "&helpterm_id=" + helpterm_id + "&notify=" + notify
  });
});
$("#discussion_order_desc").click(function () {
  $.ajax({
    type: "POST",
    url: "/ajax/ajax_kudoz.php",
    data: "action=discussion_order&eid_v=" + eid_v + "&helpterm_id=" + helpterm_id + "&discussion_order=desc",
    success: function () {
      updateEntries();
    }
  });
});
$("#discussion_order_asc").click(function () {
  $.ajax({
    type: "POST",
    url: "/ajax/ajax_kudoz.php",
    data: "action=discussion_order&eid_v=" + eid_v + "&helpterm_id=" + helpterm_id + "&discussion_order=asc",
    success: function () {
      updateEntries();
    }
  });
});
function viewDiscuss() {
  $("#submit_entry_button").hide();
  $("#discussion_board").slideDown();
  document.location.href = "#discussion_board";
  if (entries === 0) {
    $(".add_entry_button").click();
  } else {
    $(".view_all_button").click();
  }
}
function entryEdit(id_val) {
  if (id_val > 0) {
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_kudoz.php",
      data: {
        action: "getDiscussionEntry",
        eid_v: eid_v,
        note_id: id_val
      },
      success: function (code) {
        eval(code);
        text = text.replace(/<br>/g, "\n");
        var table = '<form><table align=center width=300 class=standard><tr><th>Post a discussion entry</th></tr>';
        table += '<tr valign=top><td align=center><input type=text id=entry_title value="' + title + '" maxlength=50 size=73></td></tr>';
        table += '<tr valign=top><td align=center><textarea cols=70 rows=3 id=entry_text onkeyUp="textCounter(this.form.entry_text,document.getElementById(\'entry_text_max_size\'),1200);">' + text + '</textarea></td></tr>';
        table += '<tr valign=top><td align=center><input type="text" readonly size=5 name="entry_text_max_size" value="' + (1200 - (text.length)) + '" style="text-align:right;" id="entry_text_max_size"> / 1200 chars</td></tr>';
        table += '<tr valign=top><td colspan=2 align=center><input type=button value=Preview class="entry_preview_button form_btn_flat">&nbsp;&nbsp;';
        table += '<input type=button value="Submit" class="entry_submit_button form_btn_flat">&nbsp;&nbsp;';
        table += '<input type=button value="Cancel" class="entry_close_button form_btn_flat"></td></tr>';
        table += "</table></form><br>";
        $("#add_entry_form").html(table).slideDown();
        $(".entry_close_button").click(function () {
          if (confirm("Are you sure you wish to cancel?")) {
            $("#add_entry_form").slideUp().html("");
            $("#preview_entry_div").slideUp().html("");
            $("#bottom_buttons").show("slow");
          }
        });
        $(".entry_preview_button").click(function () {
          var title = $("#entry_title").val();
          var text = $("#entry_text").val();
          text = text.replace(/\n/g, "<br>");
          var preview = '<table align=center width="90%"><tr><td valign="top" style="background-color:#EFEFC2; border:1px solid #B8B78F" width="150" rowspan=2>' + user_information + '</td><td style="background-color:#EFEFC2; border:1px solid #B8B78F"><b>' + title + '</b><br><br>' + text + '</td></tr></table>';
          $("#preview_entry_div").html(preview).slideDown();
        });
        $(".entry_submit_button").click(function () {
          var title = $("#entry_title").val();
          var text = $("#entry_text").val();
          var error = "";
          if ($.trim(text) === "") {
            if (error !== "") {
              error += "\n";
            }
            error += "Please insert a text";
          }
          if (text.lenght > 1200) {
            text = text.subString(0, 1200);
            $("#entry_text").val(text);
          }
          if (error === "") {
            $("#preview_entry_div").html('<div align="center"><img src="/images/wikiwords/loading.gif"> Saving. Please wait...</div>').slideDown();
            $.ajax({
              type: "POST",
              url: "/ajax/ajax_kudoz.php",
              dataType: "json",
              data: {
                action: "editDiscussionEntry",
                eid_v: eid_v,
                text: text,
                title: title,
                note_id: id_val
              },
              success: function (code) {
                if (code.data.status === "ok") {
                  $("#entry_title_" + id_val).html(title);
                  $("#entry_text_" + id_val).html(text.replace(/\n/g, '<br>\n'));
                  if (update_timer) {
                    clearInterval(update_timer);
                  }
                  seconds = cons_time;
                  updateCounter();
                  $("#add_entry_form").slideUp().html("");
                  $("#preview_entry_div").slideUp().html("");
                  $("#bottom_buttons").show("slow");
                } else {
                  switch (code.data.status) {
                    case 'error': {
                      alert("Error trying to edit this entry\nTry again later or contact support");
                      break;
                    }
                    case 'no_text': {
                      alert("Please insert a text");
                      break;
                    }
                    case 'too_long': {
                      alert("Text too long. Maximum number of characters allowed: 1200");
                      break;
                    }
                  }
                }
              }
            });
          } else {
            alert(error);
          }
        });
      }
    });
  }
}
function entryPeerCommentEdit(vote_id, is_glossary_type) {
  var comment_max_length = 255;
  if (vote_id > 0) {
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_kudoz.php",
      data: {
        action: "getPeerCommmentEntry",
        vote_id: vote_id
      },
      success: function (code) {
        eval(code);
        comment = comment.replace(/<br>/g, "\n");
        $(".peer_comment_post_send").attr('disabled', 'disabled');
        var table = '<br><form><table align="center" width="300" class="standard" style="border: 0px; background-color: white;">';
        table += '<tr><th colspan="2"><font size="' + font_size_kudoz + '">Edit your peer comment</font></th></tr>';
        table += '<tr valign=top><td>';
        var str_agree = 'agree';
        var str_agreement = 'disagree';
        if (is_glossary_type === true) {
          str_agree = 'Yes';
          str_agreement = 'No';
        }
        table += '<select name="agreement" id="peer_comments_entry_agreement">';
        table += '<option value="agree" ' + ((agreement === 'agree') ? 'selected' : '') + ' >' + str_agree;
        table += '<option value="disagree" ' + ((agreement === 'disagree') ? 'selected' : '') + ' >' + str_agreement;
        if (is_glossary_type !== true) {
          table += '<option value="neutral" ' + ((agreement === 'neutral') ? 'selected' : '') + ' >neutral';
        }
        table += '</select></td>';
        table += '<td align=center><textarea cols=70 rows=2 id="entry_comment" onkeyUp="textCounter(this.form.entry_comment,document.getElementById(\'peer_comment_text_max_size\'), ' + comment_max_length + ');">' + comment + '</textarea></td></tr>';
        table += '<tr valign=top><td align="center" colspan="2"><input type="text" readonly size=5 name="peer_comment_text_max_size" value="' + (comment_max_length - (comment.length)) + '" style="text-align:right;" id="peer_comment_text_max_size"> / ' + comment_max_length + ' chars</td></tr>';
        table += '<tr valign=top><td align="center" colspan="2"><input type=button value="Submit" class="edit_peer_comments_submit_button form_btn_flat">&nbsp;&nbsp;<input type=button value="Cancel" class="entry_close_button form_btn_flat">';
        table += '<span style="display:none;" id="edit_peer_comments_preview_entry"></span></td></tr>';
        table += '</table></form><br>';
        table += '<center><font size="1">The answerer will be notified of your change.</font></center>';
        $("#edit_peer_comments_form_" + vote_id).html(table).slideDown();
        $("#edit_peer_comments_buttons").hide();
        $(".entry_close_button").click(function () {
          if (confirm("Are you sure you wish to cancel?")) {
            $("#edit_peer_comments_form_" + vote_id).slideUp().html("");
            $(".peer_comment_post_send").removeAttr('disabled');
          }
        });
        $(".edit_peer_comments_submit_button").click(function () {
          var comment = $("#entry_comment").val();
          var error = "";
          var agreement_text = $("#peer_comments_entry_agreement").val();
          if ($.trim(comment) === "" && agreement_text !== "agree") {
            error += "Please insert a peer comment";
          }
          if (comment.lenght > comment_max_length) {
            comment = comment.subString(0, comment_max_length);
            $("#entry_comment").val(comment);
          }
          if (error === "") {
            var agreement = $('#peer_comments_entry_agreement :selected').val();
            $("#edit_peer_comments_preview_entry").html('<span align="center"><img src="/images/wikiwords/loading.gif"> Saving. Please wait...</span>').slideDown();
            $.ajax({
              type: "POST",
              url: "/ajax/ajax_kudoz.php",
              data: {
                action: "updatePeerCommentEntry",
                agreement: agreement,
                comment: comment,
                vote_id: vote_id
              },
              success: function (html) {
                var text_agree = "";
                if (agreement === 'agree') {
                  text_agree += '<font color="blue" size="' + font_size_kudoz + '">';
                  if (is_glossary_type !== true) {
                    text_agree += '<b><span id="peer_comment_agreement_' + vote_id + '">' + msg_agree + '</span></b></font>&nbsp;';
                  } else {
                    text_agree += '<b><span id="peer_comment_agreement_' + vote_id + '">Yes</span></b></font>&nbsp;';
                  }
                } else if (agreement === 'disagree') {
                  text_agree += '<font color="red" size="' +  font_size_kudoz + '">';
                  if (is_glossary_type !== true) {
                    text_agree += '<b><span id="peer_comment_agreement_' + vote_id + '">' + msg_disagree + '</span></b></font>&nbsp;';
                  } else {
                    text_agree += '<b><span id="peer_comment_agreement_' + vote_id + '">No</span></b></font>&nbsp;';
                  }
                } else {
                  text_agree += '<font color="gray" size="' +  font_size_kudoz + '">';
                  text_agree += '<b><span id="peer_comment_agreement_' + vote_id + '">' + msg_neutral + '</span></b></font>&nbsp;';
                }
                $("#peer_comment_agreement_" + vote_id).html(text_agree);
                $("#peer_comment_" + vote_id).html(comment);
                $("#edit_peer_comments_form_" + vote_id).slideUp().html("");
                $("#edit_peer_comments_preview_entry").slideUp().html("");
                $(".peer_comment_post_send").removeAttr('disabled');
              }
            });
          } else {
            alert(error);
            $(".peer_comment_post_send").removeAttr('disabled');
          }
        });
      }
    });
  }
}
function entryPeerCommentEditReply(vote_id) {
  var comment_max_length = 255;
  if (vote_id > 0) {
    $.ajax({
      type: "POST",
      url: "/ajax/ajax_kudoz.php",
      data: {
        action: "getPeerCommmentEntryReply",
        vote_id: vote_id
      },
      success: function (code) {
        eval(code);
        comment = comment.replace(/<br>/g, "\n");
        $(".peer_comment_post_send").attr('disabled', 'disabled');
        var table = '<br><form><table align="center" width="300" class="standard" style="border: 0px; background-color: white;">';
        table += '<tr><th colspan="2"><font size="' + font_size_kudoz + '">Edit your reply</font></th></tr>';
        table += '<tr valign=top>';
        table += '<td align=center><textarea cols=70 rows=2 id="entry_comment" onkeyUp="textCounter(this.form.entry_comment,document.getElementById(\'peer_comment_text_max_size\'), ' + comment_max_length + ');">' + comment + '</textarea></td></tr>';
        table += '<tr valign=top><td align="center" colspan="2"><input type="text" readonly size=5 name="peer_comment_text_max_size" value="' + (comment_max_length - (comment.length)) + '" style="text-align:right;" id="peer_comment_text_max_size"> / ' + comment_max_length + ' chars</td></tr>';
        table += '<tr valign=top><td align="center" colspan="2"><input type=button value="Submit" class="edit_peer_comments_submit_button form_btn_flat">&nbsp;&nbsp;';
        table += '<input type=button value="Cancel" class="entry_close_button form_btn_flat">';
        table += '<span style="display:none;" id="edit_peer_comments_preview_entry"></span></td></tr>';
        table += '</table></form><br>';
        table += '<center><font size="1">The peer will be notified of the change.</font></center>';
        $("#edit_peer_comments_form_reply_" + vote_id).html(table).slideDown();
        $("#edit_peer_comments_buttons").hide();
        $(".entry_close_button").click(function () {
          if (confirm("Are you sure you wish to cancel?")) {
            $("#edit_peer_comments_form_reply_" + vote_id).slideUp().html("");
            $(".peer_comment_post_send").removeAttr('disabled');
          }
        });
        $(".edit_peer_comments_submit_button").click(function () {
          var comment = $("#entry_comment").val();
          var error = "";
          var agreement_text = $("#peer_comments_entry_agreement").val();
          if ($.trim(comment) === "" && agreement_text !== "agree") {
            error += "Please insert a peer comment";
          }
          if (comment.lenght > comment_max_length) {
            comment = comment.subString(0, comment_max_length);
            $("#entry_comment").val(comment);
          }
          if (error === "") {
            $("#edit_peer_comments_preview_entry").html('<span align="center"><img src="/images/wikiwords/loading.gif"> Saving. Please wait...</span>').slideDown();
            $.ajax({
              type: "POST",
              url: "/ajax/ajax_kudoz.php",
              data: {
                action: "updatePeerCommentReply",
                comment: comment,
                vote_id: vote_id
              },
              success: function (html) {
                var text_agree = "";
                $("#peer_comment_agreement_reply_" + vote_id).html(text_agree);
                $("#peer_comment_reply_" + vote_id).html("&nbsp;&nbsp;-&gt;&nbsp;" + comment);
                $("#edit_peer_comments_form_reply_" + vote_id).slideUp().html("");
                $("#edit_peer_comments_preview_entry").slideUp().html("");
                $(".peer_comment_post_send").removeAttr('disabled');
              }
            });
          } else {
            alert(error);
            $(".peer_comment_post_send").removeAttr('disabled');
          }
        });
      }
    });
  }
}
function selectAnswer(helpterm_id, helpterm_reply_id, entity_id) {
  $("#select_this_answer_" + helpterm_reply_id).hide();
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: '/ajax/ajax_kudoz.php',
    async: false,
    data: {
      action: 'get_grading_form',
      helpterm_reply_id: helpterm_reply_id
    },
    success: function (json) {
      $("#asker_grade_answer_form_" + helpterm_reply_id).html(json.data.html_form).slideDown();
      $("#edit_peer_comments_buttons").hide();
      $(".entry_close_button").click(function () {
        if (confirm("Are you sure you wish to cancel?")) {
          $("#asker_grade_answer_form_" + helpterm_reply_id).slideUp().html("");
          $(".peer_comment_post_send").removeAttr('disabled');
          $("#select_this_answer_" + helpterm_reply_id).show();
        }
      });
    }
  });
}
function checkURL(link) {
  return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&\'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&\'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&\'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&\'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&\'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(link);
}
function kudozModNoteToogleEdition(kudoz_note_id, toogle_value) {
  if (toogle_value == 1) {
    $("#note_" + kudoz_note_id).hide();
    $("#edit_mod_note_" + kudoz_note_id).show();
    $("#mod_textarea_" + kudoz_note_id).val($("#note_" + kudoz_note_id).text());
  } else {
    $("#note_" + kudoz_note_id).show();
    $("#edit_mod_note_" + kudoz_note_id).hide();
  }
}
function updateKudozModNote(kudoz_note_id, helpterm_id, scope) {
  var comment = $("#mod_textarea_" + kudoz_note_id).val();
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: '/ajax/ajax_kudoz.php',
    data: {
      action: 'save_mod_note',
      kudoz_note_id: kudoz_note_id,
      helpterm_id : helpterm_id,
      scope : scope,
      comment : comment
    },
    success: function (json) {
      if (!json.is_success) {
        alert("Error saving note");
      } else {
        getModNotes(helpterm_id, scope);
      }
    }
  });
}
function textCounter(field, countfield, maxlimit) {
  if (field.value.length > maxlimit) {
    field.value = field.value.substring(0, maxlimit);
  } else {
    countfield.value = maxlimit - field.value.length;
  }
}