const isAsciiCompatible = (s) => {
    /* if not every character is within extended ASCII character set (0-255 in hexadecimal) */
    var maxAsciiValue = 255;
    return [...s].every(
        (c) =>
            c.charCodeAt(0) <= maxAsciiValue ||
            c.charAt(0) == "'|| UNISTR('\2018') ||'" ||
            c.charAt(0) == "'|| UNISTR('\2019') ||'"
    );
}

const extendValidationCheck = () => {
    $(".needs-validation")
        .find("input")
        .on("input", function () {
            /* check validity and change class */
            $(this).removeClass("is-valid is-invalid");
            $(this).addClass(
                this.checkValidity() &&
                    isAsciiCompatible(this.value) &&
                    this.value.trim().length > 0
                    ? "is-valid"
                    : "is-invalid"
            );
        });
}

const setDefaultDate = (targetField) => {
    const defaultAxiumDate = "1980-01-01";
    if (!targetField.value) {
        targetField.value = defaultAxiumDate;
    }
}

const setPageTitle = (title, fromIFrame = false, parentTitle = undefined) => {
    const setTitle = (document) => {
        const pageTitle = document.getElementById("pagetitle");
        if (pageTitle) {
            pageTitle.innerHTML = title;
        }
        
        // Also update the title tag
        const titleTag = document.querySelector("title");
        const organizationName = document.getElementById("vOrganizationName")?.textContent;
        
        if (titleTag && organizationName) {
            titleTag.innerHTML = (parentTitle || title) + " - " + organizationName;
        }
    }
    
    if (!fromIFrame) {
        setTitle(document); return;
    }
    
    const parentDoc = window.parent.document;
    if (parentDoc) {
        setTitle(parentDoc);
        
        // Update the title attribute of the iframe
        parentDoc.getElementById("iFrameId")
            ?.setAttribute("title", title);
    }
}

function replaceAndAttachEventListener(selector, event, handler) {
    const originalElement = document.querySelector(selector);
    if (!originalElement) return;

    const clonedElement = originalElement.cloneNode(true);
    originalElement.parentNode.replaceChild(clonedElement, originalElement);
    clonedElement.addEventListener(event, handler, {once: true});
}

// Ping parent window to prevent session timeout, see Includes/Scripts/PA2.0/autologout.js
// This is intended to be used in iframes (since all iframes are using this script, if not they should)
$(document).on('active.idleTimer', function () {
    window.parent.postMessage('ping','*');
});

$(document).ready(function () {
    $(this).on('mousemove keypress scroll', function () {
        window.parent.postMessage('ping', '*');
    });
});

window.addEventListener('pageshow', function (event) {
    if (event.persisted) {
        closeModalSpinner();
    }
});