(function() {
    'use strict';

    dashboard.moduleUtils = dashboard.moduleUtils || {};

    dashboard.moduleUtils.getModule = function(namespaceString) {
        var parts = namespaceString.split('.');
        var result = parts.reduce(function(crnt, next){
            return crnt && crnt[next];
        }, window);
        return result;
    };

    var ongoingModuleRequests = {};

    dashboard.moduleUtils.ensureLoaded = function(namespaceString) {
        var existingNamespace = this.getModule(namespaceString);
        if (existingNamespace) {
            return $.Deferred().resolve(existingNamespace);
        }

        if (ongoingModuleRequests[namespaceString]) {
            return ongoingModuleRequests[namespaceString];
        }

        var modulePromise = $.getScript(namespaceString.toLowerCase() + '.js')
            .always(function() {
                ongoingModuleRequests[namespaceString] = null;
            }).then(function() {
                return dashboard.moduleUtils.getModule(namespaceString);
            });
        ongoingModuleRequests[namespaceString] = modulePromise;
        return modulePromise;
    };

})();
