
// ==============
// Base Functions
// ==============

// --------------------------------
// Clear the Error State for Inputs
// --------------------------------

function clearInputErrors() {

    $(".is-invalid").removeClass("is-invalid");
    $(".invalid-feedback").remove();

}

// -----------------------------------
// Create an Error State for an Input.
// -----------------------------------

function createInputError(input, message = "", scroll = false) {

    if ($(input).hasClass("search-dropdown")) { // Select Picker

        $(input).closest(".bootstrap-select")
                .find("button").first()
                .addClass("is-invalid")
                .after("<div class='invalid-feedback fs-875'>" + message + "</div>")
                .focus();

    } else {

        $(input).focus().addClass("is-invalid");

        if ($(input).is(":last-child")) {
            $(input).after("<div class='invalid-feedback'>" + message + "</div>");
        } else {
            $(input).siblings(":last").after("<div class='invalid-feedback'>" + message + "</div>");
        }

    }

    if (scroll === true) {

        var element = document.getElementById(input.attr("id"));
        var header_offset = 130;
        var element_position = element.getBoundingClientRect().top;
        var offset_position = element_position + window.pageYOffset - header_offset;

        window.scrollTo({
            top: offset_position,
            behavior: "smooth"
        });

}

}

// ---------------------
// Test for Blank Value.
// ---------------------

function isBlank(object) {

    if ($.trim(object.val()).length == 0) {
        return true;
    } else {
        return false;
    }

}

// ------------------------
// Verify an Email Address.
// ------------------------

function isEmail(email) {

    var valid = false;
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,6})+$/;

    return regex.test(email.val());

}

// ------------------------
// Validate a URL (syntax).
// ------------------------

function isURL(object) {
    return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(object.val());
}

// ---------------------------------
// AJAX Call to Get Zip Code Detail.
// ---------------------------------

function getZipCodeDetail(zipcode) {

    var zipCodeDetail = null;

    $.ajax({
        url: "./",
        type: "POST",
        async: false,
        data: {action: "get_zipcode_detail",
            zip_code: zipcode},
        dataType: "json",
        success: function (info) {
            zipCodeDetail = info;
        }
    });

    return zipCodeDetail;

}

// -----------------------------
// AJAX Call to Validate a Date.
// -----------------------------

function isDate(date) {

    var valid = false;

    $.ajax({
        url: "./",
        type: "POST",
        async: false,
        data: {action: "validateDate",
            date: date.val()},
        dataType: "json",
        success: function (result) {
            valid = result;
        }
    });

    return valid;

}

// ---------------------------------------------
// Ending Date cannot be prior to Starting Date.
// ---------------------------------------------

function checkEndingDate(startingDate, endingDate) {

    var parts = startingDate.val().match(/(\d+)/g);
    var sDate = new Date(parts[0], parts[1] - 1, parts[2]);

    parts = endingDate.val().match(/(\d+)/g);
    var eDate = new Date(parts[0], parts[1] - 1, parts[2]);

    sDate.setHours(0, 0, 0, 0);
    eDate.setHours(0, 0, 0, 0);

    // The Ending Date cannot be prior to the Starting Date.

    if (eDate.getTime() < sDate.getTime()) {
        return false;
    } else {
        return true;
    }

}

// -------------------------------------------------------
// Convert a string to Title Case and remove extra spaces.
// -------------------------------------------------------

function titleCase(string) {

    string = string.replace(/([^\W_]+[^\s-]*) */g, function (s) {
        return s.charAt(0).toUpperCase() + s.slice(1);
    });
    string = string.replace(/\s+/g, " ").trim();

    return string;

}

// ------------------------------------------
// Trim a string and remove extra white space
// ------------------------------------------

function trimString(string) {

    return string.replace(/\s+/g, " ").trim();

}

// -------------------
// Post a Form (AJAX).
// -------------------

function formPost(inputs) {

    var response = "";

    $.ajax({
        url: "./",
        type: "POST",
        async: false,
        dataType: "json",
        data: inputs,
        success: function (results) {
            response = results;
        }, error: function (errorcode) {
            console.log(errorcode);
        }

    });

    return response;

}

// --------------
// Submit a Form.
// --------------

//function formSubmit(inputs, target) {
//
//    $('<form action="./" method="post" id="formSubmit"/>').appendTo("body");
//
//    var form = $("#formSubmit");
//
//    if (target === "_blank") {
//        form.prop("target", target);
//    }
//
//    for (var name in inputs) {
//        form.append('<input type="hidden" name="' + name + '" value="' + inputs[name] + '"/>');
//    }
//
//    console.log($('#formSubmit').html());
//
////    form.submit();
//
//}

// --------------
// Submit a Form.
// --------------

function formSubmit(inputs, target = "") {

    var form = $("#formSubmit");

    if (target === "_blank") {
        form.prop("target", target);
    } else {
        form.prop("target", "");
    }

    for (var name in inputs) {
        form.append('<input type="hidden" name="' + name + '" value="' + inputs[name] + '"/>');
    }

    form.submit();

}

$(document).ready(function () {

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

    // ----------------------------
    // Enable Tooltips and Popovers
    // ----------------------------

    $("[data-bs-toggle=tooltip]").tooltip({trigger: "hover", container: "body"});
    $("[data-bs-toggle=popover]").popover({trigger: "focus", container: "body"});

    // -------------
    // Display Toast
    // -------------

    const toast = $sessionStorage.toast || "";

    if (toast !== "") {

        $(".toast-body").html(toast);

        $("#toast-message").toast("show");

        $sessionStorage.toast = "";

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

    }

});
