$(document).ready(function () {
	$("#upload_receipt").click(function (event) {
		event.preventDefault();

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

		$("#upload_receipt").attr("disabled", "");

		var validImageTypes = [
			"image/gif",
			"image/jpeg",
			"image/jpg",
			"image/png",
		];
		let request_data = new FormData();

		var receipt_file = $("#receipt_file")[0].files[0];

		$(".receipt_feedback").hide();
		if (receipt_file.length === 0) {
			$(".receipt_feedback").html(
				"Please upload your transaction receipt."
			);
			$(".receipt_feedback").show();
			$("input#receipt_file").focus();

			$(".confirm_and_submit").removeClass("disabled");
			return false;
		} else {
			var fileType = receipt_file["type"];

			if ($.inArray(fileType, validImageTypes) < 0) {
				upload_spinner.hide();
				upload_btn.attr("disabled", false);
				alert("Invalid file format.");
			} else {
				request_data.append("receipt_file", receipt_file);
			}
		}

		$.ajax({
			url: "../helpers/upload_charges_invoice_receipt",
			type: "POST",
			data: request_data,
			processData: false,
			contentType: false,
		}).done(function (response) {
			$("#upload_receipt").removeAttr("disabled");
			$(".button_spinner").hide();
			$("input#receipt_file").prop("disabled", false);

			$("#errorPrompt").show();

			if (response == "success") {
				$("#errorPrompt").html(
					'<div class="alert alert-success" role="alert">Payment receipt uploaded.</div>'
				);
			} else {
				$("#errorPrompt").html(
					'<div class="alert alert-danger" role="alert">' +
						response +
						"</div>"
				);
			}

			$("html, body").animate(
				{
					scrollTop: $("#top_area").offset().top,
				},
				500
			);
		});

		return false;
	});
});
