// embedder-iframe.js
//
// This is the JS that gets loaded by external sites to enable the embedder.
// To maintain backwards compatibility, it needs to be served at
// https://amara.org/embedder-iframe.js -- which is why it's in the templates
// directory rather than assets.
(function() {
    // This must be done when the js file is first loaded
    var scriptFiles = document.getElementsByTagName("script");
    var THIS_JS_FILE = scriptFiles[scriptFiles.length-1].src;

    // Map iframe names to the HTMLIFrameElements
    var iframeCounter = 0;
    var iframeMap = {};

    if (window.amaraEmbedderLoaded == undefined) {
        window.amaraEmbedderLoaded = true;
    } else {
        return;
    }

    function findNewEmbedDivs() {
        var embeds = document.getElementsByClassName("amara-embed");
        for(var i = 0; i < embeds.length; i++) {
            if(embeds[i].dataset.amaraEmbed === undefined) {
                embeds[i].dataset.amaraEmbed = true;
                createEmbedder(embeds[i]);
            }
        }
    }

    function createEmbedder(elt) {
        var iframe = document.createElement("IFRAME");
        var data = calcData(elt);
        setupWidthAndPaddingTop(elt, data);
        elt.style.height = "37px";
        elt.style.position = "relative";
        elt.style.boxSizing = "content-box";
        iframe.src = createUrl('/embedder-widget-iframe/?data=' + formatData(data));
        iframe.style.position = "absolute";
        iframe.style.left = "0";
        iframe.style.top = "0";
        iframe.style.width = "100%";
        iframe.style.height = "100%";
        iframe.style.border = "none";
        iframe.style.overflow = "hidden";
        iframe.scrolling = "no";
        iframe.setAttribute("allowfullscreen", true);
        iframe.name = 'amara-embedder-' + iframeCounter++;
        elt.appendChild(iframe);
        iframeMap[iframe.name] = iframe;
        addLoadingBackground(elt);
    }

    function setupWidthAndPaddingTop(elt, data) {
        // Set the width/paddingTop styles for our container element.
        // The idea here is to make paddingTop equal to the height of the video
        // player.  This allows us to use the CSS trick to make the height
        // proportional to the width when the width is 100% (see the else case
        // below).  We the use the height style to allocate enough space for
        // the other elements (toolbar and optionally the transcript viewer).
        if(data.width) {
            // Manual width specified, set the height to exactly 9/16th of this.
            if(data.width.match(/\d+$/)) {
                elt.style.width = parseInt(data.width, 10) + 'px';
            } else {
                elt.style.width = data.width;
            }
            var height = Math.round(elt.getBoundingClientRect().width * 9 / 16);
            elt.style.paddingTop = height + 'px';
        } else {
            // No width specified, set the height to 56.25%, which will make it
            // 9/16ths of the container width.
            elt.style.width = "100%";
            elt.style.paddingTop = "56.25%";
        }
    }

    function calcData(elt) {
        var data = {};
        for(var i = 0; i < elt.attributes.length; i++) {
            var attr = elt.attributes[i];
            if(attr.name.startsWith('data-')) {
                var name = attr.name.substring(5).replace(/-/g, '_');
                var value = attr.value;
                if(value == "0" || value == "false") {
                    value = false;
                } else if(value == "1" || value == "true") {
                    value = true;
                } else if(value == "null") {
                    value = null;
                }
                data[name] = value;
            }
        }
        return data;
    }

    function formatData(data) {
        return encodeURIComponent(JSON.stringify(data));
    }


    function addLoadingBackground(elt) {
        elt.style.backgroundColor = '#1B1C1D';
        elt.style.backgroundImage = 'url(https://static.amara.org/b51edc9e/images/embedder/loading.gif)';
        elt.style.backgroundPosition = 'center center';
        elt.style.backgroundRepeat = 'no-repeat';
    }

    function adjustHeight(iframe, transcriptEnabled) {
        var container = iframe.parentNode;
        if(transcriptEnabled) {
            container.style.height = "377px";
        } else {
            container.style.height = "37px";
        }
    }

    function amaraDomain() {
        var parser = document.createElement('a');
        parser.href = THIS_JS_FILE;
        return parser.protocol + '//' + parser.host;
    }

    function createUrl(path) {
        return amaraDomain() + path;
    }

    function onMessage(evt) {
        if(evt.origin != amaraDomain()) {
            return;
        }
        var iframe = iframeMap[evt.data.name];
        if(evt.data.type == 'transcriptEnabled') {
            adjustHeight(iframe, evt.data.enabled);
        }
    }

    var amaraEmbedderInit = function() {
        window.addEventListener('message', onMessage);
        findNewEmbedDivs();
        var nodesAddedAndRemovedCallback = function(records) {
            findNewEmbedDivs();
        };
        new MutationObserver(nodesAddedAndRemovedCallback).observe(document.body, { childList: true, subtree: true });
    };
    window.amaraEmbedderInit = amaraEmbedderInit;

    window.addEventListener('load', window.amaraEmbedderInit);
}).call(this);
