$(function() {
  /* rename */
  $("#exam-details-h1-name, .exam-details-rename-button").click(function() {
    $("#exam-details-h1-name span").hide();
    $("#exam-details-rename-form").show().css('display', 'inline-block');
    $("#exam-details-rename-name").select();
  });

  /* rename ajax */
  $('#exam-details-rename-submit').click(function() {
    if(!$("#exam-details-rename-name")[0].checkValidity()) {
      return true;
    }
    var name = $('#exam-details-rename-name').val();

    $.ajax({
      method: 'POST',
      url: location.href,
      data: {'new_name': name},
      headers: {"X-CSRFToken": getCookie('csrftoken')},
      success: function(data, textStatus, xhr) {
        $("#exam-details-h1-name span").text(data.new_name).show();
        $('#exam-details-rename-form').hide();
      },
      error: function(xhr, textStatus, error) {
        addMessage("Error during renaming.", "danger");
      }
    });
    return false;
  });

    /* update description click */
  $(".exam-details-home-edit-description-click").click(function(e) {
    $(".exam-details-home-edit-description-click").hide();
    $("#exam-details-home-description").show();
    var ta = $("#exam-details-home-description textarea");
    var tmp = ta.val();
    ta.val("");
    ta.focus();
    ta.val(tmp);
    e.preventDefault();
  });

    /* description update ajax */
  $('.exam-details-description-submit').click(function() {
    var description = $(this).prev("textarea").val();
    $.ajax({
      method: 'POST',
      url: location.href,
      data: {'new_description': description},
      headers: {"X-CSRFToken": getCookie('csrftoken')},
      success: function(data, textStatus, xhr) {
        var new_desc = data.new_description;
        /* we can't simply use $.text, because we need new lines */
        var tagsToReplace = {
          '&': "&amp;",
          '<': "&lt;",
          '>': "&gt;",
        };

        new_desc = new_desc.replace(/[&<>]/g, function(tag) {
          return tagsToReplace[tag] || tag;
        });

        $(".exam-details-home-edit-description")
          .html(new_desc.replace(/\n/g, "<br />"));
        $(".exam-details-home-edit-description-click").show();
        $("#exam-details-home-description").hide();
        // update the textareia
        $("exam-details-home-description textarea").text(data.new_description);
      },
      error: function(xhr, textStatus, error) {
        addMessage("Error during renaming!", "danger");
      }
    });
    return false;
  });
});
