
// =============
// Edit SIC Code
// =============

$(document).ready(function () {

     var $application = $("#APPLICATION_MNEMONIC").val(), $sessionStorage = JSON.parse(sessionStorage.getItem($application) || "{}");

    // -----------
    // Save Button
    // -----------

    $(".btnSave").on("click", function (e) {
        e.preventDefault();
        $("#editSICCode").submit();
    });

    // --------------
    // Cancel Button.
    // --------------

    $(".btnCancel").on("click", function () {

        $sessionStorage.action = $sessionStorage.editSICCode || "";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);

    });

    // -------------
    // Delete Button
    // -------------

    $(".btnDelete").on("click", function () {

        if (formPost({action: "SICCodes.siccodeActive", siccode_serial: $sessionStorage.siccode_serial}) === true) {

            $("#continue-dialog").find(".modal-title").html("Cannot Delete SIC Code").end()
                    .find(".modal-body").html("This SIC Code is in use and cannot be deleted.").end()
                    .modal("show");

        } else {

            $("#confirm-dialog").removeClass().addClass("modal confirm-delete-siccode")
                    .find(".modal-title").html("Confirm Delete SIC Code").end()
                    .find(".modal-body").html("Are you sure you wish to delete this SIC Code?").end()
                    .modal("show");

        }

    });

    $("body").on("click", ".confirm-delete-siccode .btnConfirmDialogConfirm", function () {

        $.post("./", {action: "SICCodes.deleteSICCode", siccode_serial: $sessionStorage.siccode_serial})
                .done(function () {
                    formSubmit({action: $sessionStorage.deleteSICCode});
                });

    });

    // ---------------
    // Validate Inputs
    // ---------------

    $("#editSICCode").submit(function (e) {

        var siccode_serial = $("#siccode_serial"),
                siccode_description = $("#siccode_description"),
                siccode_code = $("#siccode_code");

        clearInputErrors();

        siccode_description.val(trimString(siccode_description.val()));
        siccode_code.val(trimString(siccode_code.val()));

        if (formPost({action: "SICCodes.siccodeExists", siccode_serial: siccode_serial.val(), siccode_description: siccode_description.val()}) === true) {
            createInputError(siccode_description, "Name already exists");
            return false;
        }

        if (isBlank(siccode_description)) {
            createInputError(siccode_description, "Name is required");
            return false;
        }

        e.preventDefault();

        $.post("./", $(this).serialize())
                .done(function () {
                    formSubmit({action: $sessionStorage.editSICCode});
                });

    });

});