/* Minification failed. Returning unminified contents.
(1183,37-38): run-time error JS1195: Expected expression: >
(1263,14-15): run-time error JS1195: Expected expression: )
(1264,9-10): run-time error JS1002: Syntax error: }
(1265,44-45): run-time error JS1195: Expected expression: )
(1265,46-47): run-time error JS1004: Expected ';': {
(1301,10-11): run-time error JS1195: Expected expression: ,
(1304,43-44): run-time error JS1004: Expected ';': {
(1314,10-11): run-time error JS1195: Expected expression: ,
(1315,42-43): run-time error JS1195: Expected expression: )
(1315,44-45): run-time error JS1004: Expected ';': {
(1417,10-11): run-time error JS1195: Expected expression: ,
(1421,36-37): run-time error JS1195: Expected expression: )
(1421,38-39): run-time error JS1004: Expected ';': {
(1429,5-16): run-time error JS1018: 'return' statement outside of function: return this
(1312,17-29): run-time error JS1018: 'return' statement outside of function: return false
 */
$(document).ready(function () {
    NCJTC.site.initializeSearchAutocomplete();
    NCJTC.site.initializeDropdowns();
    NCJTC.site.initializeMoreAndLessButtons();
    NCJTC.site.delayedAccessibilityFixes();
    NCJTC.markdown.processMarkdown(".ncjtc-markdown");
    NCJTC.site.processSiteMessage();
    NCJTC.site.shortenTitle();
    NCJTC.site.wireUpAnalyticsEvents();
    Common.intializeTrimming();
});

var placeSearch, agencyAddressAutocomplete;
var componentFormConfig = {
    country: 'short_name',
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'short_name',
    postal_code: 'short_name',
    postal_town: 'long_name',
    administrative_area_level_2: 'short_name',
    sublocality_level_1: 'long_name'
};

