(function () {
    var globalOptions;
    var playCoverHelper, crudeApi;
    var playCover, playCoverStatusWatcher;

    Mediasite.loadScripts(
        [
            "Javascript/Scripts/BabelFish.js",
            "Cover/MediasitePlayCover.js",
            "Javascript/Scripts/SFMP.MiniUtility.js",
            "Javascript/Scripts/Mediasite.Player.ApiOrigin.js",
            "Javascript/Scripts/PlayCoverHelper.js",
        ],
        function () {
            doWhenDOMReady(function () {
                globalOptions = getGlobalOptions();

                initLocalization(function () {
                    loadCoverOrPlayer();
                });
            });
        }
    );


    

    function initLocalization(completedCallback) {
        var babelFish = new BabelFish({
            dictionary: window.LocalizedDictionary,
            ready: function () {
                Mediasite.Player.Localization.initialize();
                completedCallback();
            }
        });
        Mediasite.babel = babelFish.translate;
    }

    function loadCoverOrPlayer(loadPlayerFunc) {
        if (!isPresentationId(globalOptions.ResourceId)) {
            // Skip the Play Cover, if the resource isn't a presentation.
            // This is likely a player preview.
            loadThePlayer();
            return;
        }

        playCoverHelper = Mediasite.Player.PlayCoverHelper.create(globalOptions.DataProviderType, globalOptions.ServicePath);

        playCoverHelper.getPlayCoverInfo(globalOptions.ResourceId, function (info) {
            if (!info) {
                throw new Error("Could not get play cover info.");
            }

            if (playCoverHelper.shouldShowPlayCover(info)) { 
                loadPlayCover(info);
            } else {
                loadThePlayer();
            }
        });
    }

    function loadPlayCover(info) {
        var clickAction = function () {
            // Create some video elements and call play() for each.
            // This is done RIGHT HERE to be immediately after a user action (click).
            var videoElements = createSomeVideoElements(3);

            playCoverStatusWatcher.destroy();
            playCover.destroy();

            crudeApi.raisePlayCoverClick();

            loadThePlayer(videoElements);
        };

        playCover = playCoverHelper.makePlayCover(info, clickAction);
        playCover.appendToDom(document.body);

        playCover.ready(function () {
            crudeApi = Mediasite.Player.PlayCoverHelper.createCrudeApi(window, window.parent, info.AllowedPlayerIFrameAPISites);
            crudeApi.onSetPlayCoverCustomHtml = playCoverHelper.makeSetPlayCoverCustomHtmlCallback(playCover);
            crudeApi.raisePlayCoverReady();
        });
        
        playCoverStatusWatcher = MediasitePlayCover.createStatusWatcher(playCover, playCoverHelper.makePresentationStatusGetter(globalOptions.ResourceId));
    }

    function loadThePlayer(videoElements) {
        Mediasite.loadScripts(
            [
                "Javascript/Scripts/3rdParty/jquery.js",
                "Javascript/Scripts/3rdParty/modernizr.js",
                "Javascript/Scripts/3rdParty/jquery-ui.js",
                "Javascript/Scripts/3rdParty/json2.js",
            ],
            function () {
                var scripts = [
                    "Javascript/Scripts/3rdParty/dash.all.debug.js",
                    "Javascript/Scripts/3rdParty/hls.js",
                    "Javascript/Scripts/3rdParty/Silverlight.js",
                    "Javascript/Scripts/jquery.whenAll.js",
                    "Javascript/Scripts/IosAppDetection.js",
                    "Javascript/Scripts/Mediasite.Core.js",
                    "Javascript/Scripts/Mediasite.Geometry.js",
                    "Javascript/Scripts/ImageSizeProvider.js",
                    "Javascript/Scripts/Mediasite.Css.js",
                    "Javascript/Scripts/Mediasite.Player.Core.js",
                    "Javascript/Scripts/Mediasite.LogViewer.js",
                    "Javascript/Scripts/Mediasite.Player.API.js",
                    "Javascript/Scripts/Mediasite.Player.Reporting.js",
                    "Javascript/Scripts/Mediasite.Player.APIBroker.js",
                    "Javascript/Scripts/Mediasite.Player.Model.js",
                    "Javascript/Scripts/Mediasite.Player.BookmarkStorage.js",
                    "Javascript/Scripts/Mediasite.Player.UserActivation.js",
                    "Javascript/Scripts/Mediasite.MediaPlayer.js",
                    "Javascript/Scripts/MediaPlayers/Html5MediaPlayer.js",
                    "Javascript/Scripts/MediaPlayers/HlsDotJsMediaPlayer.js",
                    "Javascript/Scripts/MediaPlayers/Html5DashMediaPlayer.js",
                    "Javascript/Scripts/MediaPlayers/Html5RampMediaPlayer.js",
                    "Javascript/Scripts/MediaPlayers/SilverlightMediaPlayer.js",
                    "Javascript/Scripts/MediaPlayers/FlashMediaPlayer.js",
                    "Javascript/Scripts/MediaPlayers/WindowsMediaPlayer.js",
                    "Javascript/Scripts/jquery.ui.messagedisplay.js",
                    "Javascript/Scripts/Mediasite.Player.StreamViewer.js",
                    "Javascript/Scripts/Mediasite.Player.DataProvider.js",
                    "Javascript/Scripts/MediasitePlayer.js",
                    "Javascript/Scripts/Mediasite.Player.AriaMessageFactory.js",
                    "Javascript/Scripts/3rdParty/swfobject.js",
                    "Javascript/Scripts/Mediasite.Player.ConvivaConfigurator.js",
                    "Javascript/Scripts/Mediasite.Player.Configurations.js"
                ];

                if (!window.MediaSource) {
                    // Old browsers (I'm looking at you IE8) may choke on the 
                    // dash.js and hsl.js libraries. Only load those libraries 
                    // if the browser supports Media Source Extensions.
                    scripts.splice(0, 2);
                }

                Mediasite.loadScripts(
                    scripts,
                    function () {
                        globalOptions.videoElementsForPool = videoElements;
                        var sfmPlayer = new Mediasite.Player.MediasitePlayer(globalOptions);
                    }
                );
            }
        );
    }

    function doWhenDOMReady(func) {
        var readyState = document && document.readyState;
        if (readyState === "interactive" || readyState === "complete") {
            func();
        } else {
            document.addEventListener("DOMContentLoaded", function (event) {
                func();
            });
        }
    }

    function getGlobalOptions() {
        var container = document.getElementById("GlobalData");

        function textBySelector(selector) {
            var elem = document.querySelector(selector);
            return elem && elem.innerText;
        }

        var options = {
            PlayerContentId: "PlayerContent",
            DataProviderType: parseInt(textBySelector("#DataProviderType")),
            ResourceId: textBySelector("#GlobalData #ResourceId"),
            ServicePath: textBySelector("#GlobalData #ServicePath"),
            UrlReferrer: textBySelector("#GlobalData #UrlReferrer"),
            CustomHeader: textBySelector("#GlobalData #CustomHeader")
        };

        return options;
    }

    function isPresentationId(resourceId) {
        return typeof resourceId === "string" && /[0-9A-F]{32,32}1d/i.test(resourceId);
    }

    function createSomeVideoElements(howMany) {
        var i, vid;
        var elements = [];

        function callPlayAndRemove(vid) {
            var promise = vid.play();
            if (promise) {
                promise.catch(function (error) { });
                document.body.removeChild(vid);
            } else {
                document.body.removeChild(vid);
            }
        }

        for (i = 0; i < howMany; i += 1) {
            vid = document.createElement("video");
            document.body.appendChild(vid);

            callPlayAndRemove(vid);
            elements.push(vid);
        }

        return elements;
    }
})();

