$(function () {
	$("#change-password-btn").click(function (event) {
		event.preventDefault();

		$("#feedbackPrompt").hide();
		$("#feedbackPrompt").html("");

		$("#change-password-btn").attr("disabled", "");

		$(".current_password_feedback").hide();
		var currentPassword = $("input#currentPassword").val();
		if (currentPassword == "") {
			$(".current_password_feedback").html(
				"Current password is required."
			);
			$(".current_password_feedback").show();
			$("input#currentPassword").focus();

			$("#change-password-btn").removeAttr("disabled");
			return false;
		}

		$(".password_feedback").hide();
		var password = $("input#password").val();
		var password_confirm = $("input#passwordconfirm").val();
		if (password == "") {
			$(".password_feedback").html("Password cannot be empty.");
			$(".password_feedback").show();
			$("input#password").focus();

			$("#change-password-btn").removeAttr("disabled");
			return false;
		} else if (password !== password_confirm) {
			$(".password_feedback").html("Passwords do not match.");
			$(".password_feedback").show();
			$("input#password").focus();

			$("#change-password-btn").removeAttr("disabled");
			return false;
		} else if (password.length < 5) {
			$(".password_feedback").html(
				"Password length cannot be less than 5 characters."
			);
			$(".password_feedback").show();
			$("input#password").focus();

			$("#change-password-btn").removeAttr("disabled");
			return false;
		}

		$(".button_spinner").show();

		$("input#currentPassword").prop("disabled", true);
		$("input#password").prop("disabled", true);
		$("input#passwordconfirm").prop("disabled", true);

		var form_data =
			"current_password=" +
			encodeURIComponent(currentPassword) +
			"&new_password=" +
			encodeURIComponent(password);

		$.ajax({
			url: "../helpers/change-password",
			type: "POST",
			data: form_data,
		}).done(function (response) {
			if (response == "success") {
				$("#feedbackPrompt").html(
					'<div class="alert alert-success" role="alert"> Your password has been changed successfully.</div>'
				);
				$("input#currentPassword").val("");
				$("input#password").val("");
				$("input#passwordconfirm").val("");
			} else {
				$("#feedbackPrompt").html(
					'<div class="alert alert-danger" role="alert">' +
						response +
						"</div>"
				);
			}

			$("#feedbackPrompt").show();
			$("#change-password-btn").removeAttr("disabled");
			$(".button_spinner").hide();

			$("input#currentPassword").prop("disabled", false);
			$("input#password").prop("disabled", false);
			$("input#passwordconfirm").prop("disabled", false);
		});
		return false;
	});
});
