/* Module/Common/JS/iDalgoLoader.js *******************************************************/
;(function(){
    var iDalgoClassLoader = function()
    {
        var isStart = true;
        var urlBaseLoadModule = 'https://vocento.idalgo-hosting.com/jjoo-paris2024/';
        var urlBaseCustomer = '';
        var urlLoadingLogo = '';
        var urlLoadingText = '';
        var sideBarId = null;
        var sideBarIndex = 0;
        var nodeIndex = 0;
        var nodeHead = null;
        var listCss = [];
        var listCssLoading = [];
        var listJs = [];
        var listJsToLoad = [];
        var isJsAlreadyLoaded = false;
        var listBody = [];
        var listDomainHref = [];
        var timeout = 0;
        var debug = false;
        var lastUrlPage = false;

        this.setStart = function(started)
        {
            isStart = started;
        };

        this.start = function()
        {
            lastUrlPage = new URL(window.location.href)
            debug = lastUrlPage.searchParams.get('iDebug') !== null || lastUrlPage.searchParams.get('iDebugJs') !== null
                || window.location.href.substring(0, 9) == 'blob:http'

            if (isStart === true) {
                if (document.readyState === 'loading') {
                    if (window.addEventListener) {
                        window.addEventListener('DOMContentLoaded', this.init, false);
                    } else {
                        window.attachEvent('onload', this.init);
                    }
                } else {
                    this.init();
                }
            }
        };

        this.init = function()
        {
            iDalgoLoader.setBaseLoadModule();

            var listSection = document.getElementsByTagName('section');
            var listRequestWidget = [];
            if (listSection.length > 0) {
                for (var index=0; index < listSection.length; index++) {
                    var section = listSection.item(index);
                    var attribute = null;

                    attribute = section.getAttribute('data-idalgo-loader-loading-logo');
                    if (attribute) {
                        iDalgoLoader.urlLoadingLogo(attribute);
                    }

                    attribute = section.getAttribute('data-idalgo-loader-loading-text');
                    if (attribute) {
                        iDalgoLoader.urlLoadingText(attribute);
                    }

                    attribute = section.getAttribute('data-idalgo-loader-sidebar-id');
                    if (attribute) {
                        iDalgoLoader.setSideBarId(attribute);
                    }

                    attribute = section.getAttribute('data-idalgo-loader-sidebar-index');
                    if (attribute) {
                        iDalgoLoader.setSideBarIndex(attribute);
                    }

                    attribute = section.getAttribute('data-idalgo-timeout');
                    if (attribute) {
                        iDalgoLoader.setTimeOut(attribute);
                    }

                    attribute = section.getAttribute('data-idalgo-loader-src');
                    var newNodeId = 'idalgo-loader-'+nodeIndex;
                    if (attribute && section.innerHTML === '') {
                        nodeIndex++;
                        section.setAttribute('id', newNodeId);
                        listRequestWidget[newNodeId] = attribute;

                        attribute = section.getAttribute('data-idalgo-domain-href');
                        if (attribute) {
                            listDomainHref[newNodeId] = iDalgoLoader.removeLastSlash(attribute);
                        }
                    }

                    attribute = section.getAttribute('data-idalgo-loader-base-url');
                    if (attribute && section.innerHTML === '') {
                        nodeIndex++;
                        section.setAttribute('id', newNodeId);
                        iDalgoLoader.setBaseUrl(attribute);

                        attribute = section.getAttribute('data-idalgo-domain-href');
                        if (attribute) {
                            listDomainHref[newNodeId] = iDalgoLoader.removeLastSlash(attribute);
                        }

                        iDalgoLoader.loadPage(newNodeId);
                    }
                }

                for (var nodeId in listRequestWidget) {
                    iDalgoLoader.loadWidget(listRequestWidget[nodeId], nodeId);
                }
            }

            // Cancel if new url
            // console.log('iDalgo init 1 : '+window.location)
            // window.navigation.addEventListener('navigate', () => {
            //     console.log('iDalgo init 2 : '+window.location)
            //     this.newPage = true
            // })
        };

        this.setBaseUrl = function(txtUrl)
        {
            urlBaseCustomer = iDalgoLoader.removeProtocol(txtUrl);
            urlBaseCustomer = iDalgoLoader.removeLastSlash(urlBaseCustomer);
        };

        this.setBaseLoadModule = function()
        {
            // urlBaseLoadModule = iDalgoLoader.removeProtocol(urlBaseLoadModule);
            // var temp = urlBaseLoadModule.substr(0, 2);

            // if (temp !== '//') {
            //     urlBaseLoadModule = '//' + window.location.hostname + urlBaseLoadModule;
            // }

            urlBaseLoadModule = iDalgoLoader.removeLastSlash(urlBaseLoadModule);
        };

        this.urlLoadingLogo = function(txtUrl)
        {
            urlLoadingLogo = txtUrl;
        };

        this.urlLoadingText = function(txtUrl)
        {
            urlLoadingText = txtUrl;
        };

        this.removeProtocol = function(txtUrl)
        {
            var temp = txtUrl.slice(0, 5);
            if (temp === 'http:') {
                txtUrl = txtUrl.substr(5);
            }

            temp = txtUrl.slice(0, 6);
            if (temp === 'https:') {
                txtUrl = txtUrl.substr(6);
            }

            return txtUrl;
        };

        this.removeLastSlash = function(txtUrl)
        {
            var lastChar = txtUrl.substr(-1);
            if (lastChar === '/') {
                txtUrl = txtUrl.slice(0, -1);
            }

            return txtUrl;
        };

        this.setSideBarId = function(txtId)
        {
            sideBarId = txtId;
        };

        this.setSideBarIndex = function(numIndex)
        {
            sideBarIndex = numIndex;
        };

        this.setTimeOut = function(value)
        {
            timeout = parseInt(value);
        };

        this.loadPage = function(nodeId)
        {
            var urlLocal = iDalgoLoader.removeProtocol(window.location.href);
            if (urlLocal.indexOf(urlBaseCustomer) === 0) {
                iDalgoLoader.loadWidget(urlLocal.replace(urlBaseCustomer, ''), nodeId);
            }
        };

        this.loadWidget = function(txtUrl, nodeId)
        {
            // txtUrl = iDalgoLoader.removeProtocol(txtUrl);

            const protocol = txtUrl.slice(0, 4).toLowerCase()
            const ds = txtUrl.slice(0, 2)
            if (protocol !== 'http' && ds !== '//') {
                if (txtUrl.indexOf(urlBaseLoadModule) === 0) {
                    txtUrl = txtUrl.replace(urlBaseLoadModule, '')
                }

                var indexCache = txtUrl.indexOf('/cache/')
                if (indexCache >= 0) {
                    txtUrl = txtUrl.substr(indexCache)
                }

                txtUrl = urlBaseLoadModule+txtUrl
            }

            var newId = getPositionId(nodeId);

            if (nodeId && listDomainHref[nodeId]) {
                listDomainHref[newId] = listDomainHref[nodeId];
            }

            request(txtUrl, newId);
        };

        this.unloadingCss = function(txtUrl, divId)
        {
            listCssLoading[divId].splice(listCssLoading.indexOf(txtUrl), 1);
            if (listCssLoading[divId].length === 0) {
                setContentBody(divId);
            }
        };

        var getPositionId = function(nodeId)
        {
            nodeIndex++;
            var newNodeId = 'idalgo-loader-'+nodeIndex;
            if (!nodeId) {
                document.write('<div id="'+newNodeId+'"></div>');
            } else {
                var newNode = document.createElement('div');
                newNode.setAttribute('id', newNodeId);
                document.getElementById(nodeId).appendChild(newNode);
            }

            if (urlLoadingLogo.length > 0) {
                var root = document.getElementById(newNodeId);

                var div = document.createElement('div');
                div.style = 'text-align:center';
                root.appendChild(div);

                var img = document.createElement('img');
                img.style = 'width:auto';
                img.setAttribute('src', urlLoadingLogo);
                div.appendChild(img);

                if (urlLoadingText.length > 0) {
                    var style = document.createElement('style');
                    style.innerHTML = '@keyframes iDalgo_Loader_Fade{from {color:transparent} 50% {color:#aaa} to {color:transparent}}';
                    div.appendChild(style);

                    var br = document.createElement('br');
                    div.appendChild(br);

                    var span = document.createElement('span');
                    span.style = 'animation-duration:3s;animation-iteration-count:infinite;'+
                        'animation-name:iDalgo_Loader_Fade';
                    span.innerHTML = urlLoadingText;
                    div.appendChild(span);
                }
            }

            return newNodeId;
        };

        var request = function(url, divId)
        {
            var oXHR = null;
            if(window.XMLHttpRequest) {
                oXHR = new XMLHttpRequest();
            } else {
                try {
                    oXHR = new ActiveXObject("Msxml2.XMLHTTP");
                } catch(e) {
                    try {
                        oXHR = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e2) {
                        setError(e, 'iDalgo Class Load Content Error - Ajax: No HttpRequest');
                    }
                }
            }

            oXHR.addEventListener('readystatechange', () => {
                if (oXHR.status === 200){
                    if(oXHR.readyState === 4){
                        if (lastUrlPage === window.location) {
                            setContent(oXHR.responseText, divId);
                            setLog('iDalgo - Javascript Loader - callback : '+url);
                        } else {
                            setLog('iDalgo - Javascript Loader - destination page error : '+lastUrlPage+' !== '+window.location);
                        }
                    }
                }
            })

            oXHR.addEventListener('timeout', (e) => {
                setError(e,  'TimeOut ('+timeout+'ms): Try again');
                setTimeout(request, 1000, url,  divId);
            })

            setLog('iDalgo - Javascript Loader - call : '+url+' => '+divId);
            lastUrlPage = window.location
            oXHR.open("GET", url, true);
            if (timeout > 0) {
                oXHR.timeout = timeout;
            }

            oXHR.send(null);
        };

        var setContent = function(txtContent, divId)
        {
            txtContent = setContentTitle(txtContent);
            txtContent = setContentMeta(txtContent);

            txtContent = preloadContentJs(txtContent);
            setContentCss(txtContent, divId);
        };

        var setContentBody = function(divId)
        {
            txtContent = setDomainHref(listBody[divId], divId);
            txtContent = setContentAside(txtContent);
            setContentMain(txtContent, divId);
            listBody.splice(divId, 1);

            setContentJs();
        };

        var setContentMain = function(txtContent, divId)
        {
            var node = document.getElementById(divId);
            if (node) {
                var callback = node.parentNode.getAttribute('data-idalgo-callback');
                node.parentNode.innerHTML = txtContent;

                if (callback) {
                    var exec = eval(callback)
                    if (typeof exec  === 'function') {
                        exec();
                    }
                }
            }
        };

        var setDomainHref = function(txtContent, divId)
        {
            if (listDomainHref[divId]) {
                var numStart = txtContent.indexOf('<a ');
                var numEnd = txtContent.indexOf('>', numStart);
                var domain = listDomainHref[divId];
                while (numStart >= 0 && numEnd >= 0) {
                    var numStartSource = txtContent.indexOf('href="', numStart);
                    var numEndSource = txtContent.indexOf('"', numStartSource + 6);

                    var txtHref = null;
                    if (numStartSource >= 0 && numEndSource >= 0 && numStartSource < numEnd) {
                        var isProtocol = txtContent.substr(numStartSource + 6, 7) === "http://"
                            || txtContent.substr(numStartSource + 6, 8) === "https://"
                            || txtContent.substr(numStartSource + 6, 2) === "//";

                        if (!isProtocol) {
                            txtHref = txtContent.substring(numStartSource + 6, numEndSource);

                            if (txtHref) {
                                txtContent = txtContent.substring(0, numStartSource + 6) + domain + txtHref +
                                    txtContent.substring(numEndSource);
                            }
                        }
                    }

                    numStart = txtContent.indexOf('<a ', numEnd + domain.length + 1);
                    numEnd = txtContent.indexOf('>', numStart);
                }
            }

            return txtContent;
        };

        var setContentAside = function(txtContent)
        {
            var nodeSideBar = document.getElementById(sideBarId);

            if (nodeSideBar) {
                var txtStartFlag = '<!-- iDalgoAsideFlagStart -->';
                var txtEndFlag = '<!-- iDalgoAsideFlagEnd -->';
                var numStart = txtContent.indexOf(txtStartFlag);
                var numEnd = txtContent.indexOf(txtEndFlag);

                var txtAside = null;
                if (numStart >= 0 && numEnd >= 0) {
                    txtAside = txtContent.substring(numStart + txtStartFlag.length, numEnd);
                    txtContent = txtContent.substr(0, numStart) + txtContent.substr(numEnd + txtEndFlag.length);

                    var divAside = document.createElement('div');
                    divAside.innerHTML = txtAside;

                    var listChild = nodeSideBar.childNodes;
                    if (sideBarIndex) {
                        sideBarIndex = parseInt(sideBarIndex);
                        if (sideBarIndex + 1 <= listChild.length) {
                            nodeSideBar.insertBefore(divAside, listChild[sideBarIndex]);
                        } else {
                            nodeSideBar.appendChild(divAside);
                        }
                    }else {
                        nodeSideBar.appendChild(divAside);
                    }

                }
            }

            return txtContent;
        };

        var setContentTitle = function(txtContent)
        {
            var numStart = txtContent.indexOf('<title>');
            var numEnd = txtContent.indexOf('</title>', numStart);
            if (numStart >= 0 && numEnd >= 0) {
                var txtTitle = txtContent.substring(numStart+7, numEnd);
                var head = getHead();

                if (txtTitle && head) {
                    var title = head.getElementsByTagName('title');
                    if (title.length > 0) {
                        title = title[0];
                    } else {
                        title = document.createElement('title');
                        head.appendChild(title);
                    }

                    title.innerHTML = txtTitle;
                }

                txtContent = txtContent.substring(0, numStart)+txtContent.substring(numEnd+8);
            }

            return txtContent;
        };

        var setContentCss = function(txtContent, divId)
        {
            var numStart = txtContent.indexOf('<link');
            var numEnd = txtContent.indexOf('/>', numStart);
            var listCssToLoad = [];

            if (!listCssLoading[divId]) {
                listCssLoading[divId] = [];
            }

            while (numStart >= 0 && numEnd >= 0) {
                var numStartSource = txtContent.indexOf('href="', numStart);
                var numEndSource = txtContent.indexOf('"', numStartSource+6);

                var txtHref = null;
                if (numStartSource >= 0 && numEndSource >= 0) {
                    txtHref = txtContent.substring(numStartSource+6, numEndSource);
                }

                if (txtHref) {
                    if (!listCss[txtHref]) {
                        listCssLoading[divId].push(txtHref);

                        var link = document.createElement('link');
                        link.setAttribute('rel', 'stylesheet');
                        link.setAttribute('type', 'text/css');
                        link.onload = function(){ iDalgoLoader.unloadingCss(txtHref, divId); };
                        link.setAttribute('href', txtHref);
                        listCssToLoad.push(link);
                        listCss[txtHref] = true;
                    }

                    txtContent = txtContent.substring(0, numStart) + txtContent.substring(numEnd + 2);
                }

                numStart = txtContent.indexOf('<link');
                numEnd = txtContent.indexOf('/>', numStart);
            }

            listBody[divId] = txtContent;

            var head = getHead();
            if (listCssToLoad.length > 0 && head) {
                listCssToLoad.forEach(function(link) {head.appendChild(link);});
            } else {
                setContentBody(divId);
            }
        };

        var setContentMeta = function(txtContent)
        {
            var numStart = txtContent.indexOf('<meta');
            var numEnd = txtContent.indexOf('>', numStart);
            while (numStart >= 0 && numEnd >= 0) {
                var numStartSource = txtContent.indexOf('content="', numStart);
                var numEndSource = txtContent.indexOf('"', numStartSource+9);

                var txtContentNode = null;
                if (numStartSource >= 0 && numEndSource >= 0) {
                    txtContentNode = txtContent.substring(numStartSource+9, numEndSource);
                }

                numStartSource = txtContent.indexOf('property="', numStart);
                numEndSource = txtContent.indexOf('"', numStartSource+10);
                var txtProperty = null;
                if (numStartSource >= 0 && numEndSource >= 0) {
                    txtProperty = txtContent.substring(numStartSource+10, numEndSource);
                }

                numStartSource = txtContent.indexOf('name="', numStart);
                numEndSource = txtContent.indexOf('"', numStartSource+6);
                var txtName = null;
                if (numStartSource >= 0 && numEndSource >= 0) {
                    txtName = txtContent.substring(numStartSource+6, numEndSource);
                }

                var head = getHead();

                if (head) {
                    var meta = document.createElement('meta');
                    if (txtContentNode) {
                        meta.setAttribute('content', txtContentNode);
                    }
                    if (txtProperty) {
                        meta.setAttribute('property', txtProperty);
                    }
                    if (txtName) {
                        meta.setAttribute('name', txtName);
                    }
                    head.appendChild(meta);

                    txtContent = txtContent.substring(0, numStart)+txtContent.substring(numEnd+1);

                    numStart = txtContent.indexOf('<meta');
                    numEnd = txtContent.indexOf('>', numStart);
                } else {
                    break;
                }
            }

            return txtContent;
        };

        var preloadContentJs = function(txtContent)
        {
            var numStart = txtContent.indexOf('<script');
            var numEnd = txtContent.indexOf('</sc'+'ript>', numStart);
            while (numStart >= 0 && numEnd >= 0) {
                var numStartSource = txtContent.indexOf('src="', numStart);
                var numEndSource = txtContent.indexOf('"', numStartSource+5);

                var txtSrc = null;
                if (numStartSource >= 0 && numEndSource >= 0) {
                    txtSrc = txtContent.substring(numStartSource+5, numEndSource);
                }

                if (txtSrc) {
                    if (!listJs[txtSrc]) {
                        var link = document.createElement('script');
                        link.setAttribute('type', 'text/javascript');
                        link.setAttribute('src', txtSrc);
                        listJsToLoad.push(link);
                        listJs[txtSrc] = true;
                    } else {
                        isJsAlreadyLoaded = true;
                    }

                    txtContent = txtContent.substring(0, numStart) + txtContent.substring(numEnd + 9);
                }

                numStart = txtContent.indexOf('<script', numEnd);
                numEnd = txtContent.indexOf('</s'+'cript>', numStart);
            }

            return txtContent;
        };

        var setContentJs = function()
        {
            var head = getHead();
            listJsToLoad.forEach(function(link) {head.appendChild(link);});
            listJsToLoad.slice();

            if (isJsAlreadyLoaded === true) {
                if (window.iDalgoReady) {
                    iDalgoReady(function(){});
                }
            }

            if (window.idalgo && window.idalgo.reload) {
                window.idalgo.reload()
            }

        };

        var getHead = function()
        {
            if (!nodeHead) {
                var head = document.getElementsByTagName('head');
                if (head.length > 0) {
                    nodeHead = head[0];
                }
            }

            return nodeHead;
        };

        var setError = function(e, txtTitle)
        {
            setLog(txtTitle);
            if (e) {
                setLog(e.message+' '+e.name+' '+e.fileName+' '+e.lineNumber+':'+e.columnNumber+' '+e.stack);
            }
        };

        var setLog = function(value)
        {
            if (debug) {
                console.log('iDalgo - LoaderJs - '+value);
            }
        };
    };

    if (typeof window.iDalgoLoader === 'undefined' || typeof window.iDalgoLoader === 'boolean') {
        var start = null;
        if (typeof window.iDalgoLoader === 'boolean') {
            start = window.iDalgoLoader;
        }
        window.iDalgoLoader = new iDalgoClassLoader();
        if (start !== null) {
            window.iDalgoLoader.setStart(start);
        }
        window.iDalgoLoader.start();
    }
})();