$LAB.setGlobalDefaults({ CacheBust: false, UseLocalXHR: true, AlwaysPreserveOrder: true, Debug: false });
$LAB.setGlobalDefaults({'ErrorHandler': function(err){
    throw err;
}
});

window.Mediasite = window.Mediasite || {};


Mediasite.getVersionToken = (function () {
    var wasVersionDetermined = false;
    var version;

    function getUrlFromScriptElement() {
        var scriptElement = document.getElementById('loadScriptElement');

        return scriptElement && scriptElement.src;
    }

    function getUrlFromDocument() {
        return document && document.location && document.location.href;
    }

    function getVersionFromUrl(url) {
        var found;
        var pattern = /(?:[?&]version=)(\d+)(?:[&#]|$)/i;

        if (typeof url !== 'string') {
            return;
        }

        found = url.match(pattern);
        if (!found || found.length < 2) {
            return;
        }

        return found[1];
    }

    function getVersionToken() {
        var fromDoc, fromTag;
        if (!wasVersionDetermined) {
            version = getVersionFromUrl(getUrlFromScriptElement()) || getVersionFromUrl(getUrlFromDocument());
            wasVersionDetermined = true;
        }

        return version;
    }

    return getVersionToken;
})();


Mediasite.loadScripts = (function () {
    var versionValue = Mediasite.getVersionToken();
    var versionParamName = 'version';

    function getNextQueryJoinCharacter(path) {
        return (path.indexOf('?') > -1) ? '&' : '?';
    }

    function makeVersionedScriptPath(scriptPath) {
        if (!versionValue) {
            return scriptPath;
        }

        return betterPath = scriptPath + getNextQueryJoinCharacter(scriptPath) + versionParamName + '=' + versionValue;
    }

    function versionArrayOfScriptPaths(input) {
        var i;
        var output = [];

        for (i = 0; i < input.length; i += 1) {
            output[i] = makeVersionedScriptPath(input[i]);
        }

        return output;
    }

    function versionAllScriptPaths(input) {
        if ('string' === typeof input) {
            return makeVersionedScriptPath(input);
        } else if ('[object Array]' === Object.prototype.toString.call(input)) {
            return versionArrayOfScriptPaths(input);
        }
    }

    function loadScripts(scriptsArray, loadedCallback) {
        var labChain;
        scriptsArray = versionAllScriptPaths(scriptsArray);
        labChain = $LAB.script(scriptsArray);
        if (typeof loadedCallback === 'function') {
            labChain.wait(loadedCallback);
        }
    }

    return loadScripts;
})();
