/*
    Created: 2025-12-10
    Author: Kārlis Grīnvalds
    Last edited: 2026-06-04
    Edited by: Kārlis Grīnvalds
*/

// Used for entry.html

// Executes all the needed code
async function Load() {
    $("#CancelChanges").on("click", function() {
        RedirectBack("/" + Topic() + "/Page:Entries");
    });
    $("#SaveChanges").on("click", async function() {
        // Checks if the fields have been filled
        if ($("#EntryTitle").val().trim().length > 0 && $("#SaveChanges").attr("value") != "disabled") {
            $("#SaveChanges").attr("value", "disabled");
            // Hides the error text
            $("#ErrorText").hide();
            $("#ErrorText").text("");
            // Prepares POST data
            let data = {
                topic: Topic(),
                name: $("#EntryTitle").val().replaceAll(" ", "_"),
                title: $("#EntryTitle").val(),
                content: $("#EntryContent").val(),
            };
            if (activeLock > 0) {
                return;
            }
            LockUI();
            // Creates the entry and returns the results
            await $.ajax({
                url: "/entry/0",
                method: "POST",
                data: data,
                success: function(response) {
                    activeLock++;
                    // Entry has been created!
                    UnlockUI();
                    AlertWindow("success", "Entry has been created!", "/" + Topic() + "/" + response.redirect, true);
                },
                error: function(response) {
                    UnlockUI();
                    // Outputs the error message
                    $("#ErrorText").show();
                    $("#ErrorText").text(response.responseJSON.messages.error);
                }
            }); 
        }
        else {
            // Outputs the error message
            $("#ErrorText").show();
            if ($("#SaveChanges").attr("value") == "disabled") {
                $("#ErrorText").text("Loading!");
            }
            else {
                $("#ErrorText").text("Entry needs a title!");
            }
        }
        $("#SaveChanges").attr("value", "");
    });
}