var NCJTC = {
    site:
    {
        signOut: function (cookieSignOutUrl) {
            window.top.open(cookieSignOutUrl, "SignOutWindow");

            setTimeout(function () {

                window.location.href = window.location.origin + "/SignIn";
            }, 500);
        },
        showPleasWait: function () {
            $("#loading-id").foundation("open");
        },
        hidePleasWait: function () {
            $("#loading-id").foundation("close");
        },
        continueImpersonation: function (fvtcId, userName) {

            $.ajax({
                url: '/ContinueImpersonation',
                dataType: "html",
                data: {
                    fvtcId: fvtcId,
                    userName: userName
                },
                type: "POST",
                success: function (result) {
                    if (result === "true") {
                        window.location.reload();
                    } else {
                        console.error("Error continuing impersonation");

                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.error(errorThrown);

                }
            });

        },
        checkAccessibleAction: function (evt) {
            var continueAction = false;

            if (evt instanceof KeyboardEvent) {
                var keyCode = evt.which || evt.keyCode;

                if (keyCode === 0 || keyCode === 32 || keyCode === 13) {
                    continueAction = true;
                }
            } else {
                continueAction = true;
            }

            return continueAction;
        },
        // Space key is a space code is 'Space'
        // Enter key & code is 'Enter'
        // For things that normally don't get tab focus
        // And a tags without HREFs
        checkForKeyboardClick: function (evt) {
            var isKeyboardClick = false;

            if (evt instanceof KeyboardEvent) {
                var key = evt.code || evt.key;

                // Chrome: Space, NumpadEnter, Enter
                // IE: Spacebar, NumpadEnter, Enter
                if (key.indexOf('Space') !== -1 || key.indexOf('Enter') !== -1) {
                    isKeyboardClick = true;
                    if (key.indexOf('Space') !== -1) {
                        evt.preventDefault();
                    }
                }
            } else {
                isKeyboardClick = true;
            }

            return isKeyboardClick;
        },
        showSearch: function (showAnimation, event) {

            if (NCJTC.site.checkForKeyboardClick(event)) {

                var siteSearchSection = $("#siteSearch-id");
                var siteSearchTrigger = $(".nav-search > a");
                var siteSearchInput = $("#training-search-text-id");
                if (showAnimation !== undefined && showAnimation === true) {

                    $(siteSearchSection).slideToggle();
                } else {
                    $(siteSearchSection).show();
                }


                $(siteSearchTrigger).toggleClass("activeSearch");

                if ($(siteSearchTrigger).hasClass("activeSearch")) {
                    setTimeout(function () {
                        $(siteSearchInput).focus();
                    }, 300);
                } else {
                    $(siteSearchInput).blur();
                }
            }
            if (event instanceof KeyboardEvent) {
                var key = event.code || event.key;

                if (key !== 'Tab') {
                    event.preventDefault();
                    return false;
                }
            }
        },
        searchByTerms: function (event, anchor) {

            if (NCJTC.site.checkForKeyboardClick(event)) {
                event.preventDefault();

                var form = $(event.currentTarget);

                if (!form.is("form")) {
                    form = $(event.currentTarget).closest("form");
                }

                var terms = $("input:text", form).val();

                if (anchor !== undefined) {
                    terms += "#" + anchor;
                }

                var contentType = $("#content").val();
                var contentTypeParam = "";

                if (contentType !== undefined) {
                    contentTypeParam = "&content=" + contentType;
                }

                $.ajax(
                    {
                        type: 'GET',
                        url: "/search-url?terms=" + terms + contentTypeParam,
                        success: function (data) {
                            var url = data;

                            setTimeout(function () {
                                window.location.href = url;
                            }, 500);
                        },
                        beforeSend: function () {
                            $("#progress-id").show();
                            $("input:text", form).blur();
                        },
                        complete: function () {

                        },
                        error: function () {
                            console.debug("Error while retrieving search result url endpoint!");
                            $("#progress-id").hide();
                        }
                    });
            }

            if (event instanceof KeyboardEvent) {
                var key = event.code || event.key;

                if (key !== 'Tab') {
                    event.preventDefault();
                    return false;
                }
            }
        },
        fixSliderAccessibility: function () {
            $(".slick-slider [aria-selected]").removeAttr("aria-selected");
            $(".slick-slider [aria-controls]").removeAttr("aria-controls");
            $(".slick-slider [aria-describedby]").removeAttr("aria-describedby");
            $(".slick-track").attr("aria-label", "Other Trainings");
        },
        initializeDropdowns: function () {
            $('.ui.dropdown').dropdown();
            $('.tag.example .ui.dropdown')
                .dropdown({
                    allowAdditions: true
                });
        },
        animateModal: function (elem) {
            var currentElem = $(elem).data("animate");
            $("#" + currentElem).css({ "top": "100px", 'opacity': '0', 'display': 'block', " visibility": "visible" });
            $("#" + currentElem).css({ 'opacity': '0', 'display': 'block' }).animate({ 'opacity': '1', 'top': '145px' }, 500);
        },
        sendCatalogRequest: function (element, actionUrl, incompleteProfile) {
            $("[id^='requestCatalogAccess-id']").prop('disabled', true).addClass("disabled");

            $.ajax({
                cache: false,
                url: actionUrl,
                dataType: "html",
                type: "POST",
                success: function () {
                    if (incompleteProfile === "true") {
                        $("#registrationPreviousStep").addClass("hide");
                        $("[id$='accountAddOrganization']").each(function (idx, elem) {
                            $(elem).removeClass("hidden");
                        });
                        $("[id$='registrationAddOrganization']").each(function (idx, elem) {
                            $(elem).addClass("hidden");
                        });
                        NCJTCOrganization.firstQuestion("AddOrganizationModal");
                    } else {
                        NCJTC.site.animateModal(element);

                        $("#modProtectedContentRequestSent").foundation("open");

                        $("[id^='callToActionButton']").addClass("hidden");
                        $("[id^='callToActionButton']").addClass("hide");
                        $("[id^='pendingApprovalButton']").removeClass("hidden");
                        $("[id^='pendingApprovalButton']").removeClass("hide");
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $("[id^='requestCatalogAccess-id']").prop('disabled', false).removeClass("disabled");
                }
            });
        },
        shortenTitle: function (elem) {
            $(".shortTitle").each(function () {
                var titleCharacterCount = $(this).text().length;

                if (titleCharacterCount > 45) {
                    var extra = $(this).text().substring(0, titleCharacterCount);

                    var shortened = $(this).text().substring(0, 45) + '<span>...</span>';
                    $(this).attr("data-tooltip", "");
                    $(this).attr("title", extra);
                    $(this).html(shortened);

                }
                $(this).removeClass("hide");
            });
        },
        delayedAccessibilityFixes: function () {
            setTimeout(function () {
                $("#g-recaptcha-response").attr("aria-label", "captcha");
                $("iframe[src^='https://platform.twitter.com']").attr("title", "Twitter Frame");
                $("iframe[src^='https://www.recaptcha.net/recaptcha']").attr("title", "Google Captcha");
            }, 250);
        },
        closeSiteMessage: function () {
            //Set cookie 1 day out.
            NCJTC.site.cookies.setCookie("ncjtc_site_banner", "1", "1");
        },
        animateProgressBar: function () {

            var percent = $("#hidCompPercent-id").val();
            var progress = $("#progress-meter-id");

            if ($(progress).width() < percent && percent !== '100') {
                //Animate progress bar
                $(progress).animate({
                    width: percent + '%'
                });

                //Animate counter for percentage
                $('.counter').each(function () {
                    var $this = $(this),
                        countTo = $this.attr('data-count');

                    $({ countNum: $this.text() }).animate({
                        countNum: countTo
                    },
                        {
                            duration: 500,
                            step: function () {
                                $this.text(Math.ceil(this.countNum) + "%");
                            },
                            complete: function () {
                                $this.text(this.countNum + "%");
                            }
                        });
                });
            }
        },
        processSiteMessage: function () {
            var getSiteBannerCookie = NCJTC.site.cookies.getCookie("ncjtc_site_banner");
            if (getSiteBannerCookie !== "") {
                $("#l-header-msg").hide();
            }
        },
        clickMoreInfoLink: function (event, isTargetBlank) {
            var elem = event.currentTarget;
            var moreInfoLink = $("a.button", $(elem).closest(".pod"));

            if ($(moreInfoLink).attr("href")) {
                if (isTargetBlank) {
                    window.open($(moreInfoLink).attr("href"), '_blank');
                } else {
                    window.location.href = $(moreInfoLink).attr("href");
                }
            }
        },
        openRequestForm: function (actionUrl, isGenericForm, event) {
            if (NCJTC.site.checkForKeyboardClick(event)) {
                if (isGenericForm) {
                    NCJTC.site.openGenericRequestForm(actionUrl, event);
                } else {
                    NCJTC.site.openSpecificRequestForm(actionUrl, event);
                }
            }
        },
        openListServReqestForm: function (actionUrl, programName, event) {
            if (NCJTC.site.checkForKeyboardClick(event)) {
                if (typeof event !== "undefined") {
                    event.preventDefault();
                }

                $(window).scrollTop(0);

                $("#modRequestListServForm").foundation("open");
                $("#list-serv-dynamics-error-id").hide();

                var htmlId = "#request-listserv-form-container";

                $(htmlId).empty();
                $("#list-serv-pleasewait-id").show();
                $("#request-training-form-data").hide();

                $.ajax({
                    cache: false,
                    url: actionUrl + "?program=" + programName,
                    type: "GET",
                    success: function (data) {
                        $("#list-serv-pleasewait-id").hide();
                        $("#request-listserv-form-data").show();

                        //Show request form partial view
                        $(htmlId).html(data).hide().slideDown(150);

                        $("#modRequestListServForm input:text:first").focus();

                        //Anything changed here needs to be change in contactus.js
                        $("#RequestFormProgram").val("");
                        $("#RequestFormContactName").val("");
                        $("#RequestFormContactEmail").val("");

                        var url = window.location.href;
                        $("#RequestListServFormUrl").val(url);

                        NCJTC.site.initializeAgencySearchAutocomplete();

                        var form = $("#requestListServForm");

                        $(form).data('validator', null);
                        $.validator.unobtrusive.parse($(form));
                        grecaptcha.reset();

                        NCJTC.site.initializeAgencyAddressAutocomplete();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        //Dynamics threw an error
                        console.log(errorThrown);
                        $("#list-serv-pleasewait-id").hide();
                        $("#list-serv-dynamics-error-id").show();
                    }
                });
            }
        },
        openGenericRequestForm: function (actionUrl, event) {
            if (NCJTC.site.checkForKeyboardClick(event)) {
                if (typeof event !== "undefined") {
                    event.preventDefault();
                }

                $(window).scrollTop(0);

                $("#modRequestTrainingForm").foundation("open");
                $("#dynamics-error-id").hide();
                $("#request-training-generic-id").removeClass("hide");
                $("[id^='request-training-specific']").addClass("hide");

                var htmlId = "#request-training-form-container";

                $(htmlId).empty();
                $("#pleasewait-id").show();
                $("#request-training-form-data").hide();

                $.ajax({
                    cache: false,
                    url: actionUrl + "?IsGenericForm=" + true,
                    type: "GET",
                    success: function (data) {
                        $("#pleasewait-id").hide();
                        $("#request-training-form-data").show();

                        //Show request form partial view
                        $(htmlId).html(data).hide().slideDown(150);

                        $("#modRequestTrainingForm input:text:first").focus();

                        //Anything changed here needs to be change in contactus.js
                        $("#RequestFormTrainingId").val("");
                        $("#RequestFormTrainingInstanceId").val("");
                        $("#RequestFormTrainingTitle").val("");
                        $("#RequestFormImportedTitle").val("");
                        $("#RequestFormCategory").val("");
                        $("#RequestFormProgram").val("");
                        $("#RequestFormContactName").val("");
                        $("#RequestFormContactEmail").val("");
                        $("#RequestFormIsWebinar").val("false");
                        $("#RequestFormCourseId").val("");
                        $("#RequestFormStartDate").val("");
                        $("#RequestFormCatalogId").val("");

                        var url = window.location.href;
                        $("#RequestFormUrl").val(url);

                        $("#HowCanWeAssist").val("1");
                        NCJTC.site.showAdditionalQuestions();

                        NCJTC.site.initializeAgencySearchAutocomplete();

                        var form = $("#requestTrainingForm");

                        $(form).data('validator', null);
                        $.validator.unobtrusive.parse($(form));
                        grecaptcha.reset();

                        NCJTC.site.initializeAgencyAddressAutocomplete();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        //Dynamics threw an error
                        console.log(errorThrown);
                        $("#pleasewait-id").hide();
                        $("#dynamics-error-id").show();
                    }
                });
            }
        },
        openSpecificRequestForm: function (actionUrl, event) {
            if (NCJTC.site.checkForKeyboardClick(event)) {
                if (typeof event !== "undefined") {
                    event.preventDefault();
                }

                $(window).scrollTop(0);

                $("#modRequestTrainingForm").foundation("open");
                $("#dynamics-error-id").hide();
                $("#request-training-generic-id").addClass("hide");
                $("[id^='request-training-specific']").removeClass("hide");

                var training = $("#FormTraining").val();
                $("#request-training-specific-title-id").text(training);

                var htmlId = "#request-training-form-container";

                $(htmlId).empty();
                $("#pleasewait-id").show();
                $("#request-training-form-data").hide();

                $.ajax({
                    cache: false,
                    url: actionUrl + "?IsGenericForm=" + false,
                    type: "GET",
                    success: function (data) {
                        $("#pleasewait-id").hide();
                        $("#request-training-form-data").show();

                        //Show request form partial view
                        $(htmlId).html(data).hide().slideDown(150);

                        $("#modRequestTrainingForm input:text:first").focus();

                        var form = $("#requestTrainingForm");

                        var trainingId = $("#FormTrainingId").val();
                        var trainingInstanceId = $("#FormTrainingInstanceId").val();

                        var training = $("#FormTraining").val();
                        var importedTitle = $("#FormImportedTitle").val();

                        var category = $("#FormCategory").val();
                        var program = $("#FormProgram").val();
                        var contactName = $("#FormContactName").val();
                        var contactEmail = $("#FormContactEmail").val();
                        var isWebinar = $("#FormIsWebinar").val();
                        var catalogId = $("#FormCatalogId").val();
                        var startDate = $("#FormStartDate").val();
                        var courseId = $("#FormCourseId").val();

                        $("#RequestFormTrainingId", $(form)).val(trainingId);
                        $("#RequestFormTrainingInstanceId", $(form)).val(trainingInstanceId);

                        $("#RequestFormTrainingTitle", $(form)).val(training);
                        $("#RequestFormImportedTitle", $(form)).val(importedTitle);

                        $("#RequestFormCategory", $(form)).val(category);
                        $("#RequestFormProgram", $(form)).val(program);
                        $("#RequestFormContactName", $(form)).val(contactName);
                        $("#RequestFormContactEmail", $(form)).val(contactEmail);
                        $("#RequestFormIsWebinar", $(form)).val(isWebinar);
                        $("#RequestFormCourseId", $(form)).val(courseId);
                        $("#RequestFormStartDate", $(form)).val(startDate);
                        $("#RequestFormCatalogId", $(form)).val(catalogId);

                        var url = window.location.href;
                        $("#RequestFormUrl").val(url);

                        if (window.location.hash.toLowerCase() === "#notify") {
                            $("#HowCanWeAssist").val("3"); //Notify me when this class is scheduled
                        }

                        NCJTC.site.showAdditionalQuestions();
                        NCJTC.site.initializeAgencySearchAutocomplete();

                        var form = $("#requestTrainingForm");

                        $(form).data('validator', null);
                        $.validator.unobtrusive.parse($(form));
                        grecaptcha.reset();

                        NCJTC.site.initializeAgencyAddressAutocomplete();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        //Dynamics threw an error
                        console.log(errorThrown);
                        $("#pleasewait-id").hide();
                        $("#dynamics-error-id").show();
                    }
                });
            }
        },
        reopenRequestForm: function () {
            if (NCJTC.site.checkForKeyboardClick(event)) {
                $("#modRequestTrainingForm").foundation("open");
                $("#modRequestTrainingForm input:text:first").focus();
            }
        },
        renderAgencySearchItem: function (ul, item) {
            var newTitle = item.label;
            var newState = item.state;

            var state = "";
            if (newState !== null) {
                state = newState;
            }

            return $("<li class='autocomplete-item'>")
                .data("item.autocomplete", item)
                .append("<div class='row'><div class='large-12 columns'>" + newTitle + "<br/><span class='subtle2'>" + state + "</span></div></div>")
                .append("</li>")
                .appendTo(ul);
        },
        initializeAgencySearchAutocomplete: function () {
            $("[id$='Agency'], .organizationAutocomplete").autocomplete({
                minLength: 2,
                delay: 100,
                select: function (event, li) {
                    event.preventDefault();

                    var fieldId = event.target.id;
                    var prefixId = $(event.target).attr("data-prefix");

                    $("#" + fieldId).val(li.item.label);
                    $("#OrganizationId").val(li.item.value);
                    $("#" + prefixId + "OrgControlId").val(li.item.value);
                    $("#" + prefixId + "addorg-id").removeAttr("disabled").removeClass("disabled");
                    $("#" + prefixId + "orgChanged").val("true");
                },
                focus: function (event, ui) {
                    event.preventDefault();
                    if (event.originalEvent !== undefined && event.originalEvent.originalEvent !== undefined && event.originalEvent.originalEvent.type.indexOf("mouse") === -1) {
                        this.value = ui.item.label; //On focus show field label instead of field id
                    }
                },
                source: function (request, response) {
                    $.ajax({
                        url: "/Request/SearchOrganizations?searchText=" + request.term,
                        dataType: "json",
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return { label: item.OrganizationName, value: item.OrganizationId, state: item.State };
                            }));
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log(errorThrown);
                        }
                    });
                },
                change: function (event, ui) {
                    if (ui.item == null) {
                        $("#AgencyId").val("");
                    }
                },
                search: function (event) {
                    var prefixId = $(event.target).attr("data-prefix");
                    $("#" + prefixId + "addorg-id").prop('disabled', true).addClass("disabled");
                }
            });

            $("[id$='Agency']").keyup(function (event) {
                var text = $(this).val();
                if (text === "") {
                    var prefixId = $(event.target).attr("data-prefix");
                    //Disable Next button if there is no text in field
                    $("#" + prefixId + "addorg-id").prop('disabled', true).addClass("disabled");
                }
            });

            $("[id$='Agency'], .organizationAutocomplete").each(function (idx, elem) {
                var autocompleteInstance = $(elem).autocomplete('instance');

                if (autocompleteInstance !== undefined) {
                    $(elem).autocomplete('instance')._renderItem = NCJTC.site.renderAgencySearchItem;
                }
            });

            $("[id$='Agency'], .organizationAutocomplete").attr("autocomplete", "new-password");
        },
        renderSearchItem: function (ul, item) {
            // Creating arrays to hold each word in the title of a course, and each search term being typed by the user
            var termHolder = this.term.split(' ');
            var titleHolder = item.Title.split(' ');

            // For each word in the title, check against each search term for matches and bold them
            $.each(titleHolder, function (titleKey, titleWord) {
                $.each(termHolder, function (termKey, termWord) {
                    if (titleWord.toLowerCase().indexOf(termWord.toLowerCase()) >= 0) {
                        titleHolder[titleKey] = titleWord.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(termWord) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
                        return false;
                    }
                });
            });

            // Put the title back together again
            var revisedTitle = titleHolder.join(' ');
            var searchBoxText = $("#training-search-text-id, #home-content-heroSearch-input-id").val();

            if (item.IsFirst === true) {
                return $("<li class='autocomplete-item'>")
                    .data("item.autocomplete", item)
                    .append("<div class='grid-x'><div class='large-12 cell'><i class='far fa-search textright'></i> See all results for'<strong>" + searchBoxText + "'</stong></div></div>")
                    .append("</li>")
                    .appendTo(ul);
            } else {
                return $("<li class='autocomplete-item'>")
                    .data("item.autocomplete", item)
                    .append("<div class='grid-x'><div class='large-12 cell'>" + revisedTitle + "</div></div>")
                    .append("</li>")
                    .appendTo(ul);
            }
        },
        resizeSearchMenu: function () {
            var ul = this.menu.element;
            ul.outerWidth(this.element.outerWidth());
        },
        initializeSearchAutocomplete: function () {
            $('#training-search-text-id, #home-content-heroSearch-input-id').autocomplete({
                minLength: 2,
                delay: 500,
                open: function (event, ui) {
                    //Remove the rendered class that autocomplete puts on category
                    $("ul li.ui-autocomplete-category").removeClass("ui-menu-item");
                },

                select: function (event, li) {
                    var url = "";
                    var term = "";

                    if (li.item !== undefined) {

                        if (li.item.IsFirst) {
                            term = $('#training-search-text-id, #home-content-heroSearch-input-id').val();
                        } else {
                            term = li.item.Title;
                        }

                        // Standard training
                        if (li.item.IsOverview === true) {
                            event.preventDefault();
                            url = "/programs/" + li.item.ProgramId + "/" + li.item.Slug + "/overview";
                        }
                        else {
                            event.preventDefault();
                            var contentType = $("#content").val();
                            var contentTypeParam = "";

                            if (contentType !== undefined) {
                                contentTypeParam = "&content=" + contentType;
                            } else {
                                contentTypeParam = "&content=Training";
                            }

                            url = "/search-results?terms=" + term + contentTypeParam;
                        }
                        //update input with selection
                        $(event.target).val(term);
                    }

                    $("#progress-id").show();
                    $('#training-search-text-id, #home-content-heroSearch-input-id').blur();

                    setTimeout(function () {
                        window.location.href = url;
                    }, 500);
                },
                source: function (request, response) {
                    $.ajax({
                        url: "/autocomplete?keywords=" + request.term,
                        dataType: "json",
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        select: function (event, ui) {
                            //update input with selection
                            $(event.target).val(ui.item.value);
                            $("input:text", form).blur();
                        },
                        success: function (data) {
                            var flattened = [];
                            $.each(data, function (index, item) {

                                flattened.push(item);
                                flattened = flattened.concat(item.Matches);
                            });

                            response($.map(flattened, function (item) {
                                return item;
                            }));

                            $(".ui-autocomplete-category div.ui-menu-item-wrapper").removeClass("ui-menu-item-wrapper");
                            $(".ui-autocomplete-category div.ui-menu-item-wrapper").attr("tabindex", null);
                            $(".ui-autocomplete-category div.ui-menu-item-wrapper").attr("id", null);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log(errorThrown);
                        }
                    });
                }
            });

            //Autocomplete Width
            $('#training-search-text-id, #home-content-heroSearch-input-id').autocomplete("instance")._resizeMenu = NCJTC.site.resizeSearchMenu;

            //Autocomplete shows bold on search term results
            $('#training-search-text-id, #home-content-heroSearch-input-id').autocomplete("instance")._renderItem = NCJTC.site.renderSearchItem;
        },
        setFocusToSearch: function () {
            $("[id$='search-text-id']").focus();
        },
        initializeMoreAndLessButtons: function (domId) {

            var selector = "p.minimize span,p.minimize small, p.minimize";


            if (domId != undefined) {
                selector = domId + " " + selector;
            }

            var minimized = $(selector);

            minimized.each(function () {
                NCJTC.markdown.processMarkdownOnElement(this);
                var minimizeCount = $(this).data("mincount");

                //if data-mincount doesnt exist default it.
                if (minimizeCount == undefined) {
                    minimizeCount = '200';
                }
                var t = $(this).text();

                if (t.length < minimizeCount) {
                    $(this).removeClass("minimize");
                    $(this).html(t);
                    $(this).show();
                    return;
                };

                $(this).html(
                    t.slice(0, minimizeCount) + '<span>... </span><a href="#" class="more">More</a>' +
                    '<span style="display:none;">' + t.slice(minimizeCount, t.length) + ' <a  href="#" class="less">Less</a></span>'
                );
                $(this).show();

            });

            $('a.more', selector).click(function (event) {
                event.preventDefault();
                event.stopPropagation();
                $(this).hide().prev().hide();
                $(this).next().show();
            });

            $('a.less', selector).click(function (event) {
                event.preventDefault();
                event.stopPropagation();
                $(this).parent().hide().prev().show().prev().show();
            });
        },
        toggleHamburgerMenu: function () {
            $("#nav-small-id").fadeToggle(500);
            $(".hamburgerMenu").toggleClass("open");
        },
        cookies: {
            getCookie: function (cname) {
                var name = cname + "=";
                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);
                    }
                    if (c.indexOf(name) === 0) {
                        return c.substring(name.length, c.length);
                    }
                }
                return "";
            },
            setCookie: function (cname, cvalue, exdays) {
                var d = new Date();
                d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
                var expires = "expires=" + d.toUTCString();
                document.cookie = cname + "=" + cvalue + "; " + expires + ";secure;";
            }
        },
        attempts: 0,
        sendRequest: function (actionUrl, event) {
            $("#SubmitGeneralRequestForm").animate({ width: '100' }, "fast").val("Sending...").attr("disabled", true);
            event.preventDefault();

            var form = $(event.currentTarget).closest("form");
            form = $("#requestTrainingForm");

            var isValid = $(form).valid() && grecaptcha.getResponse() !== "";
            var contactPreference = $("input[name=ContactPreference]:checked").val();
            var trainingPreferenceIsValid = $("#HowCanWeAssist").val() === "3" || $("#HowCanWeAssist").val() === "4" ? typeof $("input[name=TrainingPreference]:checked").val() !== "undefined" : true;

            if (isValid && typeof contactPreference !== "undefined" && trainingPreferenceIsValid) {
                $.ajax({
                    type: "POST",
                    url: actionUrl,
                    data: $(form).serialize(),
                    dataType: "text",
                    success: function () {
                        NCJTC.site.sendConfirmationEmail(form);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        NCJTC.site.attempts++;
                        if (NCJTC.site.attempts < 3) {
                            NCJTC.site.sendRequest(actionUrl, event);
                        } else {
                            NCJTC.site.sendFailureEmail(form);
                        }
                    }
                });
            } else {
                if (grecaptcha.getResponse() === "") {
                    $("#google-captcha-error").removeClass('field-validation-valid').addClass('field-validation-error');
                }
                $("#SubmitGeneralRequestForm").animate({ width: '62' }, "fast").val("Send").attr("disabled", false);
                return false;
            }
        },
        sendListServRequest: function (actionUrl, event) {
            $("#SubmitListServRequestForm").animate({ width: '100' }, "fast").val("Sending...").attr("disabled", true);
            event.preventDefault();

            var form = $("#requestListServForm");

            var isValid = $(form).valid() && grecaptcha.getResponse() !== "";

            if (isValid) {
                $.ajax({
                    type: "POST",
                    url: actionUrl,
                    data: $(form).serialize(),
                    dataType: "text",
                    success: function () {
                        NCJTC.site.sendListServConfirmationEmail(form);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        NCJTC.site.attempts++;
                        if (NCJTC.site.attempts < 3) {
                            NCJTC.site.sendListServRequest(actionUrl, event);
                        } else {
                            NCJTC.site.sendListServFailureEmail(form);
                        }
                    }
                });
            } else {
                if (grecaptcha.getResponse() === "") {
                    $("#google-captcha-error").removeClass('field-validation-valid').addClass('field-validation-error');
                }
                $("#SubmitListServRequestForm").animate({ width: '62' }, "fast").val("Send").attr("disabled", false);
                return false;
            }
        },
        sendConfirmationEmail: function (form) {
            $.ajax({
                type: "POST",
                url: "/Request/SendConfirmationEmail",
                data: $(form).serialize(),
                dataType: "text",
                success: function () {
                    $("#modRequestTrainingFormDone").foundation("open");
                    $("#SubmitGeneralRequestForm").animate({ width: '62' }, "fast").val("Send").attr("disabled", false);
                    grecaptcha.reset();
                    $("#google-captcha-error").addClass('field-validation-valid').removeClass('field-validation-error');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    NCJTC.site.attempts++;
                    if (NCJTC.site.attempts < 3) {
                        NCJTC.site.sendConfirmationEmail(form);
                    }
                }
            });
        },
        sendFailureEmail: function (form) {
            $.ajax({
                type: "POST",
                url: "/Request/SendFailureEmail",
                data: $(form).serialize(),
                dataType: "text",
                success: function (successful) {
                    $("#modRequestTrainingFormDone").foundation("open");
                    $("#SubmitGeneralRequestForm").animate({ width: '62' }, "fast").val("Send").attr("disabled", false);
                    grecaptcha.reset();
                    $("#google-captcha-error").addClass('field-validation-valid').removeClass('field-validation-error');
                    NCJTC.site.attempts = 0;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $("#modRequestTrainingFormError").foundation("open");
                    $("#SubmitGeneralRequestForm").removeAttr('disabled').removeClass("disabled");
                }
            });
        },
        sendListServConfirmationEmail: function (form) {
            $.ajax({
                type: "POST",
                url: "/Request/SendListServConfirmationEmail",
                data: $(form).serialize(),
                dataType: "text",
                success: function () {
                    $("#modRequestListServFormDone").foundation("open");
                    $("#SubmitListServRequestForm").animate({ width: '62' }, "fast").val("Send").attr("disabled", false);
                    grecaptcha.reset();
                    $("#google-captcha-error").addClass('field-validation-valid').removeClass('field-validation-error');
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    NCJTC.site.attempts++;
                    if (NCJTC.site.attempts < 3) {
                        NCJTC.site.sendListServConfirmationEmail(form);
                    }
                }
            });
        },
        sendListServFailureEmail: function (form) {
            $.ajax({
                type: "POST",
                url: "/Request/SendListServFailureEmail",
                data: $(form).serialize(),
                dataType: "text",
                success: function (successful) {
                    $("#modRequestListServFormDone").foundation("open");
                    $("#SubmitListServRequestForm").animate({ width: '62' }, "fast").val("Send").attr("disabled", false);
                    grecaptcha.reset();
                    $("#google-captcha-error").addClass('field-validation-valid').removeClass('field-validation-error');
                    NCJTC.site.attempts = 0;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $("#modRequestListServFormError").foundation("open");
                    $("#SubmitListServRequestForm").removeAttr('disabled').removeClass("disabled");
                }
            });
        },
        SendIdentityConfirmationEmail: function (id) {
            $.ajax({
                type: "GET",
                url: "/Account/Organizations/resendConfirmationEmail?fvtcId=" + id,
                data: $(id).serialize(),
                dataType: "text",
                success: function () {
                    $(".resendIdentifyConf").hide();
                    $(".resendIdentifyConfSent").show();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $(".resendIdentifyConf").hide();
                    $(".resendIdentifyConfSentError").show();
                }
            });
        },
        toggleSectionVisibility: function (elem, event) {
            $(elem).next().slideToggle(500);

            $("i", $(elem)).toggleClass("fa-caret-right fa-caret-down");

            if (event != undefined) {
                event.stopImmediatePropagation();
            }
        },
        toggleOrgVisibility: function (elem, event) {
            if ($(elem).next().css('display') == 'none') {
                $("i.fa-chevron-left", $(elem)).addClass('is-active');
            } else {
                $("i.fa-chevron-left", $(elem)).removeClass('is-active');

            }

            $(elem).next().slideToggle(250);

            if (event !== undefined) {
                event.stopImmediatePropagation();
            }
        },
        lookForRequestFormUrl: function (openGenericRequestForm) {
            if (window.location.hash.toLowerCase() === "#request") {
                if (openGenericRequestForm) {
                    NCJTC.site.openGenericRequestForm("/Request/RequestTraining");
                } else {
                    NCJTC.site.openSpecificRequestForm("/Request/RequestTraining");
                }
            }
            else if (window.location.hash.toLowerCase() === "#notify") {
                NCJTC.site.openSpecificRequestForm("/Request/RequestTraining");
            }
        },
        performFilterCheckboxSearch: function (filterSectionId, filterQueryStringParameterName, mutuallyExclusive, anchor, event) {
            var filterValues = '';

            if ($(event.currentTarget).is("input:text")) {
                filterQueryStringParameterName = "terms";

                var searchTerm = $(event.currentTarget).val();

                filterValues = searchTerm;
            }
            else
            // Modify the querystring based on the checkbox group that changed
            {
                var wrapper = $(event.currentTarget);
                var checkbox = $("input", wrapper);

                $('#' + filterSectionId + ' input[type=checkbox]').each(function (index, value) {
                    var item = $(this);
                    if (item.is(':checked')) {

                        var filterValue = '';

                        if (item.is('[data-filter]')) {
                            filterValue = item.attr('data-filter');
                        }
                        else if (item.parent().is('[data-filter]')) {
                            filterValue = item.parent().attr('data-filter');
                        }
                        if (filterValue !== '') {

                            filterValues += filterValue + ',';
                        }
                    }
                });
            }

            var baseUrl = NCJTC.site.removeURLParameter(window.location.href.split('#')[0], filterQueryStringParameterName)

            if (anchor == undefined) {
                if (window.location.href.split('#').length > 0) {
                    anchor = window.location.href.split('#')[1];
                }
            }

            if (filterValues !== '') {
                filterValues = filterQueryStringParameterName + '=' + filterValues.substring(0, filterValues.length - 1);
                if (baseUrl.indexOf("?") === -1) {
                    filterValues = "?" + filterValues;
                } else {
                    filterValues = "&" + filterValues
                }
            }

            if (anchor != undefined) {
                filterValues += "#" + anchor;
            }

            window.location.href = baseUrl + filterValues;
        },
        removeURLParameter: function (url, parameter) {
            var urlparts = url.split('?');
            if (urlparts.length >= 2) {

                var prefix = encodeURIComponent(parameter) + '=';
                var pars = urlparts[1].split(/[&;]/g);

                // We always want to remove the collectionID, otherwise the last clicked collection will always pop up
                var collectionPrefix = "collectionID=";

                //reverse iteration as may be destructive
                for (var i = pars.length; i-- > 0;) {

                    if (pars[i].lastIndexOf(prefix, 0) !== -1 || pars[i].lastIndexOf(collectionPrefix, 0) !== -1) {
                        pars.splice(i, 1);
                    }
                }

                url = urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
                return url;
            } else {
                return url;
            }
        },
        setStateField: function () {
            var country = $("#CountryId").val();
            if (country === "USA") {
                $("#StateDropDown").show();
                $("#StateTextBox").hide();
                $("#Phone").mask("999-999-9999");
            } else {
                $("#StateDropDown").hide();
                $("#StateTextBox").show();
                $("#Phone").unmask();
            }

            //Update address autocomplete to find addresses for the selected country
            agencyAddressAutocomplete.setComponentRestrictions({ 'country': [country.toLowerCase()] });

            //Reset address fields so that there isn't bad data
            NCJTC.site.resetTrainingRequestAddressFields();
        },
        resetTrainingRequestAddressFields: function () {
            var form = $("#requestTrainingForm");

            $("input[id$='Address']", $(form)).val("");
            $("input[id$='City']", $(form)).val("");
            $("input[id$='ZipCode']", $(form)).val("");
            $("input[id$='StateOrProvince']", $(form)).val("");
            $("select[id$='State']", $(form)).val("WI");
        },
        initializeAgencyAddressAutocomplete: function () {
            var country = $("#CountryId").val().toLowerCase();
            agencyAddressAutocomplete = new google.maps.places.Autocomplete((document.getElementById('Address')), { types: ['geocode'], componentRestrictions: { country: country } });

            // When the user selects an address from the dropdown, populate the address
            // fields in the form.
            agencyAddressAutocomplete.addListener('place_changed', NCJTC.site.fillInAddress);

            NCJTC.site.setAgencyAddressAutocompleteResults();
        },
        setAgencyAddressAutocompleteResults: function () {
            setTimeout(function () {
                //We show the result like this in case there are multiple autocompletes on the page
                $(".pac-container").prependTo("#agencyAddressAutocompleteResult");
            }, 300);
        },
        fillInAddress: function () {
            var place = agencyAddressAutocomplete.getPlace();

            var forms = ["#requestTrainingForm", "#requestListServForm"];
            forms.forEach((formId) => {
                var form = $(formId);

                if ($(form).length == 1) {
                    try {

                        if (place.formatted_address === undefined) {
                            // User didnt select a item, they just hit enter and autocomplete captures it.
                            NCJTC.site.resetTrainingRequestAddressFields();
                        } else {
                            $("#address-found", $(form)).val("true");

                            NCJTC.site.resetTrainingRequestAddressFields();

                            // Get each component of the address from the place details
                            // and fill the corresponding field on the form.
                            var fullStreetAddress = "";

                            for (var i = 0; i < place.address_components.length; i++) {
                                var addressType = place.address_components[i].types[0];

                                if (componentFormConfig[addressType]) {
                                    var val = "";
                                    if (addressType === "street_number") {
                                        $("input[id$='Address']", $(form)).val(val);
                                        fullStreetAddress = place.address_components[i][componentFormConfig[addressType]];
                                    }

                                    if (addressType === "route") {
                                        fullStreetAddress += " " + place.address_components[i][componentFormConfig[addressType]];
                                    }

                                    if (addressType === "locality") {
                                        val = place.address_components[i][componentFormConfig[addressType]];
                                        $("input[id$='City']", $(form)).val(val);
                                        $("input[id$='City']", $(form)).change();
                                        $("input[id$='City']", $(form)).valid();
                                    }

                                    if (addressType === "postal_town") {
                                        val = place.address_components[i][componentFormConfig[addressType]];
                                        $("input[id$='City']", $(form)).val(val);
                                        $("input[id$='City']", $(form)).valid();
                                    }

                                    if (addressType === "postal_code") {
                                        val = place.address_components[i][componentFormConfig[addressType]];
                                        $("input[id$='ZipCode']", $(form)).val(val);
                                        $("input[id$='ZipCode']", $(form)).valid();
                                    }
                                }

                                if (addressType === "administrative_area_level_1") {
                                    val = place.address_components[i][componentFormConfig[addressType]];

                                    stateHidden = $("[id$='State']", $(form)).attr("type") === "hidden";
                                    if (!stateHidden) {
                                        if ($("[id$='State'] option[value='" + val + "']", $(form)).length > 0) {
                                            $("[id$='State']", $(form)).val(val);
                                        }
                                    }

                                    stateProvinceRegionHidden = $("[id$='StateOrProvince']", $(form)).attr("type") === "hidden";
                                    if (!stateProvinceRegionHidden) {
                                        $("[id$='StateOrProvince']", $(form)).val(val);
                                    }
                                }
                            }

                            $("input[id$='Address']", $(form)).val(fullStreetAddress);

                            var address1Id = $(form).find("input[id$='Address']").attr("id");
                            $(form).validate().element("input#" + address1Id);
                        }

                        $("[id$='State']", $(form)).change();
                    } catch (error) {
                        console.error(error);
                    }
                }
            });
        },
        showAdditionalQuestions: function () {
            var isGenericForm = $("#IsGenericForm").val() === "True";

            var value = $("#HowCanWeAssist").val();

            var assistQuestion = "How can we assist you?";
            var classQuestion = "Which training are you referring to?";

            //Show/hide how can we assist you text box
            if (isGenericForm) {
                if (value === "1" || value === "4" || value === "5" || value === "6" || value === "7") {
                    if (value === "1" || value === "5") {
                        $("#Description").prop("placeholder", classQuestion);
                        $("#Description").prop("aria-label", classQuestion);
                    } else {
                        $("#Description").prop("placeholder", assistQuestion);
                        $("#Description").prop("aria-label", assistQuestion);
                    }
                    $("#AssistYouTextBox").show();
                } else {
                    $("#AssistYouTextBox").hide();
                }
            } else {
                if (value === "4" || value === "5" || value === "6") {
                    $("#AssistYouTextBox").show();
                } else {
                    $("#AssistYouTextBox").hide();
                }
            }

            //Show/hide training preference question
            if (value === "3" || value === "4" || value === "5") {
                $("#TrainingPreferenceQuestion").show();
            } else {
                $("#TrainingPreferenceQuestion").hide();
            }
        },
        // - preventEnterKey
        // Used to prevent the automatic firing of validation when a user presses enter to select an address
        preventEnterKey: function (event) {
            var enterKey = 13;
            var keyCode = event.which;
            $("#autocompleteValidation").empty().removeClass('field-validation-error').addClass('field-validation-valid');

            if (keyCode === enterKey) {
                event.preventDefault();  // Prevents the default browser behavior for the key
                event.stopPropagation(); // Prevents the keystrokes event from bubbling up
                return false;
            }
        },
        wireUpAnalyticsEvents: function () {
            //Used for Google analytics.
            //Tracks all downloads and external/outbound links
            if (typeof jQuery != 'undefined') {
                var filetypes = /\.(zip|exe|dmg|pdf.*|doc.*|xls.*|ppt.*|mp3|txt|rar|wma|mov|avi|wmv|flv|wav)$/i;
                var baseHref = '';
                if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');
                var hrefRedirect = '';

                jQuery('body').on('click', 'a', function (event) {
                    var el = jQuery(this);
                    var track = true;
                    var href = (typeof (el.attr('href')) != 'undefined') ? el.attr('href') : '';
                    var isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);
                    var isThisSubdomain = href.match(document.domain);
                    var isFvtcApps = href.match(document.domain + "/apps/");

                    if (!href.match(/^javascript:/i)) {
                        var elEv = [];
                        elEv.value = 0, elEv.non_i = false;
                        if (href.match(/^mailto\:/i)) {
                            elEv.category = 'email';
                            elEv.action = 'click';
                            elEv.label = href.replace(/^mailto\:/i, '');
                            elEv.loc = href;
                        } else if (href.match(filetypes)) {
                            var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                            elEv.category = 'download';
                            elEv.action = 'click-' + extension[0].replace(/\?.*/g, '');
                            elEv.label = href.replace(/ /g, '-');
                            elEv.loc = baseHref + href;
                        } else {
                            var httpRemovedUrl = href.replace(/^https?\:\/\//i, '');

                            if (href.match(/^https?\:/i) && !isThisDomain) { // Not fvtc.edu
                                elEv.category = 'external';
                                elEv.action = 'click';
                                elEv.label = httpRemovedUrl;
                                elEv.non_i = true;
                                elEv.loc = href;
                            } else if (href.match(/^https?\:/i) && (isThisDomain && !isThisSubdomain)) {   // somethingelse.fvtc.edu
                                elEv.category = 'fvtc-subdomain';
                                elEv.action = httpRemovedUrl.split('.')[0]; // Subdomain (myfvtc.fvtc.edu would yeild myfvtc)
                                elEv.label = httpRemovedUrl;
                                elEv.non_i = true;
                                elEv.loc = href;
                            } else if (href.match(/^https?\:/i) && isFvtcApps) {   // www.fvtc.edu/apps/MyTraining
                                elEv.category = 'fvtc-apps';
                                elEv.action = httpRemovedUrl.split('/')[2];  // www.fvtc.edu/apps/MyTraining would yeild MyTraining
                                elEv.label = httpRemovedUrl;
                                elEv.non_i = true;
                                elEv.loc = href;
                            } else if (href.match(/^tel\:/i)) {
                                elEv.category = 'telephone';
                                elEv.action = 'click';
                                elEv.label = href.replace(/^tel\:/i, '');
                                elEv.loc = href;
                            } else track = false;
                        }
                        if (track) {

                            // Added try around this code so that if something goes wrong with the call to GTAG analytics,
                            //   it will not bring down the links on the site.
                            try {
                                var ret = true;

                                if ((elEv.category == 'external' || elEv.category == 'download' || elEv.category == 'fvtc-apps' || elEv.category == 'fvtc-subdomain') && (el.attr('target') == undefined || el.attr('target').toLowerCase() != '_blank')) {
                                    hrefRedirect = elEv.loc;

                                    gtag('event', elEv.action.toLowerCase(), {
                                        'event_category': elEv.category.toLowerCase(),
                                        'event_label': elEv.label.toLowerCase(),
                                        'event_value': elEv.value,
                                        'non_interaction': elEv.non_i,
                                        'event_callback': gaHitCallbackHandler
                                    });

                                    ret = false;
                                } else {

                                    gtag('event', elEv.action.toLowerCase(), {
                                        'event_category': elEv.category.toLowerCase(),
                                        'event_label': elEv.label.toLowerCase(),
                                        'event_value': elEv.value,
                                        'non_interaction': elEv.non_i
                                    });

                                }

                                return ret;

                            } catch (error) {
                                console.info(error);
                            }
                        }
                    }
                });

                gaHitCallbackHandler = function () {
                    window.location.href = hrefRedirect;
                };
            }
        },
    }
};

