
// ==========
// Add Report
// ==========

$(document).ready(function () {

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

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

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

        e.preventDefault();

        $("#addReport").submit();

    });

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

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

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

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

        formSubmit($sessionStorage);

    });

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

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

        var report_name = $("#report_name"),
                report_class = $("#report_class"),
                report_type = $("#report_type"),
                report_description = $("#report_description");

        clearInputErrors();

        report_name.val(report_name.val().replace(/\s+/g, " ").trim());

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

        if (isBlank(report_class)) {
            createInputError(report_class, "Class is required");
            return false;
        }

        if (formPost({action: "Reports.reportExists", report_serial: 0, report_class: report_class.val()}) === true) {
            createInputError(report_class, "Class already exists");
            return false;
        }

        if (isBlank(report_description)) {
            createInputError(report_description, "Description is required");
            return false;
        }

        e.preventDefault();

        $.post("./", $(this).serialize())

                .done(function () {

                    $sessionStorage.action = $sessionStorage.addReport || "";
                    $sessionStorage.toast = "Report was Added";

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

                    formSubmit($sessionStorage);

                });

    });

});