window.onload = (function (oldOnload) {
    return function () {
        var viewportWidth;
        var timeout;
        var hasRegion = false;

        var options = {
            originalItems: ["News", "Sports", "TV", "Music", "Radio", "Watch", "Listen"],
            originalItemUrls: [ "https://www.cbc.ca/news", "https://www.cbc.ca/sports/", "https://www.cbc.ca/television/", "https://www.cbc.ca/music/", "https://www.cbc.ca/radio", "https://gem.cbc.ca", "https://www.cbc.ca/listen/"],
            menuItemWidths: [],
            menuItems: [],
            menuItemUrls: [],
            childMenuItems: [],
            childMenuItemUrls: []
        };

        oldOnload && oldOnload();
        console.log(options.originalItems);

        if (menu_label.length > 0) {
            options.originalItems.unshift(menu_label);
            hasRegion = true;
        }

        if (menu_url.length > 0) {options.originalItemUrls.unshift(menu_url);}

        function getTextWidth(text, font) {
            var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
            var context = canvas.getContext("2d");
            context.font = font;
            var metrics = context.measureText(text);
            return metrics.width;
        }

        var setViewportWidth = function () {
            viewportWidth = window.innerWidth || document.documentElement.clientWidth;
        }

        setViewportWidth();

        function itemWidths(array) {
            for (var i = 0; i < array.length; i++) {
                itemWidth = Math.round(getTextWidth(array[i], "bold 15px Open Sans"));
                options.menuItemWidths.push(itemWidth);
            }
        }

        itemWidths(options.originalItems);

        function sortByWidth(array, array2, array3) {
            var comparator = 0;

            for (var i = 0; i < array.length; i++) {
                if (viewportWidth > 768) {
                    if (comparator < (viewportWidth - 620)) {
                        comparator = comparator += array[i];
                        options.menuItems.push(array2[i]);
                        options.menuItemUrls.push(array3[i]);
                    } else {
                        options.childMenuItems.push(array2[i]);
                        options.childMenuItemUrls.push(array3[i]);
                    }
                } else {
                    if (comparator < (viewportWidth - 520)) {
                        comparator = comparator += array[i];
                        options.menuItems.push(array2[i]);
                        options.menuItemUrls.push(array3[i]);
                    } else {
                        options.childMenuItems.push(array2[i]);
                        options.childMenuItemUrls.push(array3[i]);
                    }
                }
            }
        }

        sortByWidth(options.menuItemWidths, options.originalItems, options.originalItemUrls);

        var list;
        var item;
        var menuLength = options.menuItems.length;

        function makeUL(array, array2) {
            var list = document.createElement('ul');
            list.setAttribute("id", "menuList");

            for (var i = 0; i < array.length; i++) {
                var item = document.createElement('li');
                var a = document.createElement("a");

                a.textContent = (array[i]);
                a.setAttribute('href', (array2[i]));
                item.appendChild(a);
                list.appendChild(item);
            }

            if (options.childMenuItems.length !== 0) {
                var moreLi = document.createElement('li');
                moreLi.setAttribute('class', 'more');
                moreLi.setAttribute('id', 'myMore');
                list.appendChild(moreLi);

                var moreButton = document.createElement("button");
                moreButton.setAttribute("id", "moreButton");
                moreButton.setAttribute("aria-expanded", "false");
                moreButton.insertAdjacentHTML('afterbegin', '<span>More</span><svg width="12" height="8" viewBox="0 0 12 8" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1.5L6 6.5L11 1.5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>');

                moreLi.appendChild(moreButton);
            }
            return list;
        }

        function makeULChild(array, array2) {
            var list = document.createElement('ul');
            list.setAttribute("id", "myDrop");
            list.setAttribute("class", "dropdown");
            list.setAttribute("aria-label", "submenu");

            for (var i = 0; i < array.length; i++) {
                var item = document.createElement('li');
                var a = document.createElement("a");

                a.textContent = (array[i]);
                a.setAttribute('href', (array2[i]));
                item.appendChild(a);
                item.setAttribute("class", "dropClass");
                list.appendChild(item);
            }
            return list;
        }

        function makeResizedUL(array, array2) {
            list = document.getElementById('menuList');
            var menuLength = options.menuItems.length;

            for (var i = 0; i < array.length; i++) {
                var item = document.createElement('li');
                var a = document.createElement("a");

                a.textContent = (array[i]);
                a.setAttribute('href', (array2[i]));
                item.appendChild(a);
                item.setAttribute("class", "menuClass");

                list.appendChild(item);
            }

            if (options.childMenuItems.length !== 0) {
                var moreLi = document.createElement('li');
                moreLi.setAttribute('class', 'more');
                moreLi.setAttribute('id', 'myMore');
                list.appendChild(moreLi);

                var moreButton = document.createElement("button");
                moreButton.setAttribute("id", "moreButton");
                moreButton.setAttribute("aria-expanded", "false");
                moreButton.insertAdjacentHTML('afterbegin', '<span>More</span><svg width="12" height="8" viewBox="0 0 12 8" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1.5L6 6.5L11 1.5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>');

                moreLi.appendChild(moreButton);
            }

            return list;
        }

        function makeResizedChildUL(array, array2) {
            var list = document.createElement('ul');
            list.setAttribute("id", "myDrop");
            list.setAttribute("class", "dropdown");
            list.setAttribute("aria-label", "submenu");

            for (var i = 0; i < array.length; i++) {

                var item = document.createElement('li');

                var a = document.createElement("a");
                a.textContent = (array[i]);
                a.setAttribute('href', (array2[i]));
                item.appendChild(a);
                item.setAttribute("class", "dropClass");

                list.appendChild(item);
            }

            return list;
        }

        document.getElementById('topNav').appendChild(makeUL(options.menuItems, options.menuItemUrls));

        if (options.childMenuItems.length !== 0) {
            document.getElementById('myMore').appendChild(makeULChild(options.childMenuItems, options.childMenuItemUrls));
        }

        var resizeId;
        window.addEventListener('resize', function () {
            clearTimeout(resizeId);
            resizeId = setTimeout(doneResizing, 500);
        });

        function doneResizing() {
            var list = document.getElementById("menuList");
            while (list.hasChildNodes()) {list.removeChild(list.firstChild);}

            options.menuItems.splice(0, options.menuItems.length);
            options.childMenuItems.splice(0, options.childMenuItems.length);
            var menuLength = options.menuItems.length;

            setViewportWidth();
            sortByWidth(options.menuItemWidths, options.originalItems, options.originalItemUrls);
            document.getElementById('topNav').appendChild(makeResizedUL(options.menuItems, options.menuItemUrls));
            if (options.childMenuItems.length !== 0) {
                document.getElementById('myMore').appendChild(makeResizedChildUL(options.childMenuItems, options.childMenuItemUrls));
            }
            if (hasRegion) {list.firstElementChild.classList.add("regionBorder");}
        }

        let menuList = document.getElementById('menuList');
        if (hasRegion) {menuList.firstElementChild.classList.add("regionBorder");}

        var myHam = document.getElementById("hamButton");
        myHam.onclick = toggleHam;

        function toggleHam() {
            document.getElementById("ham").classList.toggle("closed");
            document.getElementById("ham").classList.toggle("open");
            document.getElementById("topNav").classList.toggle("closed");
            document.getElementById("topNav").classList.toggle("open");

            var x = document.getElementById("hamButton").getAttribute("aria-expanded");
            if (x == "true") {
                x = "false";
            } else {
                x = "true";
            }
            document.getElementById("hamButton").setAttribute("aria-expanded", x);
        }

        function toggleMore() {
            var y = document.getElementById("moreButton").getAttribute("aria-expanded");

            if (y == "true") {
                y = "false";
            } else {
                y = "true";
            }
            document.getElementById("moreButton").setAttribute("aria-expanded", y);
        }

        function triggerMoreOn() {
            document.getElementById("moreButton").setAttribute("aria-expanded", true);
        }

        function triggerMoreOff() {document.getElementById("moreButton").removeAttribute("aria-expanded");}

        if (options.childMenuItems.length !== 0) {
            var myMore = document.getElementById("myMore");

            var moreButton = document.getElementById("moreButton");
            myMore.onmouseover = toggleMore;
            myMore.onmouseout = toggleMore;
            moreButton.onfocus = triggerMoreOn;
            moreButton.onblur = triggerMoreOff;

            var myDrop = document.getElementById("myDrop");
        }
    }
})(window.onload);