Array.prototype.remove = function () {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};;
NCJTC.markdown = {
    processMarkdown: function (selector) {
        if (selector == undefined) {
            selector = "code[data-fv-markdown]";
        }
       
        $(selector).each(function (idx, elem) {
            $(elem).replaceWith("<span data-fv-markdown>" + NCJTC.markdown.parseHtml($(elem).text()) + "</span>");
        });
    },
    processMarkdownOnElement: function (elem) {
        var txt = $(elem).text();
        var htmlText = NCJTC.markdown.parseHtml(txt);

        $(elem).text(htmlText);
    },
    parseHtml: function (originalText) {
        var afterBullets = NCJTC.markdown.replaceBullets(originalText);
        var afterImages = NCJTC.markdown.replaceImages(afterBullets);
        var afterHyperlinks = NCJTC.markdown.replaceHyperLinks(afterImages);
        var afterBold = NCJTC.markdown.replaceBold(afterHyperlinks);
        var afterItalics = NCJTC.markdown.replaceItalics(afterBold);
        var afterIndents = NCJTC.markdown.replaceIndents(afterItalics);

        if ($.trim(afterIndents) === "") {
            return "";
        } else {
            return afterIndents.replace(/\n/g, "<br />");
        }
    },
    replaceImages: function (txt) {
        var newTxt = txt.replace(/(\!\[([^\]]+?)\]\(([^\)]+?)\))/g, function (str, p1, displayText, url) {

            var linkStartsWith = url.substring(0, 7).toLowerCase();

            if (linkStartsWith != "http://") {
                url = "http://" + url;
            }

            var link = "<img src='" + url + "' alt='" + displayText + "' />";


            return link;
        });

        return newTxt;
    },
    replaceHyperLinks: function (txt) {
        var newTxt = txt.replace(/(\[([^\]]+?)\]\(([^\)]+?)\))/g, function (str, p1, displayText, url) {

            var linkStartsWith = url.substring(0, 7).toLowerCase();

            if (url.substring(0, 7).toLowerCase() !== "http://" && linkStartsWith !== "mailto:" && url.substring(0, 8).toLowerCase() !== "https://") {
                url = "http://" + url;
            }

            var link = "";

            if (linkStartsWith === "mailto:") {
                link = "<a href='" + url + "'>" + displayText + "</a>";
            } else {
                link = "<a href='" + url + "' target='_blank'>" + displayText + "</a>";
            }

            return link;
        });

        return newTxt;
    },
    replaceBold: function (txt) {
        var newTxt = txt.replace(/(\*\*(.*?)\*\*)/g, function (str, p1, textToBold) {

            var bolded = "<strong>" + textToBold + "</strong>";

            return bolded;
        });

        return newTxt;
    },
    replaceItalics: function (txt) {
        var newTxt = txt.replace(/(\*(.*?)\*)/g, function (str, p1, textToItalics) {

            var italicized = "<em>" + textToItalics + "</em>";

            return italicized;
        });

        return newTxt;
    },
    replaceIndents: function (txt) {
        var newTxt = txt.replace(/(\*\*(.*)?)/g, function (str, p1, indentedText) {

            var indented = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + indentedText;

            return indented;
        });

        return newTxt;
    },
    replaceBullets: function (txt) {
        // /\* (.*)/g, \<ul\>\<li\>$1\<\/li\>/\<\/ul\>
        var firstLineStarToTags = txt.replace(/^\* (.*)?/g, function (str, match, idx) {

            var html = "<ul><li>" + match + "</li></ul>";

            return html;
        });

        var newLineStarToTags = firstLineStarToTags.replace(/\n\* (.*)?/g, function (str, match, idx) {

            var html = "<ul><li>" + match + "</li></ul>";

            return html;
        });

        var consecutiveListsRemoved = newLineStarToTags.replace(/\<\/ul\>\<ul\>/g, "");

        var extraBreakRemoved = consecutiveListsRemoved.replace(/\<\/ul\>\n/g, "</ul>");

        return extraBreakRemoved;
    }
};;
var Common = {
    // Place phone validation on a property named the same as phone number with the word "Full" at the end of it.
    // {PhoneId}Full will always be validated and should contain the full E164 phone number starting with "+"
    // {PhoneId}Prefix will be populated with the International Phone Prefix
    // It will be used to hold onto the complete phone number with international phone prefix and validate it accordingly.
    initializeInternationalPhoneNumber: function (phoneFieldId) {
        var phonePrefixId = phoneFieldId + "Prefix";

        var phoneNumberElement = $("#" + phoneFieldId);
        var phoneNumber = $(phoneNumberElement).val();
        var phonePrefixElement = $("#" + phonePrefixId);

        var phonePrefix = $(phonePrefixElement).val().replace(/[^0-9]+/g, '');
        var phoneWithPrefix = phoneNumber;

        // When an invalid partial returns from an action the prefix and phone have been seperated into seperate fields by the previous initialization of the international phone plugin,
        // this logic will set the number back to the proper + value for re-initialization. 
        if (phonePrefixElement !== undefined && phoneNumber.length > 0 && phoneNumber.substring(0, 1) !== "+") {
            phoneWithPrefix = "+" + phonePrefix + phoneNumber.replace(/[^0-9]+/g, '');
            $(phoneNumberElement).val(phoneWithPrefix);
        }

        var input = phoneNumberElement[0];
        var iti = window.intlTelInput(input, {
            autoPlaceholder: "aggressive",
            formatOnDisplay: true,
            nationalMode: true,
            separateDialCode: true,
            utilsScript: "/Content/js/phone/utils.js"
        });

        $(phoneNumberElement).attr("autocomplete", "new-password");

        iti.setNumber(phoneWithPrefix);
        if (phoneWithPrefix !== "") {
            $("#" + phoneFieldId + "Full").val("+" + phoneWithPrefix.replace(/[^0-9]+/g, ''));
        }

        $(phonePrefixElement).val($(phonePrefixElement).val().replace(/[^0-9]+/g, ''));

        //// numbers and special focus keys only.
        $(input).on("keydown", function (evt) {
            if (
                !(evt.keyCode >= 48 && evt.keyCode <= 57) &&
                !(evt.keyCode >= 96 && evt.keyCode <= 105) &&
                evt.keyCode !== 109 &&
                evt.keyCode !== 45 &&
                evt.keyCode !== 46 &&
                evt.keyCode !== 35 &&
                evt.keyCode !== 36 &&
                evt.keyCode !== 8 &&
                evt.keyCode !== 9) {
                return false;
            }
        });

        //// We fire validation as they type, setnumber will format the field properly when the number fits the country format.
        $(input).on("keyup", function (evt) {
            var hiddenPhoneFullId = $(evt.currentTarget).attr("id") + "Full";
            var hiddenPrefixId = $(evt.currentTarget).attr("id") + "Prefix";

            var hiddenPhoneFullElem = $("#" + hiddenPhoneFullId);

            var keyupiti = window.intlTelInputGlobals.getInstance(evt.currentTarget);

            var currentPhoneValue = "+" + keyupiti.getNumber().replace(/[^0-9]+/g, '');
            var currentPhonePrefixValue = keyupiti.getSelectedCountryData().dialCode;

            $(hiddenPhoneFullElem).val(currentPhoneValue);
            if ($(hiddenPhoneFullElem).valid() && $(hiddenPhoneFullElem).val() !== "+") {
                keyupiti.setNumber($(hiddenPhoneFullElem).val());

                $("#" + hiddenPrefixId).val(currentPhonePrefixValue);
            }
        });

        // This logic will capture the country phone prefix in the hidden prefix field when the user selects a new country
        $(phoneNumberElement).on("countrychange", function (evt) {
            var phoneId = $(evt.currentTarget).attr("id");
            var hiddenPrefixId = $(evt.currentTarget).attr("id") + "Prefix";

            var countrychangeiti = window.intlTelInputGlobals.getInstance(evt.currentTarget);

            var oldPrefixValue = $("#" + hiddenPrefixId).val().replace(/[^0-9]+/g, '');

            var newPrefixValue = countrychangeiti.getSelectedCountryData().dialCode;

            $("#" + hiddenPrefixId).val(newPrefixValue);

            // When the prefix changes (NOT WHEN CHANGING FROM NANP +1 to another NANP +1)
            // Trigger the keyup event on the phone number to copy the form fields properly and format the number
            if (oldPrefixValue !== newPrefixValue) {
                $("#" + phoneId).trigger("keyup");
            }
        });

        return input;
    },
    removeInternationalPhoneNumber: function (phoneFieldId) {
        var phoneElement = $("#" + phoneFieldId);
        var phoneNumber = $("#" + phoneFieldId).val();

        var input = phoneElement[0];
        var iti = window.intlTelInputGlobals.getInstance(input);

        if (typeof iti !== "undefined") {
            var phonePrefix = iti.getSelectedCountryData().dialCode;

            if (phoneNumber.length > 0 && phoneNumber.substring(0, 1) !== "+") {
                phoneNumber = "+" + phonePrefix.replace(/[^0-9]+/g, '') + phoneNumber.replace(/[^0-9]+/g, '');
            }
            iti.destroy();

            $(phoneElement).val(phoneNumber);
        }
    },
    restoreValues: function (event, formId) {
        if (typeof formId === "undefined") {
            formId = $(event.currentTarget).closest("form").attr("id");
        } 

        $.each($("input[data-original-value], select[data-original-value], textarea[data-original-value]", "#" + formId), function (idx, elem) {
            //If the type is a checkbox set it to checked
            if ($(elem).attr("type") === "checkbox") {
                var originalValue = $(elem).attr("data-original-value");
                if (originalValue === "True") {
                    if (!$(elem)[0].checked) {
                        $(elem).trigger("click");
                    }
                } else {
                    if ($(elem)[0].checked) {
                        $(elem).trigger("click");
                    }
                }
            } else {
                $(elem).val($(elem).attr("data-original-value"));
            }

            $(".field-validation-error", $("#" + formId)).removeClass('field-validation-error').addClass('field-validation-valid');

            var internationalPhoneNumber = window.intlTelInputGlobals.getInstance(elem);
            if (typeof internationalPhoneNumber !== "undefined") {
                Common.removeInternationalPhoneNumber($(elem).attr("id"));
                Common.initializeInternationalPhoneNumber($(elem).attr("id"));
            }
        });
    },
    intializeTrimming: function () {
        $("input:text, textarea").on("blur", function (event) {
            $(event.currentTarget).val($.trim($(event.currentTarget).val()));
        });
    },
};;
