
// we have to set currentScript here, because findAndLoadPlayers() is called during an event AFTER this script is no longer the "current" script.
// we have to use currentScript, because going off window.location stuff doesn't work for embeds.
// console.log("document currentscript", document.currentScript);
var embedScriptLocation = document.currentScript.src;

function findAndLoadPlayers() {
    /* Content protection */
    var url = window.location.href; // window.location.hostname;

    /* Get and loop through all players (var tags) */
    var allPlayers = document.getElementsByTagName("var");
    for (var i = 0; i < allPlayers.length; i++) loadNext(i);

    function loadNext(i){
        /* Which presentation are we loading? */
        curPresID = allPlayers[i].getAttribute('data-presentation');

        if (curPresID) {
            if (!allPlayers[i].getAttribute('data-loaded')) {
                /* Mark Var as Loaded (Prevents running again later) */
                allPlayers[i].setAttribute('data-loaded', 'true');

                /* Create iframe */
                var playerframe = document.createElement('iframe');

                /* Assign src to iframe */
                console.log("pre source url:",url);
                var sourceURL = window.btoa(url).replace(/\=+$/, '').replace('/', '_');
                console.log("post source url:",sourceURL);
                /* change whitelabel url based on embed.js location; including periods bc unlikely to repeat those in the path even if other keywords are present */
                var subdomain = "share";
                if (embedScriptLocation.indexOf("local.") !== - 1) {
                  subdomain = "local";
                } else if (embedScriptLocation.indexOf("test.") !== - 1) {
                  subdomain = "test";
                }
                playerframe.setAttribute('src', 'https://'+subdomain+'.rendia.com/whitelabel/load/'+sourceURL+'/'+curPresID);

                // hey can we just ajax some metadata? Also, no jquery, we have to use basic JS.
                var req = new XMLHttpRequest();
                req.responseType = 'json';
                req.open('GET', 'https://'+subdomain+'.rendia.com/server/player/metadata/' + curPresID, true);
                req.onload  = function() {
                   var jsonResponse = req.response;
                   console.log('player metadata', jsonResponse);
                   if (jsonResponse.title != null) {
                     playerframe.setAttribute('title', jsonResponse.title);
                     playerframe.setAttribute('aria-label', jsonResponse.title);
                   }
                };
                req.send(null);
                // playerframe.setAttribute('itemscope', '');
                // playerframe.setAttribute('itemtype', 'http://schema.org/VideoObject');

                /* create schema.org meta tags */
                // var metaDescription = document.createElement('meta');
                // metaDescription.setAttribute('itemprop', 'description');
                // metaDescription.setAttribute('content', 'Video content for educating patients about their health.');
                // var metaName = document.createElement('meta');
                // metaName.setAttribute('itemprop', 'name');
                // metaName.setAttribute('content', 'Echo by Eyemaginations');
                // var metaThumb = document.createElement('meta');
                // metaThumb.setAttribute('itemprop', 'thumbnailUrl');
                // metaThumb.setAttribute('content', 'https://showecho.com');
                // var metaDate = document.createElement('meta');
                // metaDate.setAttribute('itemprop', 'uploadDate');
                // metaDate.setAttribute('content', '2016-01-01');

                /* Assign misc attributes to iframe */
                playerframe.setAttribute('frameBorder', 0);

                playerframe.setAttribute('title', 'Rendia Embed Player');
                playerframe.setAttribute('aria-label', 'Rendia Embed Player');

                playerframe.setAttribute('onload', 'this.style.visibility = "visible"');

                playerframe.setAttribute('scrolling', 'no');

                playerframe.setAttribute('autoplay', 'false');

                // playerframe.setAttribute('allow', 'autoplay');

                playerframe.setAttribute('allow', 'web-share');

                /* Create width and height for iframe */
                var width = document.createAttribute('width');
                var height = document.createAttribute('height');

                /* New players have a style tag on the <var> to take care of the sizing */
                varStyle = allPlayers[i].getAttribute('style');

                /* Old players used data-width on the <var> for responsiveness */
                var customWidth = allPlayers[i].getAttribute('data-width');

                /* Really old player or messed up player with no sizing, default to a size */
                if(!customWidth) customWidth = 648;

                /* Rather old player, use the data-width given */
                if(!varStyle){
                    width.nodeValue = customWidth;
                    playerframe.setAttributeNode(width);
                    height.nodeValue = (customWidth * 0.5625) + 4;
                    playerframe.setAttributeNode(height);
                    playerframe.style.border = "none";

                    /* And finally, append the iframe to the <var> */
                    allPlayers[i].appendChild(playerframe);
                } else { //New player, let the style tag handle it all
                    width.nodeValue = '100%';
                    playerframe.setAttributeNode(width);
                    height.nodeValue = '100%';
                    playerframe.setAttributeNode(height);

                    /* Style the <var> to be responsive - ADS updating for IE8 compatibility */
                    allPlayers[i].style.display = "block";

                    /* Create responsive div */
                    var playercontainer = document.createElement('div');
                    playercontainer.style.paddingBottom = "56.25%";
                    playercontainer.style.position = "relative";

                    /* Style the iframe to be responsive */
                    playerframe.style.position = "absolute";
                    playerframe.style.top = "0";
                    playerframe.style.left = "0";
                    playerframe.style.border = "none";
                    // playerframe.style.visibility = "hidden"; //Prevent white flash but also prevents placeholder background image
                    playerframe.style.background = "#F5F5F5 url('https://content.rendia.com/leo/rendia_embed_r.png') no-repeat center";

                    /* SEO Add links to theater page */
                    /* //DOESN'T HELP WITH SEO, MAKES BROKEN LINKS ANYWAY...
                        var seoLink = document.createElement('a');
                        var seoHREF = document.createAttribute('href');
                        var seoStyle = document.createAttribute('style');
                        seoHREF.nodeValue = document.location.origin + '/theater/' + curPresID;
                        seoStyle.nodeValue = 'display: none;';
                        seoLink.setAttributeNode(seoHREF);
                        seoLink.setAttributeNode(seoStyle);
                        seoLink.innerHTML = 'View this Video';
                        // playerframe.innerHTML = seoLink;
                        playercontainer.appendChild(seoLink);
                    */

                    /* And finally, append the iframe to a responsive <div> then to the <var> */
                    allPlayers[i].style.paddingBottom = '0'; //Ensure we remove the height fix from the embed code if it exists
                    allPlayers[i].appendChild(playercontainer);
                    playercontainer.appendChild(playerframe);
                    // playerframe.appendChild(metaDescription);
                    // playerframe.appendChild(metaName);
                    // playerframe.appendChild(metaThumb);
                    // playerframe.appendChild(metaDate);
                }
                // attach postMessage stuff so we can communicate to the iframe when on crossdomain (which is like, all the time)
                window.addEventListener('message', function(e) {
                    console.log('got message from child', e.data);
                    if (e.data === 'ready') {
                      console.log('posting url from parent');
                      playerframe.contentWindow.postMessage({rendia: true, url: sourceURL}, '*');
                    }
                }, false);
                // failed parent click in an attempt to get autoplay working
                // window.addEventListener('click', userGestured, false);
                //
                // function userGestured() {
                //   console.log('posting click from parent');
                //   playerframe.contentWindow.postMessage({rendiaclick: true}, '*');
                //   window.removeEventListener('click', userGestured);
                // }
            }
        }
    }
}

if (typeof pageLoadedAlready === 'undefined') {
    window.addEventListener ?
        window.addEventListener("load", findAndLoadPlayers, false) :
            window.attachEvent && window.attachEvent("onload", findAndLoadPlayers);

    var pageLoadedAlready = true;
} else findAndLoadPlayers();
