// AX-28884       Jul 26, 2023         ST          Created newCanLeavePatientInfo for PA 2.0
// AX-30606       Mar 04, 2024         v.s         Updated race field to a multi-select dropdown

// 52499005
// Decline To Answer checkbox clicked. Select empty Ethnicity item and disable Ethnicity field

function checkedDeclineAnswer() {
    if ($('#DeclineAnswerChkBox').is(':checked')) {

        $('#EthnicityDropDown').removeClass('is-invalid');
        $('#EthnicityDropDown').hide();
        $('#EthnicityEmptyDropDown').show();
        $('#hdnEthnicityInactive').val('Y');

        $('#multiSelectDropdown').text('');
        $('#multiSelectDropdown').attr('disabled', 'disabled');
    } else {
        $('#EthnicityDropDown').show();
        $('#EthnicityEmptyDropDown').hide();

        $('#multiSelectDropdown').removeAttr('disabled');
        handleRaceCheckbox();
    }
}

function setDefaultDateOfBirth() {
    const defaultAxiumDate = "1980-01-01";
    const dateField = document.getElementById("BirthdayTxt");
    if (!dateField.value) {
        dateField.value = defaultAxiumDate;
    }
}

// ***************************************************************
// *********  Validate() plug-in functions  39647133 *************
// ***************************************************************
var phoneLen = 14;

// *** 39647133 Functions for Validator ***

// 39647133 OnChange Contact At DropDown call Validation of phone numbers
// Call validation for one of the field for Home, Work, Other, Mobile and it validate related fields
function validateContactDp() {
    if (!$("#HomePhone").is(':disabled'))
        $("#HomePhone").valid();       //Same way to validate: $('#FormPat').validate().element("#HomePhone1");
    if (!$("#WorkPhone").is(':disabled'))
        $("#WorkPhone").valid();
    if (!$("#OtherPhone").is(':disabled'))
        $("#OtherPhone").valid();
    if (!$("#MobilePhone").is(':disabled'))
        $("#MobilePhone").valid();
}

// 39647133 Custom Validation for phone numbers. 
// At every field to validate it needs also to validate related fields. Example validate HomPhone1 need to check for HomePhoneCode and HomePhone2
// Obtain which kind of phone are to validate: Home, Work, Other, Mobile
// Contact At Dropdown is not related to the phone to validate, then it could be empty in all the fields (Code Area, Phone1, Phone2)
// Contact At Dropdown is related then Code Area must be 3 digits or empty, Phone1 needs to be 3 digits and phone2 4 digits
jQuery.validator.addMethod("validatePhoneNumbers", function (value, element) {
    var contactDropDownValue;
    var extEmptyOrNotUsed;              // 73341708
    var phone;

    if (element.id.indexOf('HomePhone') >= 0) {
        contactDropDownValue = "1";
        phone = '#HomePhone';
        extEmptyOrNotUsed = true;       // 73341708
    } else if (element.id.indexOf('WorkPhone') >= 0) {
        contactDropDownValue = "2";
        phone = '#WorkPhone';
        extEmptyOrNotUsed = $('#WorkPhoneExt').val() == '';
    } else if (element.id.indexOf('OtherPhone') >= 0) {
        contactDropDownValue = "3";
        phone = '#OtherPhone';
        extEmptyOrNotUsed = $('#OtherPhoneExt').val() == '';
    } else {
        contactDropDownValue = "4";
        phone = '#MobilePhone';
        extEmptyOrNotUsed = true;       // 73341708
    }

    // 73341708 Check also for empty Extension or not used
    if ($('#ContactAtDropDown').val() != contactDropDownValue && $(phone).val().length == 0 && extEmptyOrNotUsed == true)
        return true;

    var ok = $(phone).val().length == phoneLen;

    ok = ok && element.checkValidity(); // bootstrap validation

    return ok;
});

function ValidEmergInfoFirstName() {
    if ($('#hdnSettingEmergInfoRequired').val() == '0')
        return true;
    if ($('#EmergInfoFirstName').val() == '')
        return false;

    return true;
}
jQuery.validator.addMethod("validateEmergInfoFirstName", function () {
    return ValidEmergInfoFirstName();
});

