"use strict";

// Container for loading prep.
var loader = {};
loader.auth = {};


//IE polyfill
if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (searchString, position) {
        position = position || 0;
        return this.indexOf(searchString, position) === position;
    };
}

//IE polyfill
if (!String.prototype.includes) {
    String.prototype.includes = function (search, start) {
        if (typeof start !== 'number') {
            start = 0;
        }

        if (start + search.length > this.length) {
            return false;
        } else {
            return this.indexOf(search, start) !== -1;
        }
    };
}

function isIE() {
    //removing this piece of code to not cache the content
    return true;
}

// Reads the settings from the given source element.
function readSettingsFrom(sourceElementId) {
    // Gather and validate settings.
    loader.loadTag = document.getElementById(sourceElementId);
    if (typeof loader.loadTag === "undefined") { console.log("Failed to find loader script."); }

    loader.whichPage = loader.loadTag.getAttribute("data-which-page");
    loader.rootUrl = loader.loadTag.getAttribute("data-root-url");
    loader.controllerPath = loader.loadTag.getAttribute("data-controller-path");
    loader.controllerName = loader.loadTag.getAttribute("data-controller-name");
    loader.controller = loader.loadTag.getAttribute("data-controller");
    if (typeof loader.whichPage === "undefined") { console.log("Failed to find which page."); }
    if (typeof loader.rootUrl === "undefined") { console.log("Failed to find root URL."); }

    loader.localization = [
        "common",
        "bing",
        "concernRoot",
        "onlineSafety",
        "privacy",
        "countries",
        "dmca",
        "healthVault",
        "partnerEscalation",
        "reinstateContent",
        "officeViolation",
        "scam"
    ];

    if (loader.loadTag.getAttribute("data-localization")) {
        loader.localization = loader.loadTag.getAttribute("data-localization").split(" ");
    }

    loader.requireAuth = loader.loadTag.getAttribute("data-require-auth");
    loader.hasAuth = loader.loadTag.getAttribute("data-hasAuth");
    loader.auth.redirectUrl = loader.loadTag.getAttribute("data-auth-redirect-url") || window.location;
}

// Configures RequireJS based on the current settings.
function configureRequireJs() {
    let urlArgs = "";

    if (isIE()) {
        urlArgs = "iecachebust=" + (new Date()).getTime();
    }

    let scriptRoot = loader.rootUrl + "/Scripts/app/";

    define("jquery", function () { return $; });

    requirejs.config({
        baseUrl: scriptRoot,
        urlArgs: urlArgs,
        map: { "*": { "spin.js": "spin" } },
        paths: {
            "spin": loader.rootUrl + '/Scripts/packages/spin.min',
            "knockout": loader.rootUrl + '/Scripts/packages/knockout-min',
            "knockout.validation": loader.rootUrl + '/Scripts/packages/knockout.validation.min',
            "moment": loader.rootUrl + '/Scripts/packages/moment.min',
            api: "../api",
            "i18next": loader.rootUrl + '/Scripts/packages/i18next.min',
            "i18next-xhr-backend": loader.rootUrl + '/Scripts/packages/i18nextXHRBackend.min',
            "fingerprintjs2": loader.rootUrl + '/Scripts/packages/getPrint',
            "bluebird": loader.rootUrl + '/Scripts/packages/bluebird.min',
            "better-dom-datepicker": loader.rootUrl + '/Scripts/packages/betterDOMDatepicker',
            "URLSearchParams": loader.rootUrl + '/Scripts/packages/url-search-params'
        }
    });
}

function actuallyStart() {
    // run configuration
    readSettingsFrom("loader-script");

    var load1DS = document.createElement('script');
    load1DS.src = loader.rootUrl + '/Scripts/1DS.js';
    load1DS.type = "text/javascript";
    document.getElementsByTagName('head')[0].appendChild(load1DS);

    configureRequireJs();

    var datepickerStyle = document.createElement('link');
    datepickerStyle.rel = 'stylesheet';
    datepickerStyle.type = 'text/css';
    datepickerStyle.href = 'https://www.w3.org/TR/wai-aria-practices/examples/dialog-modal/css/datepicker.css';
    document.head.appendChild(datepickerStyle);

    var loaderWithBluebirdRequire = document.createElement('script');
    loaderWithBluebirdRequire.src = loader.rootUrl + '/Scripts/loaderRT.js';
    loaderWithBluebirdRequire.type = 'text/javascript';
    document.body.appendChild(loaderWithBluebirdRequire);
}

// The actual initialization.
document.addEventListener("DOMContentLoaded", function (event) {
    actuallyStart();
});