
// ==============
// Add Attachment
// ==============

$(document).ready(function () {

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

    $("input[name = 'uploadCSVFile_object']", "#uploadCSVFile").val($sessionStorage.uploadCSVFile_object);
    $("input[name = 'uploadCSVFile_serial']", "#uploadCSVFile").val($sessionStorage.uploadCSVFile_serial);

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

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

        $sessionStorage.action = "";

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

        formSubmit($sessionStorage);

    });

    // ----------------------------
    // Process Attachmet File Input
    // ----------------------------

    // Disable standard Drag/Drop processing.

    $("html").on("dragenter dragover dragleave", function (e) {

        e.preventDefault();
        e.stopPropagation();

    });

    // Allow Drop only on the file input

    $("html").on("drop", function (e) {

        if (e.target.type === "file") {
            return;
        }

        e.preventDefault();
        e.stopPropagation();

    });

    // Process a Selection or Drop.

    $(".file-input").on("change", function (e) {

        if (e.target.files.length === 0) {
            return false;
        }

        var documentName = $(this).val().split("\\").pop(),
                extension = documentName.substr((documentName.lastIndexOf(".") + 1), documentName.length).toLowerCase();

        if (extension !== "csv") {
            return false;
        }

        $(".btnUpload").attr("disabled", false);

    });

    // -------------
    // Upload Button
    // -------------

    $(".btnUpload").on("click", function (e) {

        $("#spinner-dialog").modal("show");

        e.preventDefault();

        var uploadCSVFile_form = new FormData($("#uploadCSVFile")[0]);

        $.ajax({
            url: "./",
            method: "POST",
            data: uploadCSVFile_form,
            async: true,
            processData: false,
            contentType: false

        })
                .done(function () {

                    $sessionStorage.action = "";
                    $sessionStorage.toast = ($("#upload_type").val() === "full") ? "CSV Import Queued" : "Permit Records Imported";

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

                    formSubmit($sessionStorage);

                });

    });

});