// 42766229
function ValidEmergInfoLastName() {
    if ($('#hdnSettingEmergInfoRequired').val() == '0')
        return true;
    if ($('#EmergInfoLastName').val() == '')
        return false;

    return true;
}
jQuery.validator.addMethod("validateEmergInfoLastName", function () {
    return ValidEmergInfoLastName();
});

// 70551316 Custom Validation for Emergency phone numbers.
jQuery.validator.addMethod("validateEmergPhoneNumbers", function (value, element) {
    var extension;                                                      // 73341708
    var phone;

    if (element.id.indexOf('EmergInfoPhone') >= 0) {
        phone = '#EmergInfoPhone';
        extension = '#EmergInfoPhoneExt';                               // 73341708
    } else {
        phone = '#EmergInfoAlternativePhone';
        extension = '#EmergInfoAlternativePhoneExt';                    // 73341708
    }
    // 73341708 Check also Extension is not empty
    if ($(phone).val().length == 0 && $(extension).val().length == 0) {
        return (element.id.indexOf('EmergInfoAlternativePhone') >= 0);          // Return true if is EmergInfoAlternativePhone; Return false if is EmergInfoPhone bacause is required field. 
    }

    var ok = $(phone).val().length == phoneLen;

    ok = ok && element.checkValidity(); // bootstrap validation

    return ok;
});

// 52498835 During Race, found that need to do client side validation of title. Don't allow empty title if parameter allowBlancTitle is not 1
function ValidTitle() {
    if ($('#hdnAllowBlankTitle').val() != '1' && $('#TitleDropDown').val() == "") {
        return false;
    }
    return true;
}

// 52498835 During Race, found that need to do client side validation of title
jQuery.validator.addMethod("validateTitle", function () {
    return ValidTitle();
});


// 52498757
function ValidCustomCode(type) {
    var list = $('#hdnCustomCodes').val().split(",");
    var list2 = $('#hdnCustomCodesValidate').val().split(",");
    if ($.inArray(type.toString(), list2) >= 0 && $.inArray(type.toString(), list) >= 0) {

        if (type <= 10 && $.trim($('#CustomCode' + (type + 1).toString()).val()) == "Select") // 67051480
            return false;
        else if (type > 10 && $.trim($('#CustomCode' + (type + 1).toString()).val()) == "") // 67051480
            return false;
        else {
            return true;
        }
    }
    return true;
}
// 52498757
jQuery.validator.addMethod("validateCustomCode1", function () {
    return ValidCustomCode(0);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode2", function () {
    return ValidCustomCode(1);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode3", function () {
    return ValidCustomCode(2);
});


// 52498757
jQuery.validator.addMethod("validateCustomCode4", function () {
    return ValidCustomCode(3);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode5", function () {
    return ValidCustomCode(4);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode6", function () {
    return ValidCustomCode(5);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode7", function () {
    return ValidCustomCode(6);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode8", function () {
    return ValidCustomCode(7);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode9", function () {
    return ValidCustomCode(8);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode10", function () {
    return ValidCustomCode(9);
});



// 52498757
jQuery.validator.addMethod("validateCustomCode27", function () {
    return ValidCustomCode(26);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode28", function () {
    return ValidCustomCode(27);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode29", function () {
    return ValidCustomCode(28);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode30", function () {
    return ValidCustomCode(29);
});

// 52498757
jQuery.validator.addMethod("validateCustomCode31", function () {
    return ValidCustomCode(30);
});


// 52499051
// Validate Preferred Language drop down
function ValidLanguage() {
    if ($('#PreferredLanguageDropDown').val() == 'Select') {
        return false;
    }

    if ($('#hdnPrefLangInactive').val() == 'Y') {
        var selectedIndex = $('#PreferredLanguageDropDown').prop('selectedIndex');
        if (selectedIndex < 0)
            return false;
        if (selectedIndex == 0 && $("#PreferredLanguageDropDown option").eq(0).val() == $('#hdnPrefLangInactiveValue').val())
            return false;
    }
    return true;
}
// 52499051
// Add method to Validator plug-in to validate Preferred Language drop down
jQuery.validator.addMethod("validatePreferredLang", function () {
    return ValidLanguage();
});

