/* Minification failed. Returning unminified contents.
(180,29-30): run-time error JS1195: Expected expression: .
(197,46-47): run-time error JS1195: Expected expression: .
(197,76-77): run-time error JS1195: Expected expression: .
(201,25-26): run-time error JS1195: Expected expression: .
(202,25-26): run-time error JS1195: Expected expression: .
(214,19-20): run-time error JS1195: Expected expression: .
(217,10-11): run-time error JS1195: Expected expression: )
(217,11-12): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ;
 */
function refreshEditor() {
    $(".refresh-editor").each(function () {
        var editor = $(this).data("kendoEditor");
        editor.refresh();
    });
}

function disableNavigationDialogue() {
    window.onbeforeunload = null;
    $(window).unbind();
}
function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2)
        month = '0' + month;
    if (day.length < 2)
        day = '0' + day;

    return [year, month, day].join('/');
}
function onImportSelect(e) {
    var file = e.files[0];
    var errors = file.validationErrors;
    if (errors) {
        var localization = e.sender.options.localization;
        for (var i = 0; i < errors.length; i++) {
            alert(localization[errors[i]]);
        }
    }
}

function getTime(seconds) {
    if (isNaN(seconds))
        seconds = 0;
    var leftover = seconds;
    var days = Math.floor(leftover / 86400);

    leftover = leftover - (days * 86400);

    var hours = Math.floor(leftover / 3600);

    leftover = leftover - (hours * 3600);

    var minutes = Math.floor(leftover / 60);

    leftover = leftover - (minutes * 60);
    return (hours + ':' + minutes + ':' + Math.floor(leftover).toLocaleString('en-US', {
        minimumIntegerDigits: 2,
        useGrouping: false
    }));
}

function onImportError(e) {
    alert("The Document Processing Library fails to convert the input file stream to html");
}

$(document).ajaxSuccess(function (event, xhr, settings) {
    var url = settings.url;
    if (url != undefined || url != null) {
        url = url.toLowerCase();
    }
    if ((url.indexOf("destroy") > -1) || (url.indexOf("create") > -1)) {
        $('.k-filebrowser>.k-listview>.k-loading-mask').remove();
        $('.k-imagebrowser>.k-listview>.k-loading-mask').remove();
    }
});
function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

function clearMultiSelectText() {
    $(".k-multiselect.k-state-focused .k-input").val("");
}

function onColumnMenuInit(e) {
    var columnsContainer = e.container[0].children[0].children[3].children[1];
    var colList = columnsContainer.outerHTML;

    //$('ul.k-group.k-menu-group > li.k-first').removeClass('k-first');

    //$('ul.k-group.k-menu-group > li').each(function () {
    //    $(this).attr('style', 'order=2');
    //})

    //$('ul.k-group.k-menu-group').append('<li role="menuitemcheckbox">' +
    //    '<span class="k-link k-menu-link">' +
    //    '<input type="checkbox" type="checkbox" onclick="checkAll(this)">Select All' +
    //    '</span>' +
    //    '</li>');

    //colList.append('<li role="menuitemcheckbox" aria-checked="true" class="k-item k-menu-item k-state-default k-first">' +
    //        '<span class="k-link k-menu-link">' +
    //            '<input type="checkbox" title="Select All" data-field="SelectAll" data-index="0" data-locked="false"">Select All' +
    //        '</span>' +
    //    '</li>');

    //var firstOption = columnsContainer.firstChild.outerHTML;
    //var allColumns = columnsContainer.children;

    //var mylist = e.container.find(".k-columns-item>ul");
    //var listitems = mylist.children('li').get();

    //$(listitems).find(".k-link").click(function (e) {
    //    var chkBox = $(this).first("input")[0];

    //    setTimeout(function () {
    //        if (!$(chkBox).hasClass("gridCustomColumnOption")) {
    //            var allChecked = $(chkBox).closest("ul").find("li.k-item input:checked").length == $(chkBox).closest("ul").find("li.k-item input").length;

    //            $(chkBox).closest("ul").find(".gridCustomColumnOption input")[0].checked = allChecked;

    //        }
    //    }, 1);

    //});

    //$("<li class='gridCustomColumnOption'><span class='k-link'><input id='selectAllBox' type='checkbox' onclick='checkAll(this)'/>Select All</span></li>").insertBefore(e.container.find(".k-columns-item>ul>li").first());

    if ($(this).find('li[name="selectAllBox"]').length == 0) {
        $('ul.k-group.k-menu-group').prepend('<li role="menuitemcheckbox" name="selectAllBox" class="k-item k-menu-item k-state-default k-first" style="order: 1">' +
            '<span class="k-link k-menu-link">' +
            '<input type="checkbox" type="checkbox" onclick="checkAll(this)" data-index="0">Select All' +
            '</span>' +
            '</li>');
    }


    //$('<li role="menuitemcheckbox" name="selectAllBox" class="k-item k-menu-item k-state-default k-first" style="order: 1">' +
    //    '<span class="k-link k-menu-link">' +
    //    '<input type="checkbox" type="checkbox" onclick="checkAll(this)" data-index="0">Select All' +
    //    '</span>' +
    //    '</li>').insertBefore(($('ul.k-group.k-menu-group > li')).first());


}

function checkAll(el) {
    var checked = el.checked;
    $(el).closest("li").siblings().each(function (e) {
        if (!$(this).hasClass("gridCustomColumnOption") && $(this).find("input")[0].checked != checked) {
            $(this).find("input").click();
            $(this).removeClass("k-state-hover");
        }
    });
}
function isCanvasEmpty(cnv) {
    const blank = document.createElement('canvas');
    blank.width = cnv.width;
    blank.height = cnv.height;
    return cnv.toDataURL() === blank.toDataURL();
}
$(document).on('submit', 'form', function (e) {
    isKendoInputsValid(e, this);
});

