
// ==========
// Edit Alert
// ==========

$(document).ready(function () {

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

    // ----------------------
    // Initialize the Editor.
    // ----------------------

    ClassicEditor
            .create(document.querySelector('#alert_message'), {
                toolbar: {
                    items: [
                        'heading',
                        '|',
                        'bold',
                        'italic',
                        'underline',
                        'link',
                        'bulletedList',
                        'numberedList',
                        '|',
                        'fontColor',
                        'fontSize',
                        'fontFamily',
                        '|',
                        'indent',
                        'outdent',
                        'alignment',
                        '|',
                        'horizontalLine',
                        'insertTable',
                        '|',
                        'undo',
                        'redo',
                        '|'
                    ]},
                link: {
                    addTargetToExternalLinks: true,
                    defaultProtocol: "http://"

                }
            })
            .then(editor => {
                $CKEditor = editor;
            })
            .catch(error => {
                console.error('CK-Editor error...');
                console.error(error);
            });


    // ------------
    // Date Pickers
    // ------------

    $("#alert_starts_date").datepicker({format: "yyyy-mm-dd",
        container: "div.starts-date",
        keyboardNavigation: false,
        autoclose: true,
        orientation: "bottom",
        todayBtn: "linked",
        todayHighlight: true});

    $("#alert_expires_date").datepicker({format: "yyyy-mm-dd",
        container: "div.expires-date",
        keyboardNavigation: false,
        autoclose: true,
        orientation: "bottom",
        todayBtn: "linked",
        todayHighlight: true});

    $("#alert_starts_time").inputmask({alias: "datetime",
        placeholder: "HH:MM",
        inputFormat: "HH:MM",
        insertMode: false,
        showMaskOnHover: false,
        hourFormat: 24
    });

    $("#alert_expires_time").inputmask({alias: "datetime",
        placeholder: "HH:MM",
        inputFormat: "HH:MM",
        insertMode: false,
        showMaskOnHover: false,
        hourFormat: 24
    });

    // ---------------------
    // Show Calendar Buttons
    // ---------------------

    $(".btnAlertStartDateCalendar").on("click", function (e) {
        e.preventDefault();
        $("#alert_starts_date").focus().datepicker("show");
    });

    $(".btnAlertExpiresDateCalendar").on("click", function (e) {
        e.preventDefault();
        $("#alert_expires_date").focus().datepicker("show");
    });


    $("#alert_starts_date").on("blur", function () {
        $("#alert_starts_time").focus();
    });

    $("#alert_expires_date").on("blur", function () {
        $("#alert_expires_time").focus();
    });

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

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

        e.preventDefault();

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

    });

    console.log($sessionStorage);

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

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

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

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

        formSubmit($sessionStorage);

    });

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

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

        var alert_title = $("#alert_title"),
                alert_starts_date = $("#alert_starts_date"),
                alert_starts_time = $("#alert_starts_time"),
                alert_expires_date = $("#alert_expires_date"),
                alert_expires_time = $("#alert_expires_time"),
                alert_message = $("#alert_message");

        clearInputErrors();

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

        if (isBlank(alert_title)) {
            createInputError(alert_title, "Title is required");
            return false;
        }


        if ((!isBlank(alert_starts_date)) && (!isDate(alert_starts_date))) {
            createInputError(alert_starts_date, "Date is invalid");
            return false;
        }

        if (isBlank(alert_starts_time)) {
            createInputError(alert_starts_time, "Please enter a Time");
            return false;
        }

        if (!alert_starts_time.inputmask("isComplete")) {
            createInputError(alert_starts_time, "Please enter a Time");
            return false;
        }

        if (isBlank(alert_expires_date)) {
            createInputError(alert_expires_date, "Please enter a Date");
            return false;
        }

        if ((!isBlank(alert_expires_date)) && (!isDate(alert_expires_date))) {
            createInputError(alert_expires_date, "Date is invalid");
            return false;
        }

        if (isBlank(alert_expires_time)) {
            createInputError(alert_expires_time, "Please enter a Time");
            return false;
        }

        if (!alert_expires_time.inputmask("isComplete")) {
            createInputError(alert_expires_time, "Please enter a Time");
            return false;
        }

//        if (isBlank(alert_message)) {
//            createInputError(alert_message, "Please enter a Message");
//            return false;
//        }

        if (!checkDateTime(alert_starts_date, alert_starts_time, alert_expires_date, alert_expires_time)) {
            createInputError(alert_expires_time, "Cannot be prior to Start");
            return false;
        }

        e.preventDefault();

        $CKEditor.updateSourceElement();

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

                .done(function () {

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

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

                    formSubmit($sessionStorage);

                });

    });

});

// -----------------------------------------------------
// Expires date/time cannot be prior to Start date/time.
// -----------------------------------------------------

function checkDateTime(alert_starts_date, alert_starts_time, alert_expires_date, alert_expires_time) {

    var starts_date_parts = alert_starts_date.val().split("-"),
            starts_time_parts = alert_starts_time.val().split(":"),
            expires_date_parts = alert_expires_date.val().split("-"),
            expires_time_parts = alert_expires_time.val().split(":"),
            starts_date,
            expires_date;

    starts_date = new Date(starts_date_parts[0], parseInt(starts_date_parts[1], 10) - 1, starts_date_parts[2]);
    expires_date = new Date(expires_date_parts[0], parseInt(expires_date_parts[1], 10) - 1, expires_date_parts[2]);

    starts_date.setHours(starts_time_parts[0], starts_time_parts[1], 0, 0);
    expires_date.setHours(expires_time_parts[0], expires_time_parts[1], 0, 0);

    if (expires_date.getTime() < starts_date.getTime()) {
        return false;
    } else {
        return true;
    }

}