// 52499005
// Validate Ethnicity drop down
function ValidEthnicity() {
    if ($('#DeclineAnswerChkBox').is(':checked'))
        return true;

    if ($('#hdnValidateEthnicity').val() != "1")
        return true;

    if ($('#EthnicityDropDown').val() == 'Select')
        return false;

    if ($('#hdnEthnicityInactive').val() == 'Y') {
        var selectedIndex = $('#EthnicityDropDown').prop('selectedIndex');
        if (selectedIndex < 0)
            return false;
        if ($("#EthnicityDropDown option").eq(selectedIndex).val() == '' || $("#EthnicityDropDown option").eq(selectedIndex).val() == $('#hdnEthnicityInactiveValue').val())
            return false;
    }
    return true;
}
// 52499051
// Add method to Validator plug-in to validate Ethnicity drop down
jQuery.validator.addMethod("validateEthnicity", function () {
    return ValidEthnicity();
});

jQuery.validator.addMethod("validateContactAt", function () {
    if ($('#ContactAtDropDown').val() == 'Select')
        return false;
    else
        return true;
});

// 52498835 Validate Races; Decline Answer Selected, or are more than one drop down or the only one is not empty
function ValidRaces() {
    
    if ($('#DeclineAnswerChkBox').is(':checked')) {
        return true;
    }

    if ($('#hdnValidateRace').val() != "1") {
        return true;
    }

    return $('#hdnSelectedRacesId').val() != "";
}

// 52498835 
// Add method to Validator for Races validation
jQuery.validator.addMethod("validateRaces", function () {
    return ValidRaces();
});

// 70551316 Ajax Function in synchronous mode (asynchronous: false) to check if selected Relation still in Relation table (updated relation in another PA instance)
// If CheckValid fail set EmergInfoRelation as empty
function CheckValidRelationJson() {
    if ($('#EmergInfoRelation').val() != '' && $('#EmergInfoRelation').val() != 'Select') {

        var relationParam = JSON.stringify({ "userIdStr": $('#hdnUserId').val(), "relation": $('#EmergInfoRelation').val() });
        //var relationParam = JSON.stringify({ "userIdStr": $('#hdnUserId').val() });
        $.ajax({
            type: "POST",
            url: "/PatientAccess/Services/RelationService.asmx/CheckValidRelation",
            data: relationParam,
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: false,
            success: function (data) {
                if (!data.d) {
                    RemoveInvalidRelation();
                }
            },
            error: function (error) {
                RemoveInvalidRelation();
            }
        });
    }
}

// 70551316 Clear current selection
function RemoveInvalidRelation() {
    var selectVal = $("#EmergInfoRelation").val();
    $("#EmergInfoRelation option[value='" + selectVal + "']").remove();                         // Remove current selected item
    // if there is not empty first item, add one.
    if ($("#PreferredLanguageDropDown option").eq(0).val() != "")
        $("#EmergInfoRelation").prepend("<option value='' selected='selected'></option>");      // Insert first empty item
    $('#hdnEmergRelation').val("");
}


// 70551316
function ValidEmergRelation() {

    if ($("#EmergInfoRelation").val() == 'Select')
        return false;

    CheckValidRelationJson();       // Ajax function, check Relation exist
    var selectedIndex = $('#EmergInfoRelation').prop('selectedIndex');
    if ($("#EmergInfoRelation option").eq(selectedIndex).val() == '')
        return false;
    return true;    
}

// 70551316
jQuery.validator.addMethod("validateEmergRelation", function () {
    return ValidEmergRelation();
});

function ValidEmergAddress() {
    if ($('#hdnValidateEmergAddress').val() == '0')
        return true;

    if ($('#EmergInfoAddress').val() == '')
        return false;
    return true;
}

jQuery.validator.addMethod("validateEmergAddress", function () {
    return ValidEmergAddress();
});

// 70551316
function ValidEmergCity() {
    if ($('#hdnValidateEmergAddress').val() == '0')
        return true;

    if ($('#EmergInfoCity').val() == '')
        return false;
    return true;
}
// 70551316
jQuery.validator.addMethod("validateEmergCity", function () {
    return ValidEmergCity();
});

function ValidEmergZip() {
    if ($('#hdnValidateEmergAddress').val() == '0')
        return true;

    if ($('#EmergInfoZip').val() == '')
        return false;

    return true;
}

jQuery.validator.addMethod("validateEmergZip", function () {
    return ValidEmergZip();
});

// 70551316
function ValidEmergState() {
    if ($('#hdnValidateEmergAddress').val() == '0')
        return true;

    var selectedIndex = $('#EmergInfoState').prop('selectedIndex');
    if ($("#EmergInfoState option").eq(selectedIndex).val() == 'Select')
        return false;
    return true;
}
// 70551316
jQuery.validator.addMethod("validateEmergState", function () {
    return ValidEmergState();
});

function ValidAddress() {
    if ($('#hdnIsEditableAddress').val() == '0')
        return true;

    if ($('#Address').val() == '')
        return false;
    return true;
}

jQuery.validator.addMethod("validateAddress", function () {
    return ValidAddress();
});

// 66825488
function ValidCity() {
    if ($('#hdnIsEditableZipPostalCode').val() == '0')
        return true;

    if ($('#cityAutocomplete').val() == '')
        return false;

    return true;
}

// 66825488
jQuery.validator.addMethod("validateCity", function () {
    return ValidCity();
});

// 66825488
function ValidCountry() {

    if ($('#hdnIsEditableZipPostalCode').val() == '0')
        return true;

    var selectedIndex = $('#CountryDropDown').prop('selectedIndex');
    if ($("#CountryDropDown option").eq(selectedIndex).val() == 'Select')
        return false;

    return true;
}

// 66825488
jQuery.validator.addMethod("validateCountry", function () {
    return ValidCountry();
});

// 66825488
function ValidState() {
    if ($('#hdnIsEditableZipPostalCode').val() == '0')
        return true;

    var selectedIndex = $('#StateDropDown').prop('selectedIndex');
    if ($("#StateDropDown option").eq(selectedIndex).val() == 'Select')
        return false;

    return true;
}

// 66825488
jQuery.validator.addMethod("validateState", function () {
    return ValidState();
});

// 42766229
function ValidFirstName() {
    if ($('#hdnIsEditableFirstName').val() == '0')
        return true;
    if ($('#FirstNameTxt').val() == '')
        return false;

    return true;
}
jQuery.validator.addMethod("validateFirstName", function () {
    return ValidFirstName();
});

// 42766229
function ValidLastName() {
    if ($('#hdnIsEditableLastName').val() == '0')
        return true;
    if ($('#LastNameTxt').val() == '')
        return false;

    return true;
}
jQuery.validator.addMethod("validateLastName", function () {
    return ValidLastName();
});

function ValidBirthday() {
    if ($('#hdnIsEditableBirthday').val() == '0')
        return true;
    if ($('#BirthdayTxt').val() == '')
        return false;

    return true;
}
jQuery.validator.addMethod("validateBirthday", function () {
    return ValidBirthday();
});

jQuery.validator.addMethod("regex", function (value, element, regexp) {
    return this.optional(element) || regexp.test(value);
});

// AX-17079
function getSettingMessage(key) {
   var msg = $('input[id$="' + key + '"]').val();
   return msg;
}

function cancel() {
    if (newCanLeavePatientInfo(undefined, true)) {
        parent.window.location.reload();
    }
}

var isSaving = false;

// AX-28884
function newCanLeavePatientInfo(redirectUrl, reload, redirectNode) {
    // check if current window has error window opened
    // this process will be terminated
    console.log(window);
    if (window.isErrorWindowOpened() || window.isConfirmWindowOpened()) {
       return false;
    }

    if (isSaving) {
        return true; // form has been submited
    }

    var formSerialized = serializePersonalInfoForm();
    var different = $('#hdnPatSerial').val() != formSerialized;

    if (different) {
        $('#modalTitle').html(getSettingMessage("hdnSettingLeaveUnsavedPatHeader"));
        $('#modalBody').html(getSettingMessage("hdnSettingLeaveUnsavedPatMessage"));
        $('#modalOkBtn').html("Yes");
        $('#modalCancelBtn').html("No");

        $('#modalOkBtn').on("click", function () {
            if (redirectUrl) {
                parent.openModalSpinner();
                $('#canLeaveModal').modal('hide');
                if (redirectNode != undefined) {
                    parent.window.toggleNavItem(redirectNode);
                }
                parent.window.redirectIFrameTo(redirectUrl);
            }
            else if (reload) {
                parent.window.location.reload();
            }
        });

        $('#canLeaveModal').modal('show'); 

        return false;     // This is trigger first time before even show the confirmWindow, so need to return false.
    }

    return true;      // Nothing to save, then return true
}

// AX-17079 validate if logout is possible (has personal info saved)
function canLeavePatientInfoToLogout() {
    // check if current window has error window opened
    // this process will be terminated
    if (getParentWindow(window).isErrorWindowOpened() || getParentWindow(window).isConfirmWindowOpened())
        return false;

    var formSerialized = serializePersonalInfoForm();
    var different = $('#hdnPatSerial').val() != formSerialized;

    if (different) {
        $('#modalTitle').html(getSettingMessage("hdnSettingLeaveUnsavedPatHeader"));
        $('#modalBody').html(getSettingMessage("hdnSettingLeaveUnsavedPatMessage"));
        $('#modalOkBtn').html("Yes");
        $('#modalCancelBtn').html("No");

        $('#modalOkBtn').on("click", function () {
            if (redirectUrl) {
                parent.window.location.href = redirectUrl;
            }
            else if (reload) {
                parent.window.location.reload();
            }
        });

        $('#canLeaveModal').modal('show');

        return false;     // This is trigger first time before even show the confirmWindow, so need to return false.
    }

    return true;      // Nothing to save, then return true
}

// AX-17079.2 Back button, check if pressing browser back button can go back
function checkCanGoBackPatient() {

    var formSerialized = serializePersonalInfoForm();
    var different = $('#hdnPatSerial').val() != formSerialized;

    if (!different) {       // Nothing changed, then go back
        // go back
        if (window.history.length > 0)
            window.history.back();

        return;
    }

    $('#modalTitle').html(getSettingMessage("hdnSettingLeaveUnsavedPatHeader"));
    $('#modalBody').html(getSettingMessage("hdnSettingLeaveUnsavedPatMessage"));
    $('#modalOkBtn').html("Yes");
    $('#modalCancelBtn').html("No");

    $('#modalOkBtn').on("click", function () {
        history.back(); // no trigger
        return;
    });
    $('#canLeaveModal').on("hidden.bs.modal", function () {
        history.pushState(null, null, null);
        return;
    });

    $('#canLeaveModal').modal('show');
}

function serializePersonalInfoForm() {
    return $($("#FormPat")[0].elements).not(".ignore-serialize").not("#__EVENTTARGET").serialize();
}

function detectChanges() {
    if (!window.changed) {
        var formSerialized = serializePersonalInfoForm();
        var different = $('#hdnPatSerial').val() != formSerialized;

        if (different) {
            window.changed = true;
            $('#cancelBtn').removeClass("d-none").addClass("d-inline");
            $("#SubmitBtn").val('Save');
        }
    }
}

function searchRace_onKeyUp() {
    var input, filter, ul, li, a, i, txtValue, label;
    input = document.getElementById("searchRace");
    filter = input.value.toUpperCase();
    ul = document.getElementById("RaceMultiSelectDropdown");
    li = ul.getElementsByTagName("li");
    for (i = 1; i < li.length; i++) { // starting from the second list item because the first one is the search box
        label = li[i].getElementsByTagName("label")[0];
        txtValue = label.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}

function raceCheckbox_onchange() {
    handleRaceCheckbox();
    $('#hdnSelectedRacesId').trigger('change');
}

function handleRaceCheckbox() {
    mySelectedListItems = [];
    let mySelectedListItemsText = '';
    let mySelectedListItemsId = '';

    const chBoxes = document.querySelectorAll('.dropdown-menu input[type="checkbox"]');

    chBoxes.forEach((checkbox) => {
        if (checkbox.checked) {
            mySelectedListItems.push(checkbox.value);
            mySelectedListItemsId += checkbox.value + ',';

            const label = checkbox.parentElement.querySelector('label');
            mySelectedListItemsText += label.innerText + ', ';
        }
    });

    const dpBtn = document.getElementById('multiSelectDropdown');

    if ($('#DeclineAnswerChkBox').is(':checked')) {
        dpBtn.innerText = '';
    }
    else {
        dpBtn.innerText = mySelectedListItems.length > 0 ? mySelectedListItemsText.slice(0, -2) : 'Select';
    }

    $('#hdnSelectedRacesId').val(mySelectedListItemsId);
}

function orderRacesBySelected() {

    // order by name alphabetically
    const ul = document.getElementById('RaceMultiSelectDropdown');
    const lis = [...ul.querySelectorAll('li:not(.search)')];
    lis.forEach(li => li.remove());
    lis.sort(function (a, b) {
        var labelA = a.querySelector('label');
        var labelB = b.querySelector('label');

        if (labelA.innerText < labelB.innerText) {
            return -1;
        }
        if (labelA.innerText > labelB.innerText) {
            return 1;
        }
        return 0;
    });
    lis.forEach(li => ul.append(li));

    // order by checked
    var firstUnchecked;
    const chBoxes = document.querySelectorAll('.dropdown-menu input[type="checkbox"]');
    chBoxes.forEach((checkbox) => {
        if (!checkbox.checked && firstUnchecked == undefined) {
            firstUnchecked = checkbox.parentElement;
        }
        else if (checkbox.checked && firstUnchecked != undefined) {
            checkbox.parentNode.parentNode.insertBefore(checkbox.parentNode, firstUnchecked);
        }
    });
}

$(document).ready(function () {

    // 66825488 allows validating hidden fields
    $.validator.setDefaults({
        ignore: []

    });

    // 52499051
    // Preferred Language first dropdown item
    var preferredLangDropDownFirstItem = $("#PreferredLanguageDropDown option").eq(0);

    // 52499051
    // Define change function and blur function for Preferred Language first dropdown item
    $('#PreferredLanguageDropDown').on('change', function () {     	// AX-24898.24919.2 .change(function () {
        if ($('#hdnPrefLangInactive').val() == 'Y' && $("#PreferredLanguageDropDown option").eq(0).val() == $('#hdnPrefLangInactiveValue').val())
            preferredLangDropDownFirstItem.remove();
    }).on('blur', function () {			// AX-24898.24919.2 .blur(function() {       // At blur function check if invalid was selected and display error
        if (!ValidLanguage())
            $('#PreferredLanguageDropDown').addClass('is-invalid');
    });


    // 52499005
    // Define change function and blur function for Ethnicity first dropdown item
    $('#EthnicityDropDown').on('change', function () {     	// AX-24898.24919.2 .change(function () {
        if ($('#hdnEthnicityInactive').val() == 'Y' && $("#EthnicityDropDown option").eq(0).val() == $('#hdnEthnicityInactiveValue').val())
            $("#EthnicityDropDown option").eq(0).remove();
    }).on('blur', function () {			// AX-24898.24919.2 .blur(function() {       // At blur function check if invalid was selected and display error
        if (!ValidEthnicity())
            $('#EthnicityDropDown').addClass('is-invalid');
    });

    $('#hdnSelectedRacesId').on('change', function () {
        if (!ValidRaces())
            $('#multiSelectDropdown').addClass('is-invalid');
        else
            $('#multiSelectDropdown').removeClass('is-invalid');
    });

    $('#FormPat').validate({
        onkeyup: function () { return false; },      //39647133 Don't validate when type in field 
        onfocusout: function (element) {            // 73341708 OnBlur is not always trigger, having phone1, phone2 fields clear one of then and error is nor raised
            $(element).valid();
        },
        onsubmit: false,
        onclick: function (element) {
            if (element.id == 'EmergInfoRelation')
                return;

            $(element).valid();
        },
        errorPlacement: function () {
            return true;                            // Override error placement to not show error message beside element. Instead use highligth and unhighlight functions
        },
        rules: {    //39647133 Define rules for Phone Numbers setting special validation function
            FirstNameTxt: { validateFirstName: true }, // 42766229
            LastNameTxt: { validateLastName: true }, // 42766229
            BirthdayTxt: { validateBirthday: true },
            HomePhone: { validatePhoneNumbers: true },
            WorkPhone: { validatePhoneNumbers: true },
            WorkPhoneExt: { validatePhoneNumbers: true }, // 73341708
            OtherPhone: { validatePhoneNumbers: true },
            OtherPhoneExt: { validatePhoneNumbers: true }, // 73341708
            MobilePhone: { validatePhoneNumbers: true },
            TitleDropDown: { validateTitle: true },
            PreferredLanguageDropDown: { validatePreferredLang: true },
            EthnicityDropDown: { validateEthnicity: true },
            ContactAtDropDown: { validateContactAt: true },
            hdnSelectedRacesId: { validateRaces: true },
            CustomCode1: { validateCustomCode1: true },
            CustomCode2: { validateCustomCode2: true },
            CustomCode3: { validateCustomCode3: true },
            CustomCode4: { validateCustomCode4: true },
            CustomCode5: { validateCustomCode5: true },
            CustomCode6: { validateCustomCode6: true },
            CustomCode7: { validateCustomCode7: true },
            CustomCode8: { validateCustomCode8: true },
            CustomCode9: { validateCustomCode9: true },
            CustomCode10: { validateCustomCode10: true },
            CustomCode27: { validateCustomCode27: true },
            CustomCode28: { validateCustomCode28: true },
            CustomCode29: { validateCustomCode29: true },
            CustomCode30: { validateCustomCode30: true },
            CustomCode31: { validateCustomCode31: true },
            Address: { validateAddress: true },
            cityAutocomplete: { validateCity: true },
            StateDropDown: { validateState: true },
            CountryDropDown: { validateCountry: true },
            EmergInfoFirstName: { validateEmergInfoFirstName: true },
            EmergInfoLastName: { validateEmergInfoLastName: true },
            EmergInfoAddress: { validateEmergAddress: true },
            EmergInfoCity: { validateEmergCity: true }, // 70551316
            EmergInfoZip: { validateEmergZip: true },
            EmergInfoState: { validateEmergState: true }, // 70551316
            EmergInfoPhone: { validateEmergPhoneNumbers: true }, // 70551316
            EmergInfoAlternativePhone: { validateEmergPhoneNumbers: true }, // 70551316
            EmergInfoRelation: { validateEmergRelation: true },
            Email: { regex: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
        },
        groups: {   //39647133 Define group fields
            workPhoneGroup: "WorkPhone WorkPhoneExt",
            otherPhoneGroup: "OtherPhone OtherPhoneExt",
            emergPhoneGroup: "EmergInfoPhone EmergInfoPhoneExt", // 70551316
            emergAltPhoneGroup: "EmergInfoAlternativePhone EmergInfoAlternativePhoneExt" // 70551316
        },
        highlight: function (element) {
            var control = $(element.form).find('[id=' + element.id + ']');

            if (element.id == 'DeclineAnswerChkBox' || element.id == 'multiSelectDropdown')
                return;

            control.addClass('is-invalid');
        },
        unhighlight: function (element) {
            if (element.id == undefined || element.id == '')
                return;

            var control = $(element.form).find('[id=' + element.id + ']');

            if (element.id == 'DeclineAnswerChkBox' || element.id == 'multiSelectDropdown')
                return;

            control.removeClass('is-invalid');

            var allInvalidInputs = $('.is-invalid');
            if (allInvalidInputs.val() == undefined)
                $('#GeneralErrorMessage').css("display", "none");
        }
    });

    window.changed = false;

    $($("#FormPat")[0].elements).not(".ignore-serialize").on('change', detectChanges);

    setPageTitle("Personal Information", true);

    const chBoxes = document.querySelectorAll('.dropdown-menu input[type="checkbox"]');
    let mySelectedListItems = [];

    chBoxes.forEach((checkbox) => {
        checkbox.addEventListener('change', raceCheckbox_onchange);
    });

    if ($("#RaceParentDiv").val() != null && $("#RaceParentDiv").val() != undefined) {
        handleRaceCheckbox();

        $("#searchRace").on("search", function () {
            searchRace_onKeyUp();
        });
    }

    // AX-17079
    var formSerialize = serializePersonalInfoForm();
    $('#hdnPatSerial').val(formSerialize);

    var firstInvalidInput = $('.is-invalid:first');
    if (firstInvalidInput.val() != undefined) {
        var position = parseInt(firstInvalidInput.offset().top);
        if (!isNaN(position)) {
            setTimeout(() => window.scrollTo({ top: position - 30, left: 0, behavior: "instant" }), 100);
        }
    }

    parent.closeModalSpinner();

});