function isKendoInputsValid(e, form) {
    var isPageValid = true;
    var saveAndExit = $(form).find(".save-and-exit").hasClass("clicked");
    var validationCount = 0;
    if (saveAndExit) {
        return;
    }
    else {
        var buttons = null;
        if (form) {
            buttons = $(form).find('[type="submit"].btn-action-lg');
        }
        var initialText = "";
        var initialInnerText = "";
        if (form && buttons?.length > 1) {
            clickedButtons = $(form).find('[type="submit"].btn-action-lg.clicked');
            if (clickedButtons.length > 0) {
                buttons = clickedButtons;
            }
            initialText = buttons[0].value;
            initialInnerText = buttons[0].innerText;
        }

        //if (isPageValid) {
        $(".kendo-textbox-required-true").each(function () {
            $(this).parent().find('.custom-error-msg').remove();
            if ($(this)[0].value === "" &&
                (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                var label = $(this).parent()?.children(".formQuestion")[0]?.innerText || "This";
                //if (isPageValid) {
                //alert(label + " is required. Please also check all required fields.");
                //}
                $(this)?.parent()?.parent()?.find('.custom-error-msg').remove();
                $(this)?.parent()?.parent()?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");
                //$(this)?.parent()?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");
                var sectionElement = $(this).closest("section");
                if (sectionElement.length > 0) {
                    var sectionId = sectionElement.attr("id");
                    if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                        var pageNum = sectionId.split('-')[1];
                        $('#PageNumber').val(parseInt(pageNum) + 1);
                        $('#PageNumber').trigger("change");
                        validationCount++;
                    }
                }
                e?.preventDefault();
                isPageValid = false;
            }
        });

        $(".kendo-phone-required-true").each(function () {
            $(this).parent().find('.custom-error-msg').remove();
            if ($(this)[0].value === "" &&
                (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                var label = $(this).parent()?.children(".formQuestion")[0]?.innerText || "This";
                //if (isPageValid) {
                //alert(label + " is required. Please also check all required fields.");
                //}
                $(this)?.parent()?.parent()?.find('.custom-error-msg').remove();
                $(this)?.parent()?.parent()?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");
                //$(this)?.parent()?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");
                var sectionElement = $(this).closest("section");
                if (sectionElement.length > 0) {
                    var sectionId = sectionElement.attr("id");
                    if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                        var pageNum = sectionId.split('-')[1];
                        $('#PageNumber').val(parseInt(pageNum) + 1);
                        $('#PageNumber').trigger("change");
                        validationCount++;
                    }
                }
                e?.preventDefault();
                isPageValid = false;
            }

            if ($(this)[0].value != "" && $(this)[0].value != undefined && $(this)[0].value.replace(/\D/g, '').length != 10 &&
                (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                var label = $(this).parent()?.children(".formQuestion")[0]?.innerText || "Phone number";
                //if (isPageValid) {
                //alert(label + " is required. Please also check all required fields.");
                //}
                $(this)?.parent()?.parent()?.find('.custom-error-msg').remove();
                $(this)?.parent()?.parent()?.append("<span class='text-danger custom-error-msg'> Not a valid " + label + " .</span>");
                //$(this)?.parent()?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");
                var sectionElement = $(this).closest("section");
                if (sectionElement.length > 0) {
                    var sectionId = sectionElement.attr("id");
                    if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                        var pageNum = sectionId.split('-')[1];
                        $('#PageNumber').val(parseInt(pageNum) + 1);
                        $('#PageNumber').trigger("change");
                        validationCount++;
                    }
                }
                e?.preventDefault();
                isPageValid = false;
            }

        });

        $("input.kendo-aggregate-required-true.ceu-info-required:not(.k-formatted-value)").each(function () {
            const parentWrapper = $(this).closest('.training-event-ceu-wrapper');
            if (parentWrapper) {
                parentWrapper?.find('.custom-error-msg').remove();
                const ceuSum = $(parentWrapper).find('input.ceu-info-required').map(function () {
                    return parseFloat($(this).val() || 0, 10); // Parse value as an integer
                }).get().reduce(function (acc, val) {
                    return acc + val;
                }, 0);
                if (ceuSum < 0.25) {
                    parentWrapper?.find('.custom-error-msg').remove();
                    parentWrapper.append("<span class='text-danger custom-error-msg'> Please enter a number greater than or equal to 0.25 . </span>");
                    e?.preventDefault();
                    isPageValid = false;
                }
            }
        });

        //}
        //if (isPageValid) {
        $("input.date-required-true").each(function () {
            $(this)?.parent()?.parent()?.parent()?.find('.custom-error-msg').remove();
            if ((($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                    $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                if ($(this)[0].value === "") {
                    var label = $(this).parent().parent().parent().children(".formQuestion")[0].innerText;
                    //if (isPageValid) {
                    //    alert(label + " is required. Please also check all required fields.");
                    //}
                    $(this)?.parent()?.parent()?.parent()?.find('.custom-error-msg').remove();
                    $(this)?.parent()?.parent()?.parent()?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");
                    var sectionElement = $(this).closest("section");
                    if (sectionElement.length > 0) {
                        var sectionId = sectionElement.attr("id");
                        if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                            var pageNum = sectionId.split('-')[1];
                            $('#PageNumber').val(parseInt(pageNum) + 1);
                            $('#PageNumber').trigger("change");
                            validationCount++;
                        }
                    }
                    e?.preventDefault();
                    isPageValid = false;
                }
                else {
                    var dateRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/g;
                    var label = $(this).parent().parent().parent().children(".formQuestion")[0].innerText;
                    if (!dateRegex.test($(this)[0].value)) {
                        //if (isPageValid) {
                        //    alert(label + " date value is not in correct format.The format required is MM/DD/YYYY.");
                        //}
                        $(this)?.parent()?.parent()?.parent()?.find('.custom-error-msg').remove();
                        $(this)?.parent()?.parent()?.parent()?.append("<span class='text-danger custom-error-msg'> " + label + " date value is not in correct format.The format required is MM/DD/YYYY.</span>");
                        e?.preventDefault();
                        isPageValid = false;
                    }
                }
            }
        });
        //}
        //if (isPageValid) {
        $("input.date-required-false").each(function () {
            $(this)?.parent()?.parent()?.parent()?.find('.custom-error-msg').remove();
            if ((($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                    $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                if ($(this)[0].value !== "") {
                    var dateRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/g;
                    var label = $(this).parent().parent().parent().children(".formQuestion")[0].innerText;
                    if (!dateRegex.test($(this)[0].value)) {
                        //if (isPageValid) {
                        //    alert(label + " date value is not in correct format.The format required is MM/DD/YYYY.");
                        //}
                        $(this)?.parent()?.parent()?.parent()?.find('.custom-error-msg').remove();
                        $(this)?.parent()?.parent()?.parent()?.append("<span class='text-danger custom-error-msg'> " + label + " date value is not in correct format.The format required is MM/DD/YYYY.</span>");
                        e?.preventDefault();
                        isPageValid = false;
                    }
                }
            }
        });
        //}
        //if (isPageValid) {
        $(".kendo-editor-required-true").each(function () {
            $(this)?.find('.custom-error-msg').remove();
            if ($(this)[0].value === "" &&
                (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                var label = $(this).attr("aria-label");
                //if (isPageValid) {
                //    alert(label + " is required. Please also check all required fields.");
                //}
                $(this)?.find('.custom-error-msg').remove();
                $(this)?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");

                var sectionElement = $(this).closest("section");
                if (sectionElement.length > 0) {
                    var sectionId = sectionElement.attr("id");
                    if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                        var pageNum = sectionId.split('-')[1];
                        $('#PageNumber').val(parseInt(pageNum) + 1);
                        $('#PageNumber').trigger("change");
                        validationCount++;
                    }
                }
                e?.preventDefault();
                isPageValid = false;
            }
        });
        //}

        //if (isPageValid) {
        $(".kendo-dropdown-required-true input").each(function () {
            $(this).parents(".custom-dropdown").find('.custom-error-msg').remove();
            if ($(this)[0].value === "" &&
                (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                if ($(this).parents(".custom-dropdown").children(".formQuestion").length > 0) {
                    var label = $(this).parents(".custom-dropdown").children(".formQuestion")[0].innerText;
                    $(this).parents(".custom-dropdown").find('.custom-error-msg').remove();
                    $(this)?.parents(".custom-dropdown")?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");
                    //if (isPageValid) {
                    //    alert(label + " is required. Please also check all required fields.");
                    //}
                    var sectionElement = $(this).closest("section");
                    if (sectionElement.length > 0) {
                        var sectionId = sectionElement.attr("id");
                        if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                            var pageNum = sectionId.split('-')[1];
                            $('#PageNumber').val(parseInt(pageNum) + 1);
                            $('#PageNumber').trigger("change");
                            validationCount++;
                        }
                    }
                }
                else {
                    //if (isPageValid) {
                    $(this).parents(".custom-dropdown").find('.custom-error-msg').remove();
                    $(this)?.parents(".custom-dropdown")?.append("<span class='text-danger custom-error-msg'> This is required.</span>");
                    //alert("Please check all required fields.");
                    //}
                }
                e?.preventDefault();
                isPageValid = false;
            }
        });
        //}
        //if (isPageValid) {
        $(".signature-required-true").each(function () {
            $(this)?.find('.custom-error-msg').remove();
            var siblingCanvas = $(this).parent().children('canvas')[0];
            if (siblingCanvas &&
                (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                var isSignatureBlank = isCanvasEmpty(siblingCanvas);
                if (isSignatureBlank) {
                    $(this)?.find('.custom-error-msg').remove();
                    $(this)?.append("<span class='text-danger custom-error-msg'> Signature is required.</span>");
                    //if (isPageValid) {
                    //    alert("Signature is required. Please also check all required fields.");
                    //}
                    isPageValid = false;
                    var sectionElement = $(this).closest("section");
                    if (sectionElement.length > 0) {
                        var sectionId = sectionElement.attr("id");
                        if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                            var pageNum = sectionId.split('-')[1];
                            $('#PageNumber').val(parseInt(pageNum) + 1);
                            $('#PageNumber').trigger("change");
                            validationCount++;
                        }
                    }
                    e?.preventDefault();
                }
            }
        });
        //}
        //if (isPageValid) {
        $(".kendo-multiselect-required-true select").each(function () {
            $(this).parents(".custom-dropdown").find('.custom-error-msg').remove();
            if ($(this)[0].value === "" &&
                (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                {
                    if ($(this).parents(".custom-dropdown").children(".formQuestion").length > 0) {
                        var label = $(this).parents(".custom-dropdown").children(".formQuestion")[0].innerText;
                        //if (isPageValid) {
                        //    alert(label + " is required. Please also check all required fields.");
                        //}
                        $(this).parents(".custom-dropdown").find('.custom-error-msg').remove();
                        $(this)?.parents(".custom-dropdown")?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");
                        var sectionElement = $(this).closest("section");
                        if (sectionElement.length > 0) {
                            var sectionId = sectionElement.attr("id");
                            if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                                var pageNum = sectionId.split('-')[1];
                                $('#PageNumber').val(parseInt(pageNum) + 1);
                                $('#PageNumber').trigger("change");
                                validationCount++;
                            }
                        }
                    }
                    else {
                        $(this).parents(".custom-dropdown").find('.custom-error-msg').remove();
                        $(this)?.parents(".custom-dropdown")?.append("<span class='text-danger custom-error-msg'> This is required.</span>");
                        //if (isPageValid) {
                        //    alert("Please check all required fields.");
                        //}
                    }

                    e?.preventDefault();
                    isPageValid = false;
                }
            }
        });
        //}

        //if (isPageValid) {
        $(".kendo-radiobutton-required-true").parent(".custom-dropdown").each(function () {
            $(this).find('.custom-error-msg').remove();
            if ($(this).children("input:checked").length === 0 &&
                (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                var label = $(this).children(".formQuestion")[0].innerText;
                $(this).find('.custom-error-msg').remove();
                $(this)?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");
                //if (isPageValid) {
                //    alert(label + " is required. Please also check all required fields.");
                //}
                var sectionElement = $(this).closest("section");
                if (sectionElement.length > 0) {
                    var sectionId = sectionElement.attr("id");
                    if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                        var pageNum = sectionId.split('-')[1];
                        $('#PageNumber').val(parseInt(pageNum) + 1);
                        $('#PageNumber').trigger("change");
                        validationCount++;
                    }
                }
                e?.preventDefault();
                isPageValid = false;
            }
        });
        //}

        //if (isPageValid) {
        $(".kendo-checkbox-required-true").parent(".custom-dropdown").each(function () {
            $(this).find('.custom-error-msg').remove();
            if ($(this).children("input:checked").length === 0 &&
                (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                var label = $(this).children(".formQuestion")[0].innerText;
                //if (isPageValid) {
                //    alert(label + " is required. Please also check all required fields.");
                //}
                $(this).find('.custom-error-msg').remove();
                $(this)?.append("<span class='text-danger custom-error-msg'> " + label + " is required.</span>");
                var sectionElement = $(this).closest("section");
                if (sectionElement.length > 0) {
                    var sectionId = sectionElement.attr("id");
                    if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                        var pageNum = sectionId.split('-')[1];
                        $('#PageNumber').val(parseInt(pageNum) + 1);
                        $('#PageNumber').trigger("change");
                        validationCount++;
                    }
                }
                e?.preventDefault();
                isPageValid = false;
            }
        });
        //}

        if (isPageValid) {
            $("textarea.required-true").each(function () {
                if ($(this)[0].value === "" &&
                    (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                        !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                        ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                            $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                    var label = $(this).parent().children(".formQuestion")[0].innerText;
                    if (isPageValid) {
                        alert(label + " is required. Please also check all required fields.");
                    }
                    var sectionElement = $(this).closest("section");
                    if (sectionElement.length > 0) {
                        var sectionId = sectionElement.attr("id");
                        if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                            var pageNum = sectionId.split('-')[1];
                            $('#PageNumber').val(parseInt(pageNum) + 1);
                            $('#PageNumber').trigger("change");
                            validationCount++;
                        }
                    }
                    e?.preventDefault();
                    isPageValid = false;
                }
            });
        }
        if (isPageValid) {
            $("input.required-true").each(function () {
                if ($(this)[0].value === "" &&
                    (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                        !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                        ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                            $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                    var label = $(this).parent().children(".formQuestion")[0] != undefined ? $(this).parent().children(".formQuestion")[0].innerText : $(this).parent().parent().children(".formQuestion")[0].innerText;
                    if (isPageValid) {
                        alert(label + " is required. Please also check all required fields.");
                    }
                    var sectionElement = $(this).closest("section");
                    if (sectionElement.length > 0) {
                        var sectionId = sectionElement.attr("id");
                        if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                            var pageNum = sectionId.split('-')[1];
                            $('#PageNumber').val(parseInt(pageNum) + 1);
                            $('#PageNumber').trigger("change");
                            validationCount++;
                        }
                    }
                    e?.preventDefault();
                    isPageValid = false;
                }
            });
        }

        if (isPageValid) {
            $(".file-required-true").each(function () {
                var fileCount = $(this).data("kendoUpload").getFiles().length;
                var questionId = parseInt(this.id.split('-')[1]);
                var currentAttachmentsCounts = $(".QuestionId-" + questionId).find('div[id^="file-"]').length ?? 0;
                if (fileCount + currentAttachmentsCounts === 0 &&
                    (($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                        !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                        ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                            $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                    e?.preventDefault();
                    var label = $(this).parent().parent().parent().parent().children(".formQuestion")[0].innerText;
                    if (isPageValid) {
                        alert(label + " is required. Please also check all required fields.");
                    }
                    var sectionElement = $(this).closest("section");
                    if (sectionElement.length > 0) {
                        var sectionId = sectionElement.attr("id");
                        if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                            var pageNum = sectionId.split('-')[1];
                            $('#PageNumber').val(parseInt(pageNum) + 1);
                            $('#PageNumber').trigger("change");
                            validationCount++;
                        }
                    }
                    isPageValid = false;
                }
            });
        }

        if (isPageValid) {
            var hasValue = false;
            $('div.grid-required-true').each(function () {
                if ((($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                    var question = $(this).find('div.formQuestion')[0].innerText;
                    hasValue = false;
                    $(this).find('input').each(function () {
                        var id = $(this).attr('id')
                        var inputType = $(this).attr('type');
                        if (id != undefined) {
                            if (inputType == 'checkbox' || inputType == 'radio') {
                                if ($(this).is(':checked')) {
                                    hasValue = true;
                                }
                            }
                            else {
                                if ($(this).val() != "") {
                                    hasValue = true;
                                }
                            }
                        }
                    });

                    if (!hasValue) {
                        if (isPageValid) {
                            alert(question + " is required. Please also check all required fields.");
                        }
                        var sectionElement = $(this).closest("section");
                        if (sectionElement.length > 0) {
                            var sectionId = sectionElement.attr("id");
                            if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                                var pageNum = sectionId.split('-')[1];
                                $('#PageNumber').val(parseInt(pageNum) + 1);
                                $('#PageNumber').trigger("change");
                                validationCount++;
                            }
                        }
                        e?.preventDefault();
                        isPageValid = hasValue;
                    }
                }
            });
        }

        if (isPageValid) {
            var hasValue = false;
            $('div.multiple-text-required-true').each(function () {
                if ((($(this).closest(".divAdditionalQuestionVisibilityWrapper").length === 0 &&
                    !$(this).closest(".toggleSection").hasClass("initial-hide")) ||
                    ($(this).closest(".divAdditionalQuestionVisibilityWrapper").length > 0 &&
                        $(this).closest(".divAdditionalQuestionVisibilityWrapper").css("display") !== "none"))) {
                    var question = $(this).find('div.formQuestion')[0].innerText;
                    hasValue = false;
                    $(this).find('input').each(function () {
                        var id = $(this).attr('id')
                        var inputType = $(this).attr('type');
                        if (id != undefined) {
                            if (inputType == 'checkbox' || inputType == 'radio') {
                                if ($(this).is(':checked')) {
                                    hasValue = true;
                                }
                            }
                            else {
                                if ($(this).val() != "") {
                                    hasValue = true;
                                }
                            }
                        }
                    });

                    if (!hasValue) {
                        if (isPageValid) {
                            alert(question + " is required. Please also check all required fields.");
                        }
                        var sectionElement = $(this).closest("section");
                        if (sectionElement.length > 0) {
                            var sectionId = sectionElement.attr("id");
                            if (sectionId.indexOf("pageNumber") !== -1 && validationCount == 0) {
                                var pageNum = sectionId.split('-')[1];
                                $('#PageNumber').val(parseInt(pageNum) + 1);
                                $('#PageNumber').trigger("change");
                                validationCount++;
                            }
                        }
                        e?.preventDefault();
                        isPageValid = hasValue;
                    }
                }
            });
        }
        if (form && $(form).valid() && isPageValid) {
            if (!buttons.hasClass("no-loading")) {
                if (buttons.hasClass("btn-disabled")) {
                    e?.preventDefault();
                }
                else {
                    buttons.addClass("btn-disabled");
                }
                let btnMessage = 'Please Wait..'
                const culture = getCulture();
                if (culture && culture === 'es-ES') {
                    btnMessage = 'Espere por favor..'
                }
                buttons.each(function (btn) {
                    if (!buttons.hasClass("btn-no-change")) {
                        $(buttons[btn]).prop('disabled', true);

                        $(buttons[btn]).val(btnMessage);
                    }
                    else {
                        $(buttons[btn]).text(btnMessage);
                    }
                });
            }
        } else if (buttons?.length > 1) {
            buttons.each(function (btn) {
                if (!buttons.hasClass("btn-no-change")) {
                    $(buttons[btn]).prop('disabled', false);

                    $(buttons[btn]).val(initialText);
                }
                else {
                    $(buttons[btn]).text(initialInnerText);
                }
            });
            if (isPageValid === true) {
                alert("Please look for the required field(s) to continue.");
            }
        }
    }
    if (!isPageValid) {
        alert("Please look for the required field(s) to continue.");
    }
    return isPageValid;
}

window.onscroll = function () { scrollFunction() };
function getCulture() {
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    return urlParams?.get('culture') || '';
}

function scrollFunction() {
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
        $(".upArrowLink").css("display", "block");
    } else {
        $(".upArrowLink").css("display", "none");
    }
}

function validateTextBox(e) {
    var layoutName = $(this).parent().children("input").val();
    if (layoutName == "")
        e.preventDefault();
}

function handlePagerVisibility() {
    $(".k-pager-sm").each(function () {
        if (window.innerWidth >= 1365) {
            $(this).removeClass("k-pager-sm");
        }
        else if (window.innerWidth < 1365 && window.innerWidth >= 995) {
            $(this).removeClass("k-pager-sm");
            $(this).addClass("k-pager-lg");
        }
        else if (window.innerWidth < 995 && window.innerWidth >= 821) {
            $(this).removeClass("k-pager-sm");
            $(this).addClass("k-pager-md");
        }
    });
}

$(document).ready(function () {
    handlePagerVisibility();
    $('tr.k-master-row td.no-print').addClass('firstGridButton');

    $(".layoutBtn").click(function (e) {
        var layoutName = $(this).parent().children("input").val();
        if (layoutName == "")
            e.preventDefault();
    });

    $('.no-enter-submit input').on('keyup keypress', function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode === 13) {
            e.preventDefault();
            return false;
        }
    });

    $(".upArrowLink").click(function () {
        $("html, body").animate({
            scrollTop: 0
        }, 'slow');
    });

    $("address:not(.viewed-map)").each(function () {
        if (isScrolledIntoView($(this))) {
            $(this).addClass("viewed-map");

            var embed = "<iframe width='100%' height='150' frameborder='0' scrolling='no'  marginheight='0' marginwidth='0'   src='https://maps.google.com/maps?&amp;q=" + encodeURIComponent

                ($(this).text()) + "&amp;output=embed'></iframe>";
            $(this).html(embed);
        }
    });

    $(".viewPopup").click(function () {
        $(this).parent().parent().find('#popup').css("display", "block");
    });

    $(".btnCloseCss").click(function () {
        var video = $(this).parent().parent().find("video");

        if (video[0] != undefined) {
            video[0].pause();
            video[0].currentTime = 0;
        }

        $(this).closest('#popup').css("display", "none");
    });

    var navValue = readCookie("condensedNav");
    if (navValue == 'true') {
        $("#navContainer").addClass("condensed");
        $("#navContainer").removeClass("expanded");
        $(".form-horizontal").addClass("margined");
        $(".form-horizontal").css("margin-left", "135px");
        $(".respNavHamburger").css("left", "115px");
        $(".respNavHamburger").addClass("rotate");
    }
    else {
        $("#navContainer").removeClass("condensed");
        $("#navContainer").addClass("expanded");
        $(".form-horizontal").removeClass("margined");
        $(".form-horizontal").css("margin-left", "230px");
        $(".respNavHamburger").css("left", "205px");
        $(".respNavHamburger").removeClass("rotate");
    }

    var currentUrl = (window.location.href).toLowerCase();
    if (currentUrl.indexOf('onlinetraining/submission') == -1 && currentUrl.indexOf('quiz/submission') == -1 &&
        currentUrl.indexOf('discussionpost') == -1) {
        UpdateLessonMinutes();
    }

    if (currentUrl.indexOf('create') != -1) {
        $('span.k-textbox > input').attr('value', '');
    }

    if (currentUrl.indexOf('account/login') != -1 || currentUrl.indexOf('account/logoutconfirmation') != -1 ||
        currentUrl.indexOf('account/forgotpassword') != -1 || currentUrl.indexOf('home/unauthorized') != -1 ||
        currentUrl.indexOf('account/forgotpasswordconfirmation') != -1 ||
        currentUrl.indexOf('account/resetpasswordconfirmation') != -1 ||
        currentUrl.indexOf('account/resetpassword') != -1) {
        $('#mainBody').addClass('backgroundGradient');
    }

    function UpdateLessonMinutes() {
        var currentSeconds = 0;

        var currentSecondStoredValue = readCookie("currentSecondValue");
        if (currentSecondStoredValue != 'NaN') {
            if (currentSecondStoredValue != null)
                currentSeconds = parseInt(currentSecondStoredValue);
            else
                currentSeconds = 0;
        }
        else
            currentSeconds = 0;

        var currentRegistrationId = 0;

        var currentRegistrationIdValue = readCookie("currentRegistrationId");
        if (currentRegistrationIdValue != 'NaN') {
            if (currentRegistrationIdValue != null)
                currentRegistrationId = parseInt(currentRegistrationIdValue);
            else
                currentRegistrationId = 0;
        }
        else
            currentRegistrationId = 0;

        var currentLessonId = 0;

        var currentLessonIdValue = readCookie("currentLessonId");
        if (currentLessonIdValue != 'NaN') {
            if (currentLessonIdValue != null)
                currentLessonId = parseInt(currentLessonIdValue);
            else
                currentLessonId = 0;
        }
        else
            currentLessonId = 0;

        var currentLaunchId = 0;
        var currentLaunchIdValue = readCookie("currentLaunchId");
        if (currentLaunchIdValue != 'NaN') {
            if (currentLessonIdValue != null)
                currentLaunchId = parseInt(currentLaunchIdValue);
            else
                currentLaunchId = 0;
        }
        else
            currentLaunchId = 0;

        if (currentRegistrationId > 0) {

            var updateLessonMinutesLink = "/eventmanager/onlinetraining/updatelessonminutes?registrationid=currentRegistrationId&lessonid=currentLessonId&currentsecond=currentSecondValue&launchHistoryId=currentLaunchHistoryValue";
            updateLessonMinutesLink = updateLessonMinutesLink.replace("currentRegistrationId", currentRegistrationId).replace("amp;", "");
            updateLessonMinutesLink = updateLessonMinutesLink.replace("currentLessonId", currentLessonId).replace("amp;", "");
            updateLessonMinutesLink = updateLessonMinutesLink.replace("currentSecondValue", currentSeconds).replace("amp;", "");
            updateLessonMinutesLink = updateLessonMinutesLink.replace("currentLaunchHistoryValue", currentLaunchId).replace("amp;", "");
            updateLessonMinutesLink = updateLessonMinutesLink.replace("amp;", "");
            updateLessonMinutesLink = updateLessonMinutesLink.replace("amp;", "");
            updateLessonMinutesLink = updateLessonMinutesLink.replace("amp;", "");
            $.ajax(
                {
                    url: updateLessonMinutesLink,
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {

                    },
                    error: function () {

                    }
                });
        }

        delCookie("currentSecondValue");
        delCookie("currentRegistrationId");
        delCookie("currentLessonId");
        delCookie("resetLessonTimer");
        delCookie("currentLaunchId");
    }

    var mainmenu = $("#nav");

    $('li.navListItem').click(function () {
        $(this).find('ul.subMenuWrapper').toggleClass('initial-hide');
        $(this).find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');

        //if ($(this).find('ul.subMenuWrapper').hasClass('initial-hide') || $(this).hasClass('active')) {
        //    $(this).find('ul.subMenuWrapper').toggleClass('initial-hide');
        //}

        //if (!$(this).find('i.bi.bi-chevron-down').hasClass('subMenuOpen') || $(this).hasClass('active')) {
        //    $(this).find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
        //}

    });

    $('ul.subMenuWrapper').click(function () {
        $(this).toggleClass('initial-hide');
        $(this).parent('li.navListItem').find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
    });

    if ($('ul.subMenuWrapper').hasClass('subMenuOpen')) {
        $(this).parent('li.navListItem').find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
    }

    //SubMenu
    $(mainmenu).children("li").each(function () {
        var atag = $(this).children("a")

        if ($(this).find('ul.subMenuWrapper').length > 0) {
            $(this).find('i.fa.fa-plus').removeClass('initial-hide');
        }

        if (currentUrl.indexOf('admin') != -1) {
            $("#adminNav").addClass("active");
            if ($("ul#nav > li.active") !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('contactmanager') != -1) {
            $("#contactNav").addClass("active");
            if ($("#contactNav ul.subMenuWrapper").length > 0) {
                $("#contactNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'contactmanager') {
                    $("li#dashboard").addClass("active");
                }
                if (lastIndexString == 'create') {
                    $("li#newContact").addClass("active");
                }
                if (lastIndexString == 'coalitionstaff') {
                    $("li#coalitionStaff").addClass("active");
                }
                if (lastIndexString == 'contact') {
                    $("li#contactList").addClass("active");
                }
                if (lastIndexString == 'user') {
                    $("li#unserList").addClass("active");
                }
                if (lastIndexString == 'accessgroup') {
                    $("li#accessGroups").addClass("active");
                }
                if (lastIndexString == 'savedreport') {
                    $("li#savedReport").addClass("active");
                }
                if (lastIndexString == 'contactdirectory') {
                    $("li#contactDirectory").addClass("active");
                }
                if (lastIndexString == 'viewall') {
                    $("li#menuAdditionalInformationDataList").addClass("active");
                }
                $("#contactNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }
            else {
                if (currentUrl.indexOf('userintegration') > -1) {
                    if ($("#legalNav ul.subMenuWrapper").length > 0) {
                        $("#legalNav ul.subMenuWrapper").removeClass('initial-hide');
                        $("li#legalAttorneyIntegration").addClass("active");
                        $("#legalNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
                    }
                }
            }
        }

        else if (currentUrl.indexOf('tamanager') != -1) {
            $("#taNav").addClass("active");
            if ($("#taNav ul.subMenuWrapper").length > 0) {
                $("#taNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'tamanager') {
                    $("li#dashboard").addClass("active");
                }
                if (lastIndexString == 'create') {
                    $("li#newTaEntry").addClass("active");
                }
                if (lastIndexString == 'tareportsummary') {
                    $("li#searchTaEntry").addClass("active");
                }
                if (lastIndexString == 'tareport') {
                    $("li#currentTaEntry").addClass("active");
                }
                if (lastIndexString == 'savedreport') {
                    $("li#savedTaReport").addClass("active");
                }

                $("#taNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('pamanager') != -1) {
            $("#paNav").addClass("active");
            if ($("#paNav ul.subMenuWrapper").length > 0) {
                $("#paNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'pamanager') {
                    $("li#paDashboard").addClass("active");
                }
                if (lastIndexString == 'create') {
                    $("li#newPaEntry").addClass("active");
                }
                if (lastIndexString == 'pareportsummary') {
                    $("li#searchPaEntry").addClass("active");
                }
                if (lastIndexString == 'pareport') {
                    $("li#currentPaEntry").addClass("active");
                }
                if (lastIndexString == 'savedreport') {
                    $("li#savedPaReport").addClass("active");
                }

                $("#paNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }

        }

        else if (currentUrl.indexOf('donormanager') != -1) {
            $("#donorNav").addClass("active");
            if ($("#donorNav ul.subMenuWrapper").length > 0) {
                $("#donorNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'donormanager') {
                    $("li#donerDashboard").addClass("active");
                }
                if (lastIndexString == '0') {
                    $("li#newDonation").addClass("active");
                }
                if (lastIndexString == 'donorprofile') {
                    $("li#donorProfiles").addClass("active");
                }
                if (lastIndexString == 'donation') {
                    $("li#donationList").addClass("active");
                }
                if (lastIndexString == 'donationsummary') {
                    $("li#donationSearch").addClass("active");
                }
                if (lastIndexString == 'savedreport') {
                    $("li#donationReports").addClass("active");
                }
                if (lastIndexString == 'donorinteraction') {
                    $("li#donorInteractions").addClass("active");
                }
                $("#donorNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('eventmanager') != -1) {
            $("#trainingNav").addClass("active");
            if ($("#trainingNav ul.subMenuWrapper").length > 0) {
                $("#trainingNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var prevIndexString = splitCurrentUrl[splitCurrentUrl.length - 2];
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'eventmanager') {
                    $("li#trainingDashboard").addClass("active");
                }
                if ((prevIndexString == 'trainingevent' && lastIndexString == 'createseries') || (prevIndexString == 'trainingevent' && lastIndexString == 'create')) {
                    $("li#newTrainingEvent").addClass("active");
                }
                if ((prevIndexString == 'onlinetraining' && lastIndexString == 'create')) {
                    $("li#newOnlineTraining").addClass("active");
                }
                if (lastIndexString == 'eventsearch') {
                    $("li#upcomingEventSearch").addClass("active");
                }
                if (lastIndexString == 'trainingeventsummary') {
                    $("li#eventDataSummary").addClass("active");
                }
                if (lastIndexString == 'alltrainingseries') {
                    $("li#currentSeries").addClass("active");
                }
                if (lastIndexString == 'trainingevent') {
                    $("li#currentEvents").addClass("active");
                }
                if (lastIndexString == 'onlinetraining') {
                    $("li#onlineTrainings").addClass("active");
                }
                if (lastIndexString == 'trainingeventattendee') {
                    $("li#trainingEvetAttendees").addClass("active");
                }
                if (lastIndexString == 'trainingeventregistrationsummary') {
                    $("li#trainingRegistrations").addClass("active");
                }
                if (lastIndexString == 'failuretocancel') {
                    $("li#faliureToCancel").addClass("active");
                }
                if (lastIndexString == 'externaltraining') {
                    $("li#nonCoalitionTrainings").addClass("active");
                }
                if (lastIndexString == 'trainingcompliancestatus') {
                    $("li#complianceStatus").addClass("active");
                }
                if (lastIndexString == 'savedreport') {
                    $("li#trainingSavedReport").addClass("active");
                }
                if (lastIndexString == 'onlinetrainingsummary') {
                    $("li#onlineTrainingReport").addClass("active");
                }
                if (prevIndexString == 'details') {
                    $("li#myTrainingProfile").addClass("active");
                }
                if (prevIndexString == 'trainingeventregistration') {
                    $("li#myTrainingRegistrations").addClass("active");
                }
                if (lastIndexString == 'eventsearch') {
                    $("li#upcomingTrainingEventsSearch").addClass("active");
                }
                if (prevIndexString == 'memberstrainingevent' && lastIndexString == 'index') {
                    $("li#membersTrainingEvent").addClass("active");
                }

                $("#trainingNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('timetracker') != -1) {
            $("#timeTrackerNav").addClass("active");
            if ($("#timeTrackerNav ul.subMenuWrapper").length > 0) {
                $("#timeTrackerNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'timetracker') {
                    $("li#timeTrackerTimesheet").addClass("active");
                }
                if (lastIndexString == 'timereport') {
                    $("li#newDonation").addClass("active");
                }
                if (lastIndexString == 'tasklist') {
                    $("li#timeTrackerTaskList").addClass("active");
                }
                if (lastIndexString == 'submissiondetail') {
                    $("li#timeTrackerTimeReport").addClass("active");
                }
                if (lastIndexString == 'reportsummary') {
                    $("li#timeTrackerTimeSearch").addClass("active");
                }
                if (lastIndexString == 'savedreport') {
                    $("li#timeTrackerSavedReport").addClass("active");
                }
                if (lastIndexString == 'approvalrequest') {
                    $("li#timeTrackerTimeRequests").addClass("active");
                }
                if (lastIndexString == 'status') {
                    $("li#timeTrackerSubmissionStatus").addClass("active");
                }

                $("#timeTrackerNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('combinedreport') != -1) {
            $("#reportsNav").addClass("active");

            if ($("#reportsNav ul.subMenuWrapper").length > 0) {
                $("#reportsNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'dashboard') {
                    $("li#combinedReportDashboard").addClass("active");
                }
                if (lastIndexString == 'combinedreport') {
                    $("li#combinedReportsSearch").addClass("active");
                }
                if (lastIndexString == 'savedreport') {
                    $("li#combinedSavedReports").addClass("active");
                }
                if (lastIndexString == 'paymentlog') {
                    $("li#combinedPaymentLog").addClass("active");
                }

                $("#reportsNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('resourcemanager') != -1) {
            $("#resourceManagerNav").addClass("active");

            if ($("#resourceManagerNav ul.subMenuWrapper").length > 0) {
                $("#resourceManagerNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'resourcemanager') {
                    $("li#resourceManagerDashboard").addClass("active");
                }
                if (lastIndexString == 'create') {
                    $("li#resourceManagerNewResource").addClass("active");
                }
                if (lastIndexString == 'resourcefilesummary') {
                    $("li#resourceManagerResourceSummary").addClass("active");
                }
                if (lastIndexString == 'savedreport') {
                    $("li#resourceManagerSavedReport").addClass("active");
                }
                if (lastIndexString == 'resourcefile') {
                    $("li#resourceManagerCurrentResources").addClass("active");
                }
                if (lastIndexString == 'resourcelibrary') {
                    $("li#resourceManagerResourceLibrary").addClass("active");
                }

                $("#resourceManagerNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('formmanager') != -1) {
            $("#formManagerNav").addClass("active");

            if ($("#formManagerNav ul.subMenuWrapper").length > 0) {
                $("#formManagerNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'formmanager') {
                    $("li#formManagerDashboard").addClass("active");
                }
                if (lastIndexString == 'create') {
                    $("li#formManagerNewForm").addClass("active");
                }
                if (lastIndexString == 'formsummary') {
                    $("li#formManagerFormSearch").addClass("active");
                }
                if (lastIndexString == 'customform') {
                    $("li#formManagerCurrentForms").addClass("active");
                }
                if (lastIndexString == 'vieweditrequest') {
                    $("li#formManagerEditRequest").addClass("active");
                }

                $("#formManagerNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('lendinglibrary') != -1) {
            $("#lendingLibraryNav").addClass("active");

            if ($("#lendingLibraryNav ul.subMenuWrapper").length > 0) {
                $("#lendingLibraryNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'lendinglibrary') {
                    $("li#lendingLibraryDashboard").addClass("active");
                }
                if (lastIndexString == 'create') {
                    $("li#lendingLibraryNewResource").addClass("active");
                }
                if (lastIndexString == 'libraryresourcesummary') {
                    $("li#lendingLibraryResourseSearch").addClass("active");
                }
                if (lastIndexString == 'libraryresource') {
                    $("li#lengingLibraryCurrentResources").addClass("active");
                }
                if (lastIndexString == 'libraryresourcelendee') {
                    $("li#lendingLibraryResourceBorrowers").addClass("active");
                }
                if (lastIndexString == 'libraryresourceorder') {
                    $("li#lendingLibraryCurrentOrders").addClass("active");
                }

                $("#lendingLibraryNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('casemanager') != -1) {
            $("#caseManagerNav").addClass("active");

            if ($("#caseManagerNav ul.subMenuWrapper").length > 0) {
                $("#caseManagerNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'casemanager') {
                    $("li#caseManagerDashboard").addClass("active");
                }

                if (lastIndexString == 'create') {
                    $("li#createClientInformation").addClass("active");
                }
                if (lastIndexString == 'clientinformation') {
                    $("li#clinetInformationIndex").addClass("active");
                }
                if (lastIndexString == 'clientreportsummary') {
                    $("li#clientReportSummary").addClass("active");
                }
                if (lastIndexString == 'casereportsummary') {
                    $("li#caseReportSummary").addClass("active");
                }
                if (lastIndexString == 'volunteer') {
                    $("li#volunteerAttorneyList").addClass("active");
                }
                if (lastIndexString == 'savedreport') {
                    $("li#caseManagerSavedReport").addClass("active");
                }

                $("#formManagerNav").find('i.bi.bi-chevron-down').toggleClass('subMenuOpen');
            }

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('merge') != -1) {
            $("#mergeNav").addClass("active");

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }

        else if (currentUrl.indexOf('legal') != -1) {
            $("#legalNav").addClass("active");

            if ($("#legalNav ul.subMenuWrapper").length > 0) {
                $("#legalNav ul.subMenuWrapper").removeClass('initial-hide');

                var splitCurrentUrl = currentUrl.split('/')
                var thirdLastIndexString = splitCurrentUrl[splitCurrentUrl.length - 3];
                var prevIndexString = splitCurrentUrl[splitCurrentUrl.length - 2];
                var lastIndexString = splitCurrentUrl[splitCurrentUrl.length - 1];

                if (lastIndexString == 'legal') {
                    $("li#legalDashboard").addClass("active");
                }
                if (lastIndexString == 'attorney') {
                    $("li#attorneyDashboard").addClass("active");
                }
                if (prevIndexString == 'attorney' && lastIndexString == 'create') {
                    $("li#legalNewAttorney").addClass("active");
                }
                if (thirdLastIndexString == 'attorney' && prevIndexString == 'edit') {
                    $("li#legalAttorneyProfileEdit").addClass("active");
                }
                if (prevIndexString == 'survivor' && lastIndexString == 'create') {
                    $("li#legalNewSurvivor").addClass("active");
                }
                if (lastIndexString == 'agency') {
                    $("li#legalAgencies").addClass("active");
                }
                if (lastIndexString == 'advocate') {
                    $("li#legalAdvocates").addClass("active");
                }
                if (lastIndexString == 'survivorconsultation') {
                    $("li#legalConsultations").addClass("active");
                }
                if (prevIndexString == 'schedule') {
                    $("li#legalAttorneySchedule").addClass("active");
                }
                if (thirdLastIndexString == 'userintegration' && prevIndexString == 'index') {
                    $("li#legalAttorneyIntegration").addClass("active");
                }
            }

            if ($("ul#nav > li.active").offset() !== undefined) {
                $('.navContainer').animate({
                    scrollTop: $("ul#nav > li.active").offset().top - 30
                }, 0);
            }
        }
        //else if (currentUrl.indexOf('Manage') != -1 || currentUrl.indexOf('manage') != -1 || currentUrl.indexOf('Home') != -1 || currentUrl.indexOf('home') != -1)
        //    $("#accountNav").addClass("expanded");
        else
            $("#dashboardNav").addClass("active");

    });

    //$('input').each(function () {
    //    if ($(this).hasClass("required-true")) {
    //        $(this).prop("required", "true");
    //    }
    //});
    $(document).on('submit', 'form', function (e) {
        var activeButton = $(document)[0].activeElement;
        if (activeButton.className.indexOf("clicked") > -1) {
            return;
        }
        else {
            $('input').each(function () {
                var saveAndExit = $(this).find(".save-and-exit").hasClass("clicked");
                if (saveAndExit) {
                    return;
                }
                else {
                    if ($(this).hasClass("required-true")) {
                        $(this).prop("required", "true");
                    }
                }
            });
        }
    });

    $(".toggleSection").each(function () {
        if ($(this).hasClass("expanded")) {
            $(this).find(".toggleContent").slideDown(0);
        }
        else {
            $(this).find(".toggleContent").slideUp(0);
        }
    });


    function addNestedForm(container, counter, ticks, content) {
        var nextIndex = $(counter).length;
        var pattern = new RegExp(ticks, "gi");
        content = content.replace(pattern, nextIndex);
        $(container).append(content);
    }

    function removeNestedForm(element, container, deleteElement) {
        $container = $(element).parents(container);
        $container.find(deleteElement).val('True');
        $container.hide();
    }

    $("#accountNav").each(function () {
        if ($(this).hasClass("expanded")) {
            $(this).slideDown(0);
        }
        else {
            $(this).slideUp(0);
        }
    });

    function stopIntervalTimers(timerName) {
        clearInterval(timerName);
    }



    $("#advancedView").click(function () {
        $(this).addClass("active");
        $("#dataView").removeClass("active");
        $("#combinedReportView").removeClass("active");
        $("#reportGraphs").removeClass("active");
        $("#summarizedResult").css("display", "none");
        $("#advancedResult").css("display", "block");
        $("#combinedReportResult").css("display", "none");
        $("#graphicalReportView").css("display", "none");
    });

    $("#dataView").click(function () {
        $(this).addClass("active");
        $("#advancedView").removeClass("active");
        $("#combinedReportView").removeClass("active");
        $("#reportGraphs").removeClass("active");
        $("#summarizedResult").css("display", "block");
        $("#advancedResult").css("display", "none");
        $("#combinedReportResult").css("display", "none");
        $("#graphicalReportView").css("display", "none");
    });

    $("#combinedReportView").click(function () {
        $(this).addClass("active");
        $("#advancedView").removeClass("active");
        $("#dataView").removeClass("active");
        $("#reportGraphs").removeClass("active");
        $("#combinedReportResult").css("display", "block");
        $("#summarizedResult").css("display", "none");
        $("#advancedResult").css("display", "none");
        $("#graphicalReportView").css("display", "none");
    });

    $("#reportGraphs").click(function () {
        $(this).addClass("active");
        $("#advancedView").removeClass("active");
        $("#dataView").removeClass("active");
        $("#combinedReportView").removeClass("active");
        $("#combinedReportResult").css("display", "none");
        $("#summarizedResult").css("display", "none");
        $("#advancedResult").css("display", "none");
        $("#graphicalReportView").css("display", "block");
    });

    $(".toggleLink").click(function () {
        if ($(this).parent(".toggleSection").hasClass("expanded")) {
            $(this).parent(".toggleSection").removeClass("expanded");
            $(this).children("i").css("display", "block");
            $(this).next(".toggleContent").slideUp(250);
        }
        else {
            //$(".toggleSection").removeClass("expanded");
            //$(".toggleSection").find(".toggleContent").slideUp(250);
            //$(".toggleSection").find("i").removeClass("fa-minus");
            //$(".toggleSection").find("i").addClass("fa-plus");

            $(this).parent(".toggleSection").addClass("expanded");
            $(this).children("i").css("display", "none");
            $(this).next(".toggleContent").slideDown(250);


            var grid = $(this).parent('.toggleSection').find('.k-grid');

            if (grid.length > 0) {
                for (var i = 0; i < grid.length; i++) {
                    var gridId = grid[0].id;
                    if (gridId != undefined && gridId != "") {
                        var gridData = $('#' + gridId).data("kendoGrid");

                        if (gridData != undefined) {
                            kendo.resize($("#" + gridId));
                            kendo.resize(gridData);
                            gridData.dataSource.read();
                        }
                    }
                }
            }

        }
    });

    $(document).on('click', ".toggleLinkModal", function () {
        if ($(this).parent(".toggleSectionModal").hasClass("expanded")) {
            $(this).parent(".toggleSectionModal").removeClass("expanded");
            $(this).children("i").css("display", "block");
            $(this).next(".toggleContentModal").slideUp(250);
        }
        else {
            $(this).parent(".toggleSectionModal").addClass("expanded");
            $(this).children("i").css("display", "none");
            $(this).next(".toggleContentModal").slideDown(250);


            var grid = $(this).parent('.toggleSectionModal').find('.k-grid');

            if (grid.length > 0) {
                for (var i = 0; i < grid.length; i++) {
                    var gridId = grid[0].id;
                    if (gridId != undefined && gridId != "") {
                        var gridData = $('#' + gridId).data("kendoGrid");

                        if (gridData != undefined) {
                            kendo.resize($("#" + gridId));
                            kendo.resize(gridData);
                            gridData.dataSource.read();
                        }
                    }
                }
            }

        }
    });

    $(".accountNav").click(function () {
        if ($("#accountNav").hasClass("expanded")) {
            $(this).removeClass("expanded");
            $("#accountNav").removeClass("expanded");
            $("#accountNav").slideUp(250);
        }
        else {
            $(this).addClass("expanded");
            $("#accountNav").addClass("expanded");
            $("#accountNav").slideDown(250);
        }
    });

    $("input#HasLink").change(function () {
        if ($(this).is(":checked"))
            $("#divLinkInformation").css("display", "block");
        else
            $("#divLinkInformation").css("display", "none");
    });

    $(".respNavHamburger").click(function () {
        if ($(window).width() >= 768) {
            $("#navContainer").toggleClass("condensed expanded");
            if ($("#navContainer").hasClass("condensed")) {
                createCookie("condensedNav", "true", 1);
                $(".form-horizontal").addClass("margined");
                $(".form-horizontal").css("margin-left", "135px");
                $(".respNavHamburger").css("left", "115px");
                $(".respNavHamburger").addClass("rotate");
            }
            else {
                delCookie("condensedNav");
                $(".form-horizontal").removeClass("margined");
                $(".respNavHamburger").css("left", "190px");
                $(".form-horizontal").css("margin-left", "230px");
                $(".respNavHamburger").removeClass("rotate");
            }

        }
        else {
            $("body").toggleClass("navOn");
            $(".navContainer").toggleClass("navOn");
            $(".respNavHamburger").css("left", "0p");
            $(".respNavHamburger").toggleClass("rotate");
        }
    });

    //$("input[type=text]").click(function () {
    //    selectAllText(this);
    //});

    //$(".k-input").click(function () {
    //    selectAllText(this);
    //});

    $(".toggle-password").click(function () {

        $(this).toggleClass("fa-eye fa-eye-slash");
        var input = $(this).parent().find("#Password");

        if (input.length <= 0)
            input = $(this).parent().find("#ConfirmPassword");

        if (input.attr("type") == "password") {
            input.attr("type", "text");
        } else {
            input.attr("type", "password");
        }
    });

    $("#Password").focus(function () {
        $(".toggle-password").css("display", "block");
    })

    $("#ConfirmPassword").focus(function () {
        $(".toggle-password").css("display", "block");
    })

    $(".toggle-password").css("display", "none");

    $('#publicForm').on('submit', function (e) {
        if ($(".g-recaptcha").length > 0) {
            var response = grecaptcha.getResponse();
            //recaptcha failed validation
            if (response.length == 0) {
                e.preventDefault();
                $('#html_element').show();
            }
            //recaptcha passed validation
            else {
                $('#html_element').hide();
            }
            if (e.isDefaultPrevented()) {
                return false;
            } else {
                return true;
            }
        }
        else {
            return true;
        }
    });

    $(".directoryFilterMenu").each(function () {
        if ($(this).find("#boxView").hasClass("active")) {
            $("#listView").removeClass("active");
            $(".dashboardOptions ul").each(function (i) {
                $(this).addClass('dashboardList');
                $(this).removeClass('dashboardListView');
            });
        }
        else if ($(this).find("#listView").hasClass("active")) {
            $("#boxView").removeClass("active");
            $(".dashboardOptions ul").each(function (i) {
                $(this).removeClass('dashboardList');
                $(this).addClass('dashboardListView');
            });
        }
    });

    $("#boxView").click(function () {
        $(this).addClass("active");
        $("#listView").removeClass("active");
        $(".dashboardOptions ul").each(function (i) {
            $(this).addClass('dashboardList');
            $(this).removeClass('dashboardListView');
        });
    });

    $("#listView").click(function () {
        $(this).addClass("active");
        $("#boxView").removeClass("active");
        $(".dashboardOptions ul").each(function (i) {
            $(this).removeClass('dashboardList');
            $(this).addClass('dashboardListView');
        });
    });

    $(".expandAll").click(function () {
        $(this).parent().parent().find(".toggleSection").each(function () {
            $(this).addClass("expanded");
            $(this).find(".toggleContent").css("display", "block");
        })
    });

    $(".collapseAll").click(function () {
        $(this).parent().parent().find(".toggleSection").each(function () {
            $(this).removeClass("expanded");
            $(this).find(".toggleContent").css("display", "none");
        })
    });

    adjustToolBarButtons();

    $("#submitButton").click(function () {
        var startDate = $("#SearchConfirmDateFrom")[0];

        if (startDate != undefined) {
            var startDateValue = $("#SearchConfirmDateFrom")[0].value.replace(/\//g, "");
            var endDateValue = $("#SearchConfirmDateTo")[0].value.replace(/\//g, "");

            if (startDateValue != "" || endDateValue != "") {
                link = link + "&SearchDateFrom=" + startDateValue + "&SearchDateTo=" + endDateValue;
            }

            window.location.href = link;
        }

    })

    $('#nav li').hover(function () {
        $(this).find("ul.main-sub-menu").toggleClass('initial-hide');
    });

    $('ul.sysConfigDashboard li div').click(function () {
        var tabsIndex = $(this).attr('id');

        $('ul.sysConfigDashboard li').each(function () {
            if ($(this).hasClass('active')) {
                $(this).removeClass('active');
            }
        });

        $('div#configInfoWrapper div.sub-wrapper').each(function () {
            if (!$(this).hasClass('initial-hide')) {
                $(this).addClass('initial-hide');
            }
        });

        if (!$(this).parent('li').hasClass('active')) {
            $(this).parent('li').addClass('active');
        }

        $('div#configInfoWrapper div[data-tab=' + tabsIndex + ']').removeClass('initial-hide');

    });

});

$(window).on('resize load', function () {
    var height = $("#footer").height() + 60;
    var navContainer = $("#navContainer")[0];
    var logoContainer = $("div.logoContainer");
    var topNavHeight = $("#topNavContainer").height();
    var navHeight = $("#navContainer .navContainer").height();
    var totalHeight = topNavHeight + navHeight + 100;
    if (navContainer != undefined) {
        if (totalHeight >= navContainer.scrollHeight) {
            if (!logoContainer.hasClass("scroll-logoContainer")) {
                logoContainer.removeClass("no-scroll-logoContainer");
                logoContainer.addClass("scroll-logoContainer");
            }

        } else {
            if (!logoContainer.hasClass("no-scroll-logoContainer")) {
                logoContainer.removeClass("scroll-logoContainer");
                logoContainer.addClass("no-scroll-logoContainer");
            }
        }
    }

    var nav = $(".navContainer").find("ul");
    var form = $("form");
    if (nav.hasClass("publicnav")) {
        if (!$("navContainer").hasClass("publicNavContainer")) {
            $("#navContainer").addClass("publicNavContainer");
        }
    }

    if (form.hasClass("public-styled-form")) {
        if (!$("#contentWrapper").hasClass("public-styled-form")) {
            $("#contentWrapper").addClass("public-styled-wrapper");
        }
    }

    var grid = $(".k-grid");

    if (grid != undefined) {
        grid.addClass("table-responsive");
    }
    handlePagerVisibility();
    //$('.announcementsSlider').slick({
    //    dots: true,
    //    infinite: false,
    //    speed: 300,
    //    slidesToShow: 1,
    //    adaptiveHeight: true,
    //    prevArrow: '<button id="leftButton" type="button" class="sliderNavButton"><i class="fas fa-chevron-left"></i></button>',
    //    nextArrow: '<button id="rightButton" type="button" class="sliderNavButton"><i class="fas fa-chevron-right"></i></button>'
    //});
});

function createCookie(name, value, hours) {
    var expires = "";
    if (hours) {
        var date = new Date();
        date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
        expires = "; expired=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(";");
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

function delCookie(name) {
    createCookie(name, "", -5);
}

//function selectAllText(textbox) {
//    textbox.focus();
//    textbox.select();
//}

function copyToClipboard(button, showLink = true) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val(button.value).select();
    document.execCommand("copy");
    $temp.remove();
    button.innerHTML = "Copied";

    setTimeout(function () {
        if (showLink) {
            button.innerHTML = "<i class=\"bi bi-link\"></i>";
        }
        else {
            button.innerHTML = "Copy Link";
        }
    }, 2000);
}

function removeURLParameter(url, parameter) {
    //prefer to use l.search if you have a location/link object
    var urlparts = url.split('?');
    if (urlparts.length >= 2) {

        var prefix = encodeURIComponent(parameter) + '=';
        var pars = urlparts[1].split(/[&;]/g);

        //reverse iteration as may be destructive
        for (var i = pars.length; i-- > 0;) {
            //idiom for string.startsWith
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                pars.splice(i, 1);
            }
        }

        url = urlparts[0] + '?' + pars.join('&');
        return url;
    } else {
        return url;
    }
}

function GetParameterValues(param) {
    var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < url.length; i++) {
        var urlparam = url[i].split('=');
        if (urlparam[0] == param) {
            return urlparam[1];
        }
    }
}

var isStaging = false;
var pathnameIfStaging = window.location.pathname;
var firstPath = pathnameIfStaging.split("/");

if (firstPath[1].indexOf("staging") != -1)
    isStaging = true;

var fullSitePath = "";

if (isStaging)
    fullSitePath = window.location.origin + "/" + firstPath[1];
else
    fullSitePath = window.location.origin;
var worker = new Worker(fullSitePath + '/scripts/timer-worker.js')

var workerTimer = {
    id: 0,
    callbacks: {},
    setInterval: function (cb, interval, context) {
        this.id++
        var id = this.id
        this.callbacks[id] = { fn: cb, context: context }
        worker.postMessage({
            command: 'interval:start',
            interval: interval,
            id: id
        })
        return id
    },
    onMessage: function (e) {
        switch (e.data.message) {
            case 'interval:tick':
                var callback = this.callbacks[e.data.id]
                if (callback && callback.fn) callback.fn.apply(callback.context)
                break
            case 'interval:cleared':
                delete this.callbacks[e.data.id]
                break
        }
    },
    clearInterval: function (id) {
        worker.postMessage({ command: 'interval:clear', id: id })
    }
}
worker.onmessage = workerTimer.onMessage.bind(workerTimer);
var initialCounter = 1;
function startTick(currentSeconds, secondsCounter, lessonMinTime, currentLessonId, currentRegistrationId, clearValues, lessonMaxTime) {
    var onlineTrainingSubmissionPage = document.getElementById('currentSecond') !== null;
    if (onlineTrainingSubmissionPage) {
        if (currentSeconds > 60) {
            document.getElementById('currentSecond').innerText = formatNumber(currentSeconds % 60, true);
        }
        else {
            document.getElementById('currentSecond').innerText = formatNumber(currentSeconds, true);
        }
        document.getElementById('currentMinute').innerText = formatNumber(parseInt(currentSeconds / 60), false);
        var minimumSeconds = lessonMinTime * 60;
    }

    var _tick = workerTimer.setInterval(function () {
        var currentUrl = (window.location.href).toLowerCase();
        var stopCounter = readCookie("stopCounter");
        if ((currentUrl.indexOf('onlinetraining/submission') == -1 && currentUrl.indexOf('quiz/submission') == -1 &&
            currentUrl.indexOf('discussionpost') == -1) || stopCounter == "true") {
            delCookie("currentSecondValue");
            delCookie("currentRegistrationId");
            delCookie("currentLessonId");
            delCookie("currentLaunchId");
            delCookie("resetLessonTimer");
            clearInterval(_tick);
            delCookie("stopCounter");
            currentSeconds = 0;
        }

        if (idleTime <= 0 || idleTime <= (lessonMaxTime - 3) * 60) {
            currentSeconds = currentSeconds + 1;
            secondsCounter = secondsCounter + 1;
        }

        if (onlineTrainingSubmissionPage) {
            if (currentSeconds == minimumSeconds || initialCounter == 1) {
                ShowHideQuiz();
            }
            initialCounter += 1;
            if (currentSeconds < minimumSeconds) {
                $("#divMinimumTime").css("display", "block");
                $(".Lesson-Quiz-" + currentLessonId).css("display", "none");
            }
        }
        createCookie("currentSecondValue", currentSeconds, 3);
        createCookie("currentLessonId", currentLessonId, 3);
        createCookie("currentRegistrationId", currentRegistrationId, 3);

        if (onlineTrainingSubmissionPage) {
            if (currentSeconds > 60) {
                document.getElementById('currentSecond').innerText = formatNumber(currentSeconds % 60, true);
            }
            else {
                document.getElementById('currentSecond').innerText = formatNumber(currentSeconds, true);
            }
            document.getElementById('currentMinute').innerText = formatNumber(parseInt(currentSeconds / 60), false);

            if (secondsCounter == 59)
                secondsCounter = 0;
        }
    }, 1000);
}

function refreshPage(position) {
    if (position != undefined) {
        var url = removeURLParameter(window.location.href, 'page_y');

        if (url.indexOf("?") >= 0)
            window.location.href = url + '&page_y=' + position;
        else
            window.location.href = url + "?&page_y=" + position;
    }
    else {
        window.location.href = window.location.href;
    }
}

function ScrollToResult(position) {
    $("html, body").animate({
        scrollTop: position
    }, 'slow');
}

function DateFilter(args) {
    args.element.kendoDatePicker({
    })
}

function DateTimeFilter(args) {
    args.element.kendoDateTimePicker({
        timeFormat: "HH:mm tt",
        interval: 15
    })
}
window.onload = function () {
    if (window.location.href.indexOf('page_y') != -1) {
        var match = GetParameterValues('page_y');
        ScrollToResult(match);
    }
}

$(function () {
    $('.numbersOnly').keyup(function () {
        if (this.value == "") {
            this.value = '';
        }
        else if (this.value != this.value.replace(/[^0-9\.]/g, '')) {
            this.value = this.value.replace(/[^0-9\.]/g, '');
        }
    });
    $('.wholeNumbersOnly').on("keypress keyup paste", function (event) {
        var that = this;
        if (event.type === "paste") {
            setTimeout(function () {
                $(that).val($(that).val().replace(/[^\d].+/, ""));
            }, 100);
        } else {

            if (event.which === 46) {
                alert("Please input only whole numbers");
                event.preventDefault();
            } else {
                $(this).val($(this).val().replace(/[^\d]+/, ""));
            }
        }
    });
    $('.positiveNegativeNumbers').keypress(function (event) {
        if (
            event.target.value.length === 0 && (event.code === 'Minus' || event.code === 'NumpadSubtract')
            || ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].includes(event.key)
            || (event.code === 'Period' || event.code === 'NumpadDecimal') && event.target.value.indexOf('.') === -1
        ) {
            return;
        } else {
            if (event.code === 'Minus' || event.code === 'NumpadSubtract') {
                let numericValue = parseFloat("-" + event.target.value)
                if (!isNaN(numericValue)) {
                    return;
                }
            }
            event.preventDefault();
        }

    });

    $('.integerOnly').keyup(function () {
        if (this.value != this.value.replace(/[^0-9]/g, '')) {
            this.value = this.value.replace(/[^0-9]/g, '');
        }
    });

    $('.alphabetOnly').keyup(function () {
        if (this.value != this.value.replace(/[^a-z A-Z ]/g, '')) {
            this.value = this.value.replace(/[^a-z A-Z ]/g, '');
        }
    });

    $('.alphabetNumericOnly').keyup(function () {
        if (this.value != this.value.replace(/[^a-zA-Z0-9]/g, '')) {
            this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
        }
    });

    $("input.hourNumbers").keypress(function (event) {
        return keyRestrict(event, '1234567890.');
    }).keyup(function (event) {
        $(this).val(convertToRoundedDecimal($(this).val()));
    }).blur(function (event) {
        $(this).val(convertToRoundedDecimal($(this).val()));
    });

    function convertToRoundedDecimal(val) {
        return val.replace(/[.][1346890]/g, '.').replace(/[.][2][012346789.]/g, '.25').replace(/[.][7][012346789.]/g, '.75').replace(/[.][5][0-9.]/g, '.5').replace(/[.][2][5][0-9.]/g, '.25').replace(/[.][7][5][0-9.]/g, '.75').replace(/[.][.]/g, '.');
    }

    function keyRestrict(e, validchars) {
        var key = '', keychar = '';
        key = getKeyCode(e);
        if (key == null)
            return true;

        keychar = String.fromCharCode(key);
        keychar = keychar.toLowerCase();
        validchars = validchars.toLowerCase();

        if (validchars.indexOf(keychar) != -1)
            return true;
        if (key == null || key == 0 || key == 8 || key == 9 || key == 13 || key == 27)
            return true;
        return false;
    }

    function getKeyCode(e) {
        if (window.event)
            return window.event.keyCode;
        else if (e)
            return e.which;
        else
            return null;
    }
});

$(document).on('click', '.directoryQuickList a', function (e) {
    if ($("#rangeConfirmationBtn").length) {
        var startDateValue = $("#SearchDateFromQuickOption")[0].value.replace(/\//g, "");
        var endDateValue = $("#SearchDateToQuickOption")[0].value.replace(/\//g, "");
        var trainingTypeValue = "";

        if ($("#SearchTrainingTypeQuickOption")[0] != undefined) {
            trainingTypeValue = $("#SearchTrainingTypeQuickOption")[0].value;
        }

        e.preventDefault();
        if ((startDateValue != "" && startDateValue != "monthdayyear") || (endDateValue != "" && endDateValue != "monthdayyear")) {
            link = $(this)[0].href + "&SearchDateFrom=" + startDateValue + "&SearchDateTo=" + endDateValue;
            if (trainingTypeValue != '')
                link = link + "&trainingtype=" + trainingTypeValue;
            window.location.href = link;
        }
        else {
            link = $(this)[0].href;
            $("#rangeConfirmationBtn").click();
            if (trainingTypeValue != '')
                link = link + "&trainingtype=" + trainingTypeValue;
        }
    }
});

function parseJsonDate(jsonDateString) {
    if (jsonDateString != undefined)
        return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}

function dateCheck(from, to, check) {

    var fDate, lDate, cDate;
    fDate = Date.parse(from);
    lDate = Date.parse(to);
    cDate = Date.parse(check);

    if ((cDate <= lDate && cDate >= fDate)) {
        return true;
    }
    return false;
}

function validateActivitySearchQuickEndDate(e) {
    var activityEndDatePicker = $("#SearchDateToQuickOption").data("kendoDatePicker"), startDate = this.value();

    if (startDate) {
        startDate = new Date(startDate);
        startDate.setDate(startDate.getDate());
        activityEndDatePicker.min(startDate);
    }
}

function validateConfirmationSearchConfirmDateTo(e) {
    var endDatePicker = $("#SearchConfirmDateTo").data("kendoDatePicker"), startDate = this.value();

    if (startDate) {
        startDate = new Date(startDate);
        startDate.setDate(startDate.getDate());
        endDatePicker.min(startDate);
    }
}

equalheight = function (container, checkMobile) {

    if (typeof checkMobile == 'undefined') {
        checkMobile = true;
    }

    if ($('.mobile').css('display') == 'none' || checkMobile == false) {

        var currentTallest = 0,
            $el;

        $(container).each(function () {
            $el = $(this);
            $($el).height('auto')
            currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
        });

        $(container).each(function () {
            $(this).height(currentTallest);
        });

    } else {
        $(container).each(function () {
            $(this).height('auto');
        });
    }

}

/* use match height script */
$(window).on('resize load', function () {
    equalheight(".dashboardList > li", false);
    equalheight("#recentlyAddedTAReports > li", false);
    equalheight("#recentPendingTAReports > li", false);
});
equalheight(".dashboardList > li", false);
equalheight("#recentlyAddedTAReports > li", false);
equalheight("#recentPendingTAReports > li", false);
function printFunction() {
    window.print();
    return false;
}
$(window).on('beforeprint', function (event) {
    event.preventDefault(); // Prevent default action
});
function adjustToolBarButtons() {
    $('.k-editor-toolbar').each(function () {
        $(this).find('*').attr("tabindex", -1);
    });
}

//$(function () {
//    $("input[type=text]").on("focus", function () {
//        var input = $(this);
//        clearTimeout(input.data("selectTimeId"));

//        var selectTimeId = setTimeout(function () {
//            input.select();
//            input[0].setSelectionRange(0, 9999);
//        });

//        input.data("selectTimeId", selectTimeId);
//    }).blur(function (e) {
//        clearTimeout($(this).data("selectTimeId"));
//    });
//})

function onExcelExport(e) {
    var sheet = e.workbook.sheets[0];
    var dataArray = [];
    var startIndex = 0;
    var headerRow = sheet.rows[0];
    var noteColumn = -1;
    var executiveColumn = -1;
 
    for (var columnIndex = 0; columnIndex < sheet.columns.length; columnIndex++) {
        sheet.columns[columnIndex].width = 500;
        sheet.columns[columnIndex].autoWidth = false;
        if (headerRow.cells[columnIndex].value == 'Staff Notes' || headerRow.cells[columnIndex].value == 'Notes') {
            noteColumn = columnIndex;
        }
        if (headerRow.cells[columnIndex].value == 'Executive Summary') {
            executiveColumn = columnIndex;
        }
    }
    for (var rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
        var newArrIndex = rowIndex;
        if (startIndex >= newArrIndex) {
            newArrIndex = startIndex + 1;
        }
        var arrIndex = startIndex - 1;
        var row = sheet.rows[rowIndex];
        var pass = 1;
        var cellValue = "";
        for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
            var cell = row.cells[cellIndex];
            if (cell.value != null) {
                var splitString = cell.value.toString().split(" ");
                for (var i = 0; i < splitString.length; i++) {
                    cellValue += splitString[i];
                }
            }
            if ((cell.background != undefined && cell.background != null) || (cell.value != undefined && cell.value != null && cellValue != "")) {
                if (cell.value != undefined && cell.value.toString().indexOf("GMT") > -1) {
                    var newDate = new Date(cell.value);
                    var cells = [];
                    cell.value = newDate;
                    cell.format = "MM/dd/yyyy";
                    if (cellIndex == 0) {
                        cells[cellIndex] = { value: newDate, format: "MM/dd/yyyy", wrap: true, verticalAlign: 'top' };
                        dataArray.splice(startIndex, 0, { type: "data", cells: cells });
                        arrIndex = startIndex;
                    }
                    else {
                        cells = { value: newDate, format: "MM/dd/yyyy", wrap: true, verticalAlign: 'top' };
                        dataArray[newArrIndex - 1].cells.splice(cellIndex, 1, cells);
                    }
                }
                else {
                    var val = cell.value;
                    var cells = [];
                    if (isNaN(val)) {
                        if (val != undefined) {
                            val = formatCellValue(val);
                        }
                        else {
                            val = "";
                        }
                        cells[cellIndex] = { value: val, wrap: true, verticalAlign: 'top' };
                        if (cellIndex == 0) {
                            dataArray.splice(startIndex, 0, { type: "data", cells: cells });
                            arrIndex = startIndex;
                        }
                        else {
                            cells = { value: val, wrap: true, verticalAlign: 'top' };
                            dataArray[newArrIndex - 1].cells.splice(cellIndex, 1, cells);
                        }
                    }
                    else {
                        if (val && (val.toString().indexOf("<br />") >= 0 || val.toString().indexOf("<br/>") >= 0 || val.toString().indexOf("<br>") >= 0)) {
                            val = val.replaceAll("<br />", "\n").replaceAll("<br/>", "\n").replaceAll("<br>", "\n");
                        }
                        val = formatCellValue(val.toString());
                        if (val === true || val === false) {
                            if (cellIndex == 0) {
                                cells[cellIndex] = { value: val, wrap: true };
                                dataArray.splice(startIndex, 0, { type: "data", cells: cells });
                                arrIndex = startIndex;
                            }
                            else {
                                cells = { value: val, wrap: true, verticalAlign: 'top' };
                                dataArray[newArrIndex - 1].cells.splice(cellIndex, 1, cells);
                            }
                        }
                        else {
                            if ((val) % 1 != 0) {
                                if (cellIndex == 0) {
                                    cells[cellIndex] = !isNaN(parseFloat(val)) ? { value: parseFloat(val), wrap: true, verticalAlign: 'top' } : { value: "", wrap: true, verticalAlign: 'top' };
                                    dataArray.splice(startIndex, 0, { type: "data", cells: cells });
                                    arrIndex = startIndex;
                                }
                                else {
                                    cells = !isNaN(parseFloat(val)) ? { value: parseFloat(val), wrap: true, verticalAlign: 'top' } : { value: "", wrap: true, verticalAlign: 'top' };
                                    dataArray[newArrIndex - 1].cells.splice(cellIndex, 1, cells);
                                }
                            }
                            else {
                                if (cellIndex == 0) {
                                    cells[cellIndex] = !isNaN(parseInt(val)) ? { value: parseInt(val), wrap: true, verticalAlign: 'top' } : { value: "", wrap: true };
                                    dataArray.splice(startIndex, 0, { type: "data", cells: cells });
                                    arrIndex = startIndex;
                                }
                                else {
                                    cells = !isNaN(parseInt(val)) ? { value: parseInt(val), wrap: true } : { value: "", wrap: true, verticalAlign: 'top' };
                                    dataArray[newArrIndex - 1].cells.splice(cellIndex, 1, cells);
                                }
                            }
                        }
                    }
                }
            }
            else {
                var cells = [];
                var newValue = "";
                cell.value = newValue;
                if (cellIndex == 0) {
                    cells[cellIndex] = { value: newValue, wrap: true, verticalAlign: 'top' };
                    dataArray.splice(startIndex, 0, { type: "data", cells: cells });
                    arrIndex = startIndex;
                }
                else {
                    cells = { value: newValue, wrap: true, verticalAlign: 'top' };
                    dataArray[newArrIndex - 1].cells.splice(cellIndex, 1, cells);
                }
            }
            startIndex = dataArray.length;
        }
    }
    insertArrayAt(sheet.rows, 1, dataArray);
}

function formatCellValue(value) {
    // Replace <br> tags with line breaks
    value = value.replaceAll("<br />", "\n").replaceAll("<br/>", "\n").replaceAll("<br>", "\n");

    // Replace <p> tags with line breaks
    value = value.replace(new RegExp('</?p>', 'g'), '\n');

    // Replace <ul> and <li> tags with dashes and line breaks
    value = value.replace(new RegExp('</?ul>|</?li>', 'g'), '- ');

    // Handle <a> tags
    value = value.replace(/<a\s+[^>]*href="([^"]*)"[^>]*>(.*?)<\/a>/g, (match, p1, p2) => {
        return `${p2} (Link: ${p1})`;
    });

    // Replace <img> tags with link text
    value = value.replace(/<img\s+[^>]*src="([^"]*)"[^>]*>/g, (match, p1) => {
        return `(Link: ${p1})`;
    });

    // Remove any other HTML tags
    value = value.replace(new RegExp('<[^>]*>', 'g'), '');

    // Remove any remaining &nbsp; entities
    value = value.replace(/&nbsp;/g, ' ');

    return value.trim();
}

function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [1, arrayToInsert.length].concat(arrayToInsert));
}

function replaceAll(str, term, replacement) {
    return str.replace(new RegExp(escapeRegExp(term), 'g'), replacement);
}
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function onPdfExport(e) {
    var grid = e.sender;
    var gridColumns = e.sender.columns;
    $(".k-filter-row").hide();
    $(".k-icon.k-i-more-vertical").hide();
    for (var i = 0; i < gridColumns.length; i++) {
        if (gridColumns[i].title == undefined) {
            grid.hideColumn(grid.columns[i]);
        }
    }
    setTimeout(function () {
        for (var i = 0; i < gridColumns.length; i++) {
            if (gridColumns[i].title == undefined) {
                grid.showColumn(grid.columns[i]);
            }
        }
        $(".k-filter-row").show();
        $(".k-icon.k-i-more-vertical").show();
    }, 5000);
}

var insertImage = kendo.ui.editor.ImageCommand.fn.insertImage;
kendo.ui.editor.ImageCommand.fn.insertImage = function (img, range) {
    var imgsrc = this.attributes.src;
    var isStaging = false;
    var pathnameIfStaging = window.location.pathname;
    var firstPath = pathnameIfStaging.split("/");

    if (firstPath[1].indexOf("staging") != -1)
        isStaging = true;

    var fullImgSrc = "";

    if (isStaging)
        fullImgSrc = window.location.origin + "/" + firstPath[1] + imgsrc;
    else
        fullImgSrc = window.location.origin + imgsrc;

    insertImage.call(this, img, range);

    var images = range.startContainer.getElementsByTagName("img");
    for (var i = 0; i < images.length; i++) {
        if (images[i].attributes.src.value == imgsrc) {
            images[i].setAttribute("src", fullImgSrc);
        }
    }
}

var insertFile = kendo.ui.editor.FileCommand.fn.insertFile;
kendo.ui.editor.FileCommand.fn.insertFile = function (file, range) {
    var fileSrc = this.attributes.href;
    var isStaging = false;
    var pathnameIfStaging = window.location.pathname;
    var firstPath = pathnameIfStaging.split("/");

    if (firstPath[1].indexOf("staging") != -1)
        isStaging = true;

    var fullFileSrc = "";

    if (isStaging)
        fullFileSrc = window.location.origin + "/" + firstPath[1] + fileSrc;
    else
        fullFileSrc = window.location.origin + fileSrc;

    insertFile.call(this, file, range);

    var aTag = range.startContainer.getElementsByTagName("a");

    for (var i = 0; i < aTag.length; i++) {
        aTag[i].attributes.href.value = fullFileSrc;
    }
}


// adds required attribute rule to inputs
// which validates the form when we call form.valid() before submitting form programatically
// param { elements } has elements
function checkFormValid(elements) {

    $.each(elements, function (key, val) {

        let targetElement = $("#" + val.id);
        targetElement.rules("add", {
            required: true
        });
    });

    $.each(elements, function (key, val) {

        if ($(val).val() == '') {
            scrollToTarget(val.id);

            return false;
        }
    });
}

$(document).ready(function () {
    $(document).on('mouseover', '.k-file-preview', function () {
        var fileName = $(this).next('.k-file-name').text();
        $(this).attr('title', fileName);
    });
    $(document).on('mouseout', '.k-file-preview', function () {
        $(this).removeAttr('title');
    });
});

function scrollToTarget(elementId) {

    const targetElement = $("#" + elementId);

    if (targetElement.css('display') === 'none') {
        return;
    }

    // Scroll to the target element
    $('html, body').animate({

        scrollTop: targetElement.offset().top - 200

    });

    targetElement.focus();
}
;
