console.log('WE LOVE TYPO3');

// ********************** //
// INTERSECTION OBSERVERS //
// ********************** //

/* Video Autoplay */

let videos = document.querySelectorAll('.amadeusnext_caseanzahl video');
const theme_dark = window.matchMedia('(prefers-color-scheme: dark)').matches;

if (videos.length > 0) {
    var rmargins;
    var percentage;

    if (window.innerWidth < 768) {
        percentage = 0.9;
        rmargins = "0px";
    } else {
        percentage= 0.4;
        rmargins = "0px 0px -45% 0px";
    }

    const videoObserver = new IntersectionObserver(voCallback, {threshold: percentage, rootMargin: rmargins});

    videos.forEach((i) => {
        videoObserver.observe(i);
    });

    function voCallback(entries) {
        const [entry] = entries;

        if (entry.isIntersecting) {
            entry.target.play();
        } else {
            entry.target.pause();
        }
    }
}


/* Inverted Logo */

const header = document.querySelector('header');
let sections = document.querySelectorAll('main section');
const sectionObserver = new IntersectionObserver(soCallback, {threshold: 0.1, rootMargin: "0px 0px -80% 0px"});

sections.forEach((i) => {
    sectionObserver.observe(i);
});

function soCallback(entries) {
    const [entry] = entries;

    if (entry.isIntersecting) {
        let bgClass = entry.target.querySelector('div').className;

        if (bgClass.includes("bg-auto")) {
            let bgCol = colorValues(getComputedStyle(entry.target.querySelector('div'))['backgroundColor']);

            if (contrastColor(bgCol,1) === '#FFFFFF') {
                header.classList.add('inverse');
            } else {
                header.classList.remove('inverse');
            }
        } else {
            if (bgClass.includes("bg-dark")) {
                header.classList.add('inverse');
            } else {
                header.classList.remove('inverse');
            }
        }
    }
}


// ******************* //
// AUXILIARY FUNCTIONS //
// ******************* //

/**
 * Returns the inverse color (or black/white) for any given color as a HEX-String
 * @param {number[]} channels
 * @param {int|bool} bw
 * @returns {string|string}
 */
function contrastColor(channels, bw) {
    // Catch transparent background color, apply color scheme
    if (channels[3] == 0 && !theme_dark) {
        return '#000000';
    }

    if (bw) {
        // https://stackoverflow.com/a/3943023/112731
        return (channels[0] * 0.299 + channels[1] * 0.587 + channels[2] * 0.114) > 186
            ? '#000000'
            : '#FFFFFF';
    }
    // invert color components
    r = (255 - channels[0]).toString(16);
    g = (255 - channels[1]).toString(16);
    b = (255 - channels[2]).toString(16);
    // pad each with zeros and return
    return "#" + padZero(r) + padZero(g) + padZero(b);
}

/**
 * Returns an array of [r,g,b,a] from any valid color. If failed returns undefined
 * @param {string} color
 * @returns {(number|number|number)[]|number[]}
 */
function colorValues(color) {
    if (color === '')
        return;

    if (color.toLowerCase() === 'transparent')
        return [0, 0, 0, 0];

    if (color[0] === '#')
    {
        if (color.length < 7)
        {
            // convert #RGB and #RGBA to #RRGGBB and #RRGGBBAA
            color = '#' + color[1] + color[1] + color[2] + color[2] + color[3] + color[3] + (color.length > 4 ? color[4] + color[4] : '');
        }
        return [parseInt(color.substr(1, 2), 16),
            parseInt(color.substr(3, 2), 16),
            parseInt(color.substr(5, 2), 16),
            color.length > 7 ? parseInt(color.substr(7, 2), 16)/255 : 1];
    }

    if (color.indexOf('rgb') === -1)
    {
        // convert named colors
        var temp_elem = document.body.appendChild(document.createElement('fictum')); // intentionally use unknown tag to lower chances of css rule override with !important
        var flag = 'rgb(1, 2, 3)'; // this flag tested on chrome 59, ff 53, ie9, ie10, ie11, edge 14
        temp_elem.style.color = flag;
        if (temp_elem.style.color !== flag)
            return; // color set failed - some monstrous css rule is probably taking over the color of our object
        temp_elem.style.color = color;
        if (temp_elem.style.color === flag || temp_elem.style.color === '')
            return; // color parse failed
        color = getComputedStyle(temp_elem).color;
        document.body.removeChild(temp_elem);
    }

    if (color.indexOf('rgb') === 0)
    {
        if (color.indexOf('rgba') === -1)
            color += ',1'; // convert 'rgb(R,G,B)' to 'rgb(R,G,B)A' which looks awful but will pass the regxep below
        return color.match(/[\.\d]+/g).map(function (a)
        {
            return +a
        });
    }
}
