;(function(window, document, SRLiveVar){
    var SRLive = window[SRLiveVar] = window[SRLiveVar] || {},
        SRLIVE_LOADED = 2,
        SRLIVE_LOADING = 1,
        SRLIVE_NOT_LOADED = 0,
        SRLiveLoadedStatus = SRLIVE_NOT_LOADED,
        scriptAssets = "assets/itf/itf/js/itf.js".split(':'),  // jshint ignore:line
        styleAssets = "".split(':'),  // jshint ignore:line
        widgetsToLoad = {},
        currentScriptUrl = '',
        currentScriptTag = false,
        preferHttps = '1' === '1',
        debugLevel = parseInt('6',10),
        applicationUrl = '',
        autoInitAttributeValue = false,
        loadCss = true,
        loadJavascript = true,
        initMatchId = false,
        initTimezone = '',
        applicationPath = '',
        currentScript = document.currentScript,
        queryRoot,
        _timing = {
            wlLoaded : +(new Date())
        };


    if (currentScript && (currentScript.src || currentScript.id == 'sr-widgetloader')) {
        currentScriptTag = currentScript;
        autoInitAttributeValue = (!!currentScript.getAttribute('data-autoInit')) || false;
    } else {
        currentScriptTag = document.getElementById('sr-widgetloader');
        if(!currentScriptTag){
            var scripts = document.getElementsByTagName('script');
            var len = scripts.length;
            for (var i = 0; i < len; i++) {
                if (scripts[i].src.match(/widgetloader/i)){
                    currentScriptTag = scripts[i];
                    break;
                }
            }
        }
    }

    if(!currentScriptTag){
        throw new Error('Could not find current script tag');
    }


    var getAttributeValue = function(attrName, dfault) {
        var attrVal = currentScriptTag.getAttribute('data-'+attrName);
        return (attrVal === undefined || attrVal === null) ? dfault : attrVal;
    };


    currentScriptUrl = currentScriptTag.src;
    autoInitAttributeValue = getAttributeValue('autoInit', 'false') == 'true';
    loadJavascript = getAttributeValue('loadScripts', 'true') == 'true';
    loadCss = getAttributeValue('loadCss', 'true') == 'true';
    queryRoot = getAttributeValue('queryRoot', '?/');
    initMatchId = getAttributeValue('matchId', false);
    initTimezone = getAttributeValue('timezone', false);
    applicationPath = getAttributeValue('appPath', false);

    if(!currentScriptUrl){
        var location = window.location;
        var protocol = location.protocol;
        var port = location.port;
        if (protocol.substr(0, 4) !== 'http') {
            protocol = 'http:';
        }
        applicationUrl = protocol+'//'+location.hostname + (port ? ':'+port : '') + applicationPath;
    }
    else{
        applicationUrl = currentScriptUrl.split(queryRoot)[0];
    }
    if (preferHttps) { applicationUrl = 'https://' + applicationUrl.split('//')[1]; }

    var addWidget = function() {
        if (SRLiveLoadedStatus != SRLIVE_LOADED) {
            var currentHandle = SRLive._latestWidgetHandle++;
            widgetsToLoad[currentHandle] = arguments;
            loadSRLive();
            return currentHandle;
        } else {
            return SRLive.w.add.apply(SRLive.w, arguments);
        }
    };

    var removeWidget = function(handle) {
        if (SRLiveLoadedStatus != SRLIVE_LOADED) {
            if (widgetsToLoad[handle]) {
                delete widgetsToLoad[handle];
                return true;
            }
            return false;
        } else {
            return SRLive.w.remove(handle);
        }
    };

    var loadSRLive = function() {
        if (SRLiveLoadedStatus !== SRLIVE_NOT_LOADED) {
            return false;
        }

        SRLiveLoadedStatus = SRLIVE_LOADING;

        // get thru assets to load all stylesheets
        if (loadCss) {
            for (var i = 0; i < styleAssets.length; i++) {
                if (styleAssets[i]) {
                    includeStylesheet(styleAssets[i]);
                }
            }
        }

        // start loading javascripts one at a time
        if (loadJavascript && scriptAssets.length > 0) {
            _timing.srliveLoadStart = +(new Date());
            if (scriptAssets[scriptIdx]) {
                includeJavascript(scriptAssets[scriptIdx]);
            }
        } else {
            initSRLive();
        }
    };

    function includeStylesheet(src) {
        var stylesheet = document.createElement('link');

        stylesheet.setAttribute('rel', 'stylesheet');
        stylesheet.setAttribute('type', 'text/css');
        stylesheet.setAttribute('href', applicationUrl + src);
        stylesheet.className = 'srlive-stylesheet';

        document.getElementsByTagName('head')[0].appendChild(stylesheet);
    }

    var scriptCounter = 0;
    var scriptIdx = 0;

    function scriptLoaded(script) {
        // memory leak in IE8 handled
        script.onload = script.onreadystatechange = null;

        // increase counters
        scriptIdx++;
        scriptCounter++;

        // all scripts should be loaded, init SRLive
        if (scriptCounter === scriptAssets.length) {
            initSRLive();
            return;
        }

        // start loading next script
        if (scriptIdx < scriptAssets.length) {
            includeJavascript(scriptAssets[scriptIdx]);
        }
    }

    function includeJavascript(src) {
        var scriptNode = document.createElement('script');
        scriptNode.type = 'text/javascript';
        scriptNode.src = applicationUrl + src;
        scriptNode.className = 'srlive-script';

        var headNode = document.getElementsByTagName('HEAD');
        if (headNode[0]) {
            headNode[0].appendChild(scriptNode);
        }

        scriptNode.onload = scriptNode.onreadystatechange = function() {
            if (this.readyState && this.readyState !== 'loaded' && this.readyState !== 'complete') {
                return;
            }
            scriptLoaded(scriptNode);
        };
    }

    var callBuffer = {};
    var triggerCallBufferItem = function(argsArray, fn) {
        var path = fn.split('.'),
            fnRef = path.pop(),
            ix = 0, length = argsArray.length;

        var scope = SRUtil.getPropertyArray(SRLive, path), result;
        if (scope[fnRef]) {
            for (; ix<length; ix++) {
                result = scope[fnRef].apply(scope, argsArray[ix]);
            }
        }
        return result;
    };

    var getForwardingFunction = function(targetFn, onlyLastInvocation) {
        // if we're not loading javascript, it means that srlive is already on page waiting for us,
        // thus forwarding functions are not really needed
        // BUT we still need to be sure to invoke them with correct context
        if (!loadJavascript) {
            var parts = targetFn.split('.'),
                fn = parts.pop(),
                scope = SRUtil.getPropertyArray(SRLive, parts);

            return function() {
                return scope[fn].apply(scope, arguments);
            };
        } else {
            return function() {
                if (SRLiveLoadedStatus === SRLIVE_LOADED) {
                    return triggerCallBufferItem([arguments], targetFn);
                } else if (onlyLastInvocation) {
                    callBuffer[targetFn] = [arguments];
                } else {
                    (callBuffer[targetFn] = callBuffer[targetFn] || []).push(arguments);
                }
                return false;
            };
        }
    };

    var initSRLive = function() {
        var clientSpecificConfig = JSON.parse('0') || {}; /* jshint ignore: line */

        var config = SRUtil.extend(true,{
            debugLevel: debugLevel,
            client: {
                timezone: initTimezone || 'Europe/Berlin',
                language: 'en',
                name: 'itf',
                s4clientid: '4'
            },
            query: {
                url: 'https://ls.fn.sportradar.com/',
                timezoneAgnostic: true,
                service_id: parseInt('24', 10) /* jshint ignore: line */
            },
            widget: {
                solution: 'itf',
                url: applicationUrl,
                setupOverridesOptions: false,
                css: true,
                matchId: initMatchId,
                version: '',
                cssVersion: '',
                cssClient: 'itf',
                preferHttps: preferHttps,
                queryRoot: queryRoot
            },
            eventpoller: {
                feeds: {
                    event_fullfeed: {
                        disabled: true
                    },
                    event_get: {
                        disabled: true
                    }
                }
            }
        }, clientSpecificConfig, window.SRConfig || {});

        SRLiveLoadedStatus = SRLIVE_LOADED;
        // We must set loaded status before calling configure client, so that we don't get into some awkward behaviour
        // when triggering event in srlive_initialized event will not be queued (because widgets won't start loading
        // untill few lines later in this code)
        SRLive.configureClient(config);

        if (widgetsToLoad) {
            SRUtil.each(widgetsToLoad, function(args, handle) {
                SRLive.w.addFromWidgetloader(handle, args);
            });
        }

        SRUtil.each(callBuffer, function(){
            // do not return result, since some functions may return false and break the loop.
            triggerCallBufferItem.apply(this, arguments);
        });
        callBuffer = null;
    };

    SRLive['_timing'] = _timing;
    SRLive['_latestWidgetHandle'] = 0;
    SRLive['init'] = loadSRLive;
    SRLive['addWidget'] = addWidget;
    SRLive['removeWidget'] = removeWidget;

    SRLive['getWidget'] = getForwardingFunction('w.get');
    SRLive['changeLanguage'] = getForwardingFunction('languages.change', true);
    SRLive['changeTimezone'] = getForwardingFunction('changeTimezone', true);
    SRLive['triggerEvent'] = getForwardingFunction('event.trigger');
    SRLive['on'] = getForwardingFunction('event.subscribe');
    SRLive['off'] = getForwardingFunction('event.unsubscribe');

    if (autoInitAttributeValue || window.SRConfig && window.SRConfig.autoInit === true) {
        SRLive.init();
    }
})(window, document, 'SRLive');
