const initMatchHeight = () => {
    window.addEventListener('load', () => {
        matchHeight('.equal-height');
    });
    window.addEventListener('resize', () => {
        matchHeight('.equal-height');
    });
    window.addEventListener('contentResize', () => {
        matchHeight('.equal-height');
    });
    window.dispatchEvent(new Event('contentResize'));
}

const setHeight = (el, val) => {
    if (typeof val === 'function') val = val();
    if (typeof val === 'string') el.style.height = val;
    else el.style.height = val + 'px';
}

const matchHeight = (selector) => {
    const rowDivs = [];
    let currentTallest = 0;
    let currentRowStart;
    let topPosition = 0;
    let currentDiv;

    const elements = document.querySelectorAll(selector);

    for (const el of elements) {
        el.style.height = 'auto';
        topPosition = el.offsetTop;

        if (currentRowStart === undefined) {
            currentRowStart = topPosition;
        }

        if (currentRowStart !== topPosition) { // new row
            for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
                setHeight(rowDivs[currentDiv], currentTallest)
            }
            rowDivs.length = 0;
            currentRowStart = topPosition;
            currentTallest = parseFloat(getComputedStyle(el, null).height.replace('px', ''))
            rowDivs.push(el);
        } else { // same row
            rowDivs.push(el);
            currentTallest = (currentTallest < parseFloat(getComputedStyle(el, null).height.replace('px', ''))) ? (parseFloat(getComputedStyle(el, null).height.replace('px', ''))) : (currentTallest);
        }
    }

    for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
        setHeight(rowDivs[currentDiv], currentTallest)
    }
}

export { initMatchHeight };
