Gitlab Mods

Adds colored sections, extra functionality, and avatars to Gitlab. For avatars, detects locally-running image server to use for replacements of avatars. Use http-server (https://www.npmjs.com/package/http-server) for node.js for simple image hosting. Recommend image size of 100x100.

As of 17.08.2020. See ბოლო ვერსია.

// ==UserScript==
// @name			Gitlab Mods
// @namespace		COMDSPDSA
// @version			5.7
// @description		Adds colored sections, extra functionality, and avatars to Gitlab. For avatars, detects locally-running image server to use for replacements of avatars. Use http-server (https://www.npmjs.com/package/http-server) for node.js for simple image hosting. Recommend image size of 100x100.
// @author			Dan Overlander
// @include			*/gitlab.dell.com*
// @require			https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @require         https://greasyfork.org/scripts/23115-tampermonkey-support-library/code/Tampermonkey%20Support%20Library.js?version=836747
// @require		    https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js
// @require         https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js
// @require         https://greasyfork.org/scripts/40055-libraryjquerygrowl/code/libraryJQueryGrowl.js
// @grant           GM_setValue
// @grant           GM_getValue

// ==/UserScript==

// TODO: Make *hourly* reminders show only once no matter how many tabs for Gitlab are open.
// TODO: Convert prefs booleans to real booleans

// Since v05.60: ADDS Pivotal Story Details to Gitlab MR scren.  Moved utils to be defined at top, so as to include methods previously required to be defined earlier.  Unified definition of default avatar images. Allowing user preferences to be defined as true objects, not objects-as-strings (no longer will users have to reset preferences to accept new preference definitions).  Code Cleanup; moving globally-declared identifying information to global.ids object. Removed getStoryActivity as that was dumb and we dont need story history here. Colorized the required/remaining Approval Rules on the MR list screen; colors are set via user prefs. Updated Tamperlibrary to prevent tampericon unbind/bind event action. Improved MR-screen image lightbox interface. 
// Since v05.50: Working on remembering Pivotal Tracker review-type choice/preference; Redesigned log highlighter including user color preference.  Added POST comment for Pivotal Tracker.  Collapsible sidebar tools area to shove aside portions we never use. Expanded breadcrumb font size matches pre-expanded size. Automatically sets pivotal story to started if unstarted (can be disabled via preference).
// Since v05.40: Increased delay/amount of delayUntil chances. Increased initial delay of script - suspected interference with display of SVGs from Gitlab.  Added icon for ally-req PT review type. Added "Show Needed Approvals" button on Merge Request page. Renamed "Filter Merges" button to "My Checklist"
// Since v05.30: Bug fixes. Mousemove no longer inits page while prefs window is open. Tampericon changed to remove website img. added filter merges button.
// Since v05.20: Unrestricting inline view to 925px; now allowed to show full browser width. dimApprovedRequests.  Added Pivotal Tracker API integration.  User Popup has link to Teams chat. Probably many other small upgrades.  Semi-beta version, here.
// Since v05.10: Added View Site shortcut to top nav bar. update PT title linker
// Since v05.00: Added pipeline error growl notifications, colorized notes on code reviews that are not associated with line numbers.
// Since v04.99: Changed PT linking.
// Since v04.98: Fixed the alert-wrapper problem.
// Since v04.97: Moving alert removal to alert-wrapper. May need further investigation
// Since v04.96: Added remove-alert button.  Figure out why some notes are not colored
// Since v04.95: Added bisque color for active tabs; partial.
// Since v04.90: Modified the "Act" button to first click the Overview tab before scrolling to the Approve link.
// Since v04.80: Realized Gitlab's new navigation can lead to moments where the Approve button is nowhere near the top, so split main nav new button into two, "Act", and "Top"
// Since v04.70: Altered "Discussions" button to be "Top" button.  Added a reset-timeout for adding the Changes tab's font-size and collapse/expand buttons.
// Since v04.60: Updated unresolved locator to match Gitlab-changed text
// Since v04.50: Fixed TODO default prompt for new users
// Since v04.40: Added visual indicator of TODO count activity (badge count background color change). Updated to latest tamperlibrary script version.  ?? Some setPrefs extra line / bug line removed. Removes dependency on Tamper Global script.
// Since v04.30: Adjusted todo element identifier to match update from Gitlab, fixing TODO monitor.
// Since v04.20: Removed identicon from breadcrumb trail as without an image it looked weird. Important - TODO bugfix for undefined error!
// Since v04.10: Fixed the hourlies reminders.  Added user option to hide "err" code background color.
// Since v04.00: Resovled intermittent (?) avatar photo failures, allowing back in a XX second timer for reinitialization.  Added ability to reset page memory. If the TODOS count changes and you're on the TODO page, auto-reload.
// Since v03.91: User Preferences to control main functions of plugin! Avatar name tweaks.
// Since v03.90: Added comments to AT SOME POINT figure out why the Collapse All buttons are not working all the time. Added other avatar locations. Made a default broken-image "no avatar" avatar. System stops attempting to replace missing avatars if not found on the local server. TODO monitoring no longer requires a separate page to be open, and automatically updates the indicator on every page.
// Since v03.80: Expanded bot detection to include array created via regex
// Since v03.70: Optimized avatar location methods
// Since v03.60: Button bug fixes. Renamed comparisonSize. Moved default- and small- font sizes to userprefs. Hides the "nothing here block" divs. Scrolls to collapsed div when tall divs are collapsed. All states moved to global.states.  Avatar ping functionality disabled if server isn't running.
// Since v03.50: argh. They change the DOM, breaking the expand/collapse functions. Fixed and in a more flexible manner.
// Since v03.30: Gitlab changed a classname, which broke the Discussions button. Fixed in a more flexible manner.
// Since v03.20: Moving .fingery class to global script. Moving out setTamperIcon
// Since v03.10: Made comparisonSize font alteration more inclusive. Filtering out "Americas" from avatar names. Removes vertical margin from fingery class
// Since v03.00: Set title TFS/PT scan to use case-insensivite checks
// Since v02.20: Links TFS and PT values in title to their respective URLs. Adds Font+/- button for comparison text
// Since v02.10: Since Gitlab removed their Expand All button (?!), this adds it back in...
// Since v02.00: Altered the logic of colorizing discussions to search for a more universal pass-fail value. Changes Discussions buttons from icon to text (and is therefore larger)
// Since v01.81: Removed old coffee cup button code. Added Collapse All Button with diff-collapsing function. Bug tweaks.
// Since v01.80: Some conversations were not being colorized.
// Since v01.75: Removes coffee-cup as it is native functionality, now. Yay Gitlab! Fixes a name-finding method that sometimes forgot to add a comma after spaces, for avatar images.
// Since v01.7: Fixes the click functionality of the tamperlabel, also makes it look clickable
// Since v01.6: Adds ability to hide header messages. Adds ability to erase Gitlab Mods memory by clicking on Tampermonkey icon (on this page, a battery in the lower-right corner)
// Since v01.5: Added a conditional close-footer button, close broadcast message button.  Adds memory states for these buttons (only for messages already seen!) as well as the close-tree (coffee) button. Expands breadcrumb dropdown.
// Since v01.4: Linked the notifications to the TODO page. Removed a log statement. Resets TODO page title when timer runs out if reload is cancelled. Slows down reminder by 1 hour (up to 8 times) because coming back to your computer after an extended period and receiving TONS of notifications is annoying
// Since v01.3: Re-enables the Tampericon
// Since v01.2: Adds "hide tree" button (looks like a coffee cup)
// Since v01.1: Updates document title with countdown timer indication.  Adds hourly reminder of existing TODOs. Removes conversation button from non-conversation pages.
// Since v01.0: Added the countdown indicator to the page title for TODO indication; cancelling reverts the title to original
// Since v00.0: init, copying from GIT Avatars script

/*
 * tm is an object included via @require from DorkForce's Tampermonkey Assist script
 */

(function() {
    'use strict';

    var utils = {
		debug: function(msg) {
			if (global.prefs.debugMode) {
				tm.log(msg);
			}
		},
        delayUntil: function (id, condition, callback) {
            var repeat = function(id, co, ca) {
                setTimeout(() => {
                    utils.delayUntil(id, co, ca);
                }, TIMEOUT*2);
            }
            if (!global.states.delays.find((x) => x.delayId === id)) {
                global.states.delays.push({
                    delayId: id,
                    delayCount: 0
                });
            }
            global.states.delays.find((x) => x.delayId === id).delayCount++;
            if (global.states.delays.find((x) => x.delayId === id).delayCount > 20) {
                global.states.delays.find((x) => x.delayId === id).delayCount === 0;
                return;
            }
            try {
                if (!condition()) {
                    utils.debug('delay WAIT called by ' + id);
                    repeat(id, condition, callback);
                } else {
                    utils.debug('delay PASS for ' + id);
                    callback();
                }
            } catch (e) {
                utils.debug('delay WAIT called by ' + id + ' TRIED\n   ' + e);
                repeat(id, condition, callback);
            }
        },
        getPivotalStoryId: function () {
            var indexOfId;
            if (!document.querySelector('a[href^="https://www.pivotal"]')) {
                return;
            }
            var pivotalStoryIds = [];
            _.each(document.querySelectorAll('a[href^="https://www.pivotal"]'), (storyEl) => {
                var thisHref = storyEl.href;
                indexOfId = thisHref.lastIndexOf('/') + 1;
                thisHref = thisHref.substr(indexOfId, thisHref.length - indexOfId);
                pivotalStoryIds.push(thisHref);
            });
            return pivotalStoryIds[0];
        },
        isNumeric: function(n) {
            return !isNaN(parseFloat(n)) && isFinite(n);
        },
        initScript: function () {
            _.each(global.ids.triggerElements, (trigger) => {
                tm.getContainer({
                    'el': trigger,
                    'max': 100,
                    'spd': 1000
                }).then(function($container){
                    page.initialize();
                });
            });
        },
        listenOnce: function(element, event, handler) {
            element.addEventListener(
                event,
                function tempHandler(e) {
                    handler(e);
                    element.removeEventListener(event, tempHandler, false);
                },
                false
            );
        },
        pivotalHoursElapsed: function(timerId, howMany) {
            if (!global.mems.pivotalData.timers) {
                tm.log('Reset your app memory. global.mems.pivotalData.timers must be defined.');
                return false;
            }
            if (!global.mems.pivotalData.timers.find((x) => x.id === timerId)) {
                global.mems.pivotalData.timers.push({
                    id: timerId,
                    expires: moment().subtract(48, 'hours')
                });
            }
            var duration = moment.duration(moment().diff(global.mems.pivotalData.timers.find((x) => x.id === timerId).expires)),
                hours = duration.asHours();
            if (hours >= howMany) {
                global.mems.pivotalData.timers.find((x) => x.id === timerId).expires = moment();
                return true;
            } else {
                return false;
            }
        },
        savedMems: function() {
            return JSON.parse(GM_getValue(global.ids.memsName));
        },
        showGrowls: function(growlLow, growlMed, growlHigh) {
            if (growlLow.length > 0) {
                $.growl.notice({
                    message: '<div class="growlMessage">' + growlLow + '</div>',
                    size: 'large',
                    delayOnHover: true,
                    duration: 3200 // 3200 is default
                });
            }
            if (growlMed.length > 0) {
                $.growl.warning({
                    message: '<div class="growlMessage">' + growlMed + '</div>',
                    size: 'large',
                    delayOnHover: true,
                    duration: 6400 // 3200 is default
                });
            }
            if (growlHigh.length > 0) {
                $.growl.error({
                    message: '<div class="growlMessage">' + growlHigh + '</div>',
                    size: 'large',
                    delayOnHover: true,
                    duration: 9600 // 3200 is default
                });
            }
        },
        xhrAction: function(iAm, xhrType, urlPath, callback, alwaysCallback, params) {
            if (global.prefs.pivotalToken.length === 0) {
                return;
            }
            if (!iAm || !xhrType || !urlPath || !callback) {
                utils.debug('improper xhr setup');
                return;
            }
            utils.debug('xhrAction: ' + iAm);
            if (urlPath.indexOf('PIVOTALSTORYID') > 0) {
                var pivotalStoryId = utils.getPivotalStoryId();
                if (pivotalStoryId) {
                    urlPath = urlPath.replace('PIVOTALSTORYID', pivotalStoryId);
                } else if (global.prefs.debugMode) {
                    utils.debug(iAm + ' FAILED: Pivotal Story ID could not be determined.');
                    return;
                }
            }
            // Set up our HTTP request
            var xhr = new XMLHttpRequest();

            // Setup our listener to process completed requests
            xhr.onload = function () {
                global.states.xhrBusy = false;

                // Process our return data
                if (xhr.status >= 200 && xhr.status < 300) {
                    // What do when the request is successful

                    var resp = xhr.response;
                    if (resp) {
                        // resp = JSON.parse(resp).slice().reverse();
                        if (global.prefs.debugMode) console.dir({iAm, resp});
                        callback(resp);
                    }
                } else {
                    // What do when the request fails
                    tm.log('XHR Call for ' + iAm + ' failed!');
                }
                if (alwaysCallback) {
                    alwaysCallback();
                }
            };

            if (global.ids.pivotal.gitlabRelation != null) {
                var xhrUrl = 'https://www.pivotaltracker.com/services/v5/';
                if (urlPath === 'me') {
                    xhrUrl += urlPath;
                } else {
                    xhrUrl += 'projects/' + parseInt(global.ids.pivotal.gitlabRelation.project_id) + '/' + urlPath;
                }
                global.states.xhrBusy = true;
                xhr.open(xhrType,  xhrUrl);
                xhr.setRequestHeader('X-TrackerToken', global.prefs.pivotalToken);
                if (params != null) {
                    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                    xhr.send(JSON.stringify(params));
                } else {
                    xhr.send();
                }
            } else if (global.prefs.debugMode) {
                tm.log('Pivotal Settings Not Populated');
            }
        },
        userTeamsAction: function (emailName) {
            // go to teams
            var teamsLink = 'https://teams.microsoft.com/l/chat/0/0?users=';
            emailName = emailName + '@dell.com';
            window.open(teamsLink + emailName);
        },
        properName: function(thisName) {
            if (!thisName) {
                return;
            }
            var firstName = '',
                lastName = '',
                midName = '';

            thisName = thisName
                .replace('https://gitlab.dell.com/', '')
                .replace(' - Dell Team', '')
                .replace('\'s avatar', '')
                .replace('Assigned to ', '')
                .replace('Avatar for ', '')
                .replace('@', '')
                .replace(/@/g, '')
                .replace(/\//g, '')
                .replace(/_/g, '-');
            firstName = thisName.substring(0, thisName.indexOf('-'));
            lastName = thisName.substring(thisName.indexOf('-')+1, thisName.length);
            if ((firstName.length === 0 && lastName.length === 0)) {
                return;
            }
            if (firstName.length > 0 && lastName.length > 0 && thisName.indexOf(',') < 0) {
                thisName = lastName + ', ' + firstName;
            }
            if (thisName.indexOf('-') > 0) {
                midName = thisName.substring(0, thisName.indexOf('-'));
                thisName = thisName.substring(thisName.indexOf('-')+1, thisName.length);
                thisName = thisName + ' ' + midName;
            }
            while (thisName.indexOf('  ') > 0) {
                thisName = thisName.replace(/\s\s/, ''); // no double spaces
            }
            thisName = thisName
                .replace(/(\r\n\t|\n|\r\t)/gm,'') // no line breaks or tabs
                .replace(/ ,/, ',') // no spaces before commas
                .replace(/\%20/, '') // no %20 characters
                .replace(/Americas/g, '')
                .trim(); // seriously, no extra spaces
            thisName = thisName.replace(',', ', ').replace('  ', ' '); // there's probably a less-stupid way of REALLY making sure it's always "COMMA SPACE"
            return thisName;
        },
        updateImg: function(img, thisName) {
            if (thisName != null) {
                if (thisName.length > 0 && thisName !== ', ') {
                    if ($(img).prop('src').indexOf('!none') <= 0) {
                        if (global.states.avatarPingFailed === false && global.prefs.avatarPreference[0] === 'localhost' ) {
                            $(img).prop('src', 'http://' + avatarHost + thisName + imageExt);
                        } else {
                            // <img src="https://api.adorable.io/avatars/285/IMGID.png" alt="IMGALT" title="IMGALT" class="avatar s40">
                            var templateSrc = global.templates.default.replace(/IMGID/g, thisName).replace(/IMGALT/g, thisName);
                            templateSrc = encodeURI(templateSrc.substr(templateSrc.indexOf('http'), (templateSrc.indexOf('alt=') - templateSrc.indexOf('http'))-2));
                            $(img).prop('src', templateSrc);
                        }
                    }
                } else {
                    utils.debug('updateImg: invalid user name for ' + img.src + ': ' + thisName + '(' + thisName.length + ' chars)');
                }
            }
        }
    };
    var TIMEOUT = 750,
        activityTimestamp = moment(),
        avatarHost = 'localhost:8080/', // for setPhoto
        pingPhoto = '!none', // pinging for setPhoto
        imageExt = '.png',
        global = {
            ids: {
                scriptName: 'Gitlab Mods',
                prefsName: 'gitlabPrefs',
                memsName: 'gitlabMems', // using this as a system-memory kind of thing.  Like the prefs but the user doesn't see them
                triggerElements: ['.content', '#root'],
                gitlabUserId: null,
                listeners: [],
                pivotal: {
                    project: undefined,
                    story: undefined,
                    gitlabRelation: undefined
                }
            },
            states: {
                appendClickProcessed: false,
                areClassesAdded: false,
                arePrButtonsAdded: false,
                areFavesAdded: false,
                areInterfaceButtonsAdded: false,
                delays: [],
                todoMonitorInitialized: false,
                titlesLinked: false,
                isMouseMoved: false,
                avatarPingFailed: null,
                arePipelinesChecked: false,
                xhrBusy: false,
                mergeRequestScanned: false
            },
            prefs: {},
            mems: undefined,
            reload: {
                lapsed: 0,
                timespan: 10000,
                title: document.title,
                todoTimer: undefined
            },
            templates: {
                default: null,
                adorable: '<img src="https://api.adorable.io/avatars/285/IMGID.png" alt="IMGALT" title="IMGALT" class="avatar s40">',
                dicebear: '<img src="https://avatars.dicebear.com/api/bottts/IMGID.svg" alt="IMGALT" title="IMGALT" class="avatar s40">',
                pivotalComment: '  <div class="sidebar-collapsed-icon dont-change-state">' +
                '    <button class="btn btn-clipboard btn-transparent">' +
                '      <i aria-hidden="true" data-hidden="true" class="fa fa-comments" style="margin-right:0;"></i>' +
                '      <span id="pivotalParticipants"></span>' +
                '    </button>' +
                '  </div>'
            }
        },
        page = {
            initialize: function () {
                setTimeout(function () {
                    page.setPrefs();
                    page.setMems();
                    tm.setTamperIcon(global);
                    tm.initNotes(global);
                    tm.addClasses();
                    page.addClasses();
                    page.setGitlabUserId();
                    page.pivotal.defineProject();
                    page.pivotal.getMembers();
                    page.pivotal.getMe();
                    page.pivotal.getReviewTypes();
                    page.pivotal.getStory();
                    page.adjustStyles();
                    page.addElements();
                    page.adjustMarkdown();
                    page.appendClickFunctions();
                    page.expandBreadcrumb();
                    page.setAvatars();
                    page.scanMergeRequest();
                    page.monitorTodos();
                    page.linkWorkItems();
                    page.checkForInactivity();
                    page.dimApprovedRequests();
                    page.addFaves();
                    page.monitorPipelines();
                    page.collapseSidebarLowPriorities();
                }, TIMEOUT);
            },
            setPrefs: function() {
                var currentPrefs = GM_getValue(global.ids.prefsName),
                    setDefaultPrefs = function() {
                        if (global.prefs.debugMode == null)               global.prefs.debugMode = false;
                        if (global.prefs.autohideNotification == null)    global.prefs.autohideNotification = true;
                        if (global.prefs.minimizeMetaInfo == null)        global.prefs.minimizeMetaInfo = true;
                        if (global.prefs.useLocalAvatars == null)         global.prefs.useLocalAvatars = false;
                        if (global.prefs.autoStartPivotalStories == null) global.prefs.autoStartPivotalStories = true;
                        if (global.prefs.avatarPreference == null)        global.prefs.avatarPreference = ['dicebear', 'adorable', 'localhost'];
                        if (global.prefs.colorHeadline == null)           global.prefs.colorHeadline = 'cornflowerblue';
                        if (global.prefs.colorActiveTab == null)          global.prefs.colorActiveTab = 'bisque';
                        if (global.prefs.colorResolved == null)           global.prefs.colorResolved = 'palegreen';
                        if (global.prefs.colorUnresolved == null)         global.prefs.colorUnresolved = 'orange';
                        if (global.prefs.colorNavButton == null)          global.prefs.colorNavButton = 'burlywood';
                        if (global.prefs.colorDim1 == null)               global.prefs.colorDim1 = 'lightgrey';
                        if (global.prefs.colorDim2 == null)               global.prefs.colorDim2 = 'aliceblue';
                        if (global.prefs.colorsRules == null)             global.prefs.colorsRules = [
                            { "ruleName": "Ready to Merge", "hexName": "limegreen" },
                            { "ruleName": "All Members", "hexName": "gold" },
                            { "ruleName": "Design", "hexName": "chocolate" },
                            { "ruleName": "Code", "hexName": "coral" },
                            { "ruleName": "Copied to Alpha", "hexName": "sandybrown" }
                        ];
                        if (global.prefs.colorNavBackground == null)      global.prefs.colorNavBackground = 'bisque';
                        if (global.prefs.useThumbnailImages == null)      global.prefs.useThumbnailImages = true;
                        if (global.prefs.hideCodeErrClass == null)        global.prefs.hideCodeErrClass = true;
                        if (global.prefs.pipelineLogFilters == null)      global.prefs.pipelineLogFilters = [
                            {"name": "failedTest", "key": "?", "background": "darkgoldenrod", "severity": "medium"},
                            {"name": "error", "key": "error", "background": "red", "color": "white", "severity": "high"},
                            {"name": "weblink", "key": "http", "background": "green", "severity": "low"}
                        ];
                        if (global.prefs.pivotalToken == null)            global.prefs.pivotalToken = '';
                        if (global.prefs.pivotalMaps == null)             global.prefs.pivotalMaps = [
                            {"project_id":"2203130","reference":"koa/ui-core/Themes/Documentation"},
                            {"project_id":"2203130","reference":"dao/dell-digital-design/design-language-system/systems/dls-1.0"},
                            {"project_id":"2448496","reference":"dao/dell-digital-design/design-language-system/systems/dls-2.0"},
                            {"project_id":"2451317","reference":"dao/dell-digital-design/design-language-system/experiment/dls-2.0-alpha"}
                        ];
                        if (global.prefs.userFaves == null)               global.prefs.userFaves = [
                            '{"name": "Docs", "url": "https://gitlab.dell.com/koa/ui-core/Themes/Documentation/-/merge_requests"}; ' +
                            '{"name": "1.0", "url": "https://gitlab.dell.com/dao/dell-digital-design/design-language-system/systems/dls-1.0/-/merge_requests"}; ' +
                            '{"name": "2.0", "url": "https://gitlab.dell.com/dao/dell-digital-design/design-language-system/systems/dls-2.0/-/merge_requests"}; ' +
                            // '{"name": "YMLint", "url": "https://gitlab.dell.com/dao/dell-digital-design/design-language-system/systems/dls-1.0/-/ci/lint"}; ' +
                            // '{"name": "Alpha", "url": "https://gitlab.dell.com/dao/dell-digital-design/design-language-system/experiment/dls-2.0-alpha/-/merge_requests"}; ' +
                            '{"name": "CMS", "url": "https://gitlab.dell.com/dao/dell-digital-design/design-language-system/support-sys"}'
                        ];
                    };

                if (currentPrefs == null || _.isEmpty(JSON.parse(currentPrefs))) {
                    global.prefs = {};
                    setDefaultPrefs();
                    tm.savePreferences(global.ids.prefsName, global.prefs);
                } else {
                    global.prefs = JSON.parse(currentPrefs);
                    setDefaultPrefs();
                    for (var key in global.prefs) {
                        try {
                            if (global.prefs[key] === 'true' || global.prefs[key] === 'false') {
                                global.prefs[key] = (global.prefs[key] == 'true')
                            } else {
                                global.prefs[key] = JSON.parse(global.prefs[key]);
                            }
                        } catch (e) {
                            global.prefs[key] = global.prefs[key];
                        }
                    }
                }
                global.templates.default = global.prefs.avatarPreference[0] === 'adorable' ? global.templates.adorable : global.templates.dicebear;
            },
            setMems: function() {
                var currentMems = GM_getValue(global.ids.memsName);
                if (currentMems == null || _.isEmpty(JSON.parse(currentMems))) {
                    global.mems = {};
                    global.mems.todosCount = 0;
                    global.mems.todosTimestamp = moment();
                    global.mems.manyTabTimestamp = moment();
                    global.mems.reloadTimesReminded = '0';
                    global.mems.reloadReminderCount = '0';
                    global.mems.archivedMessages = [];
                    global.mems.archivedBroadcasts = [];
                    global.mems.archivedAlerts = [];
                    global.mems.currentFontSize = global.defaultLineSize;
                    global.mems.defaultLineSize = '12px';
                    global.mems.smallLineSize = '10px';
                    global.mems.avatarPingTimer = global.mems.avatarPingTimer || undefined;
                    global.mems.pivotalData = {
                        states: {
                            storyExpanded: false
                        },
                        projects: [],
                        timers: []
                    };
                    tm.savePreferences(global.ids.memsName, global.mems);
                } else {
                    global.mems = JSON.parse(currentMems);
                }
                $('.line, .line span').css('font-size', global.mems.currentFontSize);
            },
            setGitlabUserId () {
                tm.getContainer({
                    'el': '.header-user-dropdown-toggle',
                    'max': 100,
                    'spd': 1000
                }).then(function($container){
                    var myHref = document.querySelector('.header-user-dropdown-toggle').href;
                    global.ids.gitlabUserId = myHref.substr(myHref.lastIndexOf('/')+1, myHref.length - myHref.lastIndexOf('/')-1);
                });
            },
            addClasses: function () {
                if (!global.states.areClassesAdded) {
                    global.states.areClassesAdded = true;

                    // generic
                    if (global.prefs.hideCodeErrClass) tm.addGlobalStyle('.err { background-color: inherit !important; }');
                    tm.addGlobalStyle('.tamperlabel { cursor: pointer; }');
                    tm.addGlobalStyle('.btn-headerly { padding:3px 10px; height:30px; margin-top:5px !important; margin-left:0px !important; background:steelblue; border-color:darkslategray; }');
                    tm.addGlobalStyle('.btn-headerly:hover { background-color:aliceblue; border-color:black; }');

                    // breadcrumb
                    tm.addGlobalStyle('.js-breadcrumb-item-text { font-size:0.625rem; }');

                    // colored backgrounds
                    tm.addGlobalStyle('.merge-request-tabs-container {background:' + global.prefs.colorNavBackground + '; }');
                    tm.addGlobalStyle('.merge-request-tabs {background:' + global.prefs.colorNavButton + '; }');
                    tm.addGlobalStyle('.mr-widget-content {background:' + global.prefs.colorHeadline + '; }');
                    // tm.addGlobalStyle('.active {background:' + global.prefs.colorActiveTab + '; }');

                    // UI-sizing
                    tm.addGlobalStyle('.diff-files-holder.container-limited { max-width: inherit !important; }');
                    tm.addGlobalStyle('.approvals-required-text .avatar {width:24px; height:24px; }');
                    if (global.prefs.minimizeMetaInfo) {
                        tm.addGlobalStyle('.note-text ul {margin:0px !important; }');
                        tm.addGlobalStyle('.system-note {font-size:0.7em; padding:0; margin:0px !important; }');
                        tm.addGlobalStyle('.timeline-entry:hover {background:aliceblue; }');
                        tm.addGlobalStyle('.note-text .gfm-merge_request {background:aliceblue; padding:10px; float:right; position:relative; top:-23px; margin-bottom:-28px; }');
                    }
                    tm.addGlobalStyle('#lessImportant { width:260px; overflow:hidden; background-color:azure; }');
                    tm.addGlobalStyle('.lessImportantCollapsed { max-height:30px; }');

                    tm.addGlobalStyle('.tamperNewIcon {position:relative; top:-10px; }');

                    tm.addGlobalStyle('.nothing-here-block {display: none;}');

                    tm.addGlobalStyle('.beepboop { background-color:powderblue !important;}');

                    // pipelines
                    _.each(global.prefs.pipelineLogFilters, (filter) => {
                        tm.addGlobalStyle('.pipelineLog-' + filter.name.replace(/ /g, '') + ' { background-color:' + filter.background + '; ' + (filter.color ? 'color:' + filter.color + ';' : '') + ' padding-right:1rem; }');
                    });
                    tm.addGlobalStyle('.growl { opacity:0.9; }');
                    tm.addGlobalStyle('.growlMessage { overflow-y:auto; max-height:350px; background:white; color:black; }');

                    // merge requests
                    tm.addGlobalStyle('.mrNeeds { position:absolute; right:11.875rem; top:2rem; min-width:18.75rem; text-align:right; }');
                    tm.addGlobalStyle('.mrNeed { float:right; margin-left:0.625rem; border-radius:25px; border:1px solid ' + global.prefs.colorHeadline + '; padding:0 1rem; }');
                    _.each(global.prefs.colorsRules, (colorRule) => {
                        tm.addGlobalStyle('.mr' + colorRule.ruleName.replace(/ /g, '') + ' { background:' + colorRule.hexName + '; }');
                    });

                    // Pivotal Tracker-related
                    tm.addGlobalStyle('.ptComment { padding: 0.2rem; margin-bottom: 0.625rem; max-width: 17rem; }');
                    tm.addGlobalStyle('.ptTimestamp { font-size: 0.625rem; margin-left: 3rem; }');
                    tm.addGlobalStyle('.reviewsEl { flex:1 0 auto; }');
                    tm.addGlobalStyle('.reviewEl { float:right; margin-right:0.125rem; border-radius:1rem; border:2px solid white; padding:.25rem; }');
                    tm.addGlobalStyle('.ptIcon { margin-right:8px; color:white; }');
                    tm.addGlobalStyle('.userTeamsLink { height:34px; padding:10px; margin:0; background:beige; border-radius:25px; }');
                    tm.addGlobalStyle('#pivotalStoryDescription { float:right; width:190px; overflow:hidden; height:30px; margin:1rem 0 0 1rem; ' +
                                      '    border-width:2px 2px 2px 16px; border-style:solid; border-color:' + global.prefs.colorNavButton +'; ' +
                                      '    position:relative; transition: all .25s linear; z-index:1; border-radius:25px; }');
                    tm.addGlobalStyle('.pivotalStoryDescriptionExpanded { width:50% !important; height:inherit !important; max-height:350px; overflow-y:auto !important; padding:1rem; border-top-right-radius:0 !important; border-bottom-right-radius:0 !important; }');
                    tm.addGlobalStyle('.pivotalStoryDescriptionText { display:none; cursor:auto; }' +
                                      '.pivotalStoryDescriptionExpanded .pivotalStoryDescriptionText { display:block; }');
                    tm.addGlobalStyle('.pivotalStoryTitle { position:absolute; bottom:3px; right:10px; }' +
                                      '.pivotalStoryDescriptionExpanded .pivotalStoryTitle { position:relative; top:-16px; left:20px; padding:0 10px; border-bottom-left-radius:10px; border-bottom-right-radius:10px; background-color:' + global.prefs.colorNavButton + '; width:90%; }');
                    if (global.prefs.pivotalToken.length > 0) {
                        tm.addGlobalStyle('[data-qa-selector="approvals_summary_content"] { max-width:22rem; }');
                        tm.addGlobalStyle('.ptReply { margin-left:5px; font-family: Andale Mono; font-size:10px; text-transform:uppercase; text-decoration:underline; }');
                    }
                }
            },
            addFaves: function() { // adds shorcut buttons to your favorite projects
                // if areFavesAdded is false
                if (!global.states.areFavesAdded) {
                    global.states.areFavesAdded = true;
                    if (global.prefs.userFaves.length === 0) {
                        return;
                    }
                    try {
                        global.prefs.userFaves = global.prefs.userFaves.replace(/\s\s+/g, '').split(';');
                        tm.savePreferences(global.ids.prefsName, global.prefs);
                    } catch(e) {
                        utils.debug('Safe failing while trying to parse userFaves object');
                    }
                    // for each Fave
                    global.prefs.userFaves.forEach((fave) => {
                        // add a button
                        var jsoned = {};
                        try {
                            jsoned = JSON.parse(fave);
                            fave = jsoned.url;
                        }
                        catch (e) {
                            utils.debug('SAFE FAIL while parsing a user favorite:\n' + e);
                        }
                        var titleContainer = $('header .title-container');
                        var slashPosition = fave.lastIndexOf('/')+1;
                        var faveName = jsoned.name ? jsoned.name : fave.substr(slashPosition, fave.length-slashPosition);
                        titleContainer.append('<a id="fave' + faveName + '" href="' + fave + '" class="btn btn-default btn-headerly fingery">' + faveName + '</a>');
                    });
                }
            },
            adjustStyles: function() { // adjusts colors of discussions based on whether that discussion is resolved or not
                var lePass = global.prefs.colorResolved,
                    leFail = global.prefs.colorUnresolved,
                    botDivs = [],
                    botDivsRegex = new RegExp("Gitbot|ServiceCOMTeamCity");

                botDivs = $(".discussion-notes .timeline-content").filter(function () {
                    return botDivsRegex.test($(this).text());
                });

                botDivs.each(function(discussion) {
                    if ($(this).closest('.card').find('button:contains("Resolve")').length > 0) {
                        $(this).css('background-color', leFail);
                    } else {
                        if ($(this).text().indexOf('Resolved') > 0) {
                            $(this).css('background-color', lePass);
                        }
                    }
                });

                $('.timeline-entry .discussion-header').each(function(discussion) {
                    //
                    $(this).closest('.timeline-entry :contains("Resolve")').find('.discussion-header').css('background-color', leFail);
                    $(this).closest('.timeline-entry :contains("Resolved")').css('background-color', lePass);
                });

                var intX = 0;
                $('.notes').each(function(discussion) {
                    if (intX > 1 && intX < $('.notes').length-1) {
                        if ($(this).find('.discussion-resolved-text').length > 0) {
                            $(this).find('li').eq(0).css('background-color', lePass);
                        } else {
                            $(this).find('li').eq(0).css('background-color', leFail);
                        }
                    }
                    intX++;
                });

//                 // clean-up.  could be done better, I'm sure
//                 document.querySelectorAll(".timeline-entry").forEach(function(te) {
//                     var thisChild = te.querySelector(".timeline-entry");
//                     if (thisChild) {
//                         $(thisChild).css('background-color', 'inherit');
//                     }
//                 });
            },
            addElements: function() {
                $('button:contains("Expand all")').hide();
                var topScrollTarget = $('.group-path');
                var conversationScrollTarget = $('.js-mr-approvals').length > 0 ? $('.js-mr-approvals') :
                $('button:contains("Approve")').parent().length > 0 ? $('button:contains("Approve")').parent() :
                $('strong:contains("Merge request approved")').parent().parent();
                var idTop = 'idTop',
                    idConversations = 'idConversations',
                    idViewSite = 'idViewSite',
                    conversationsClass = '.header-new',
                    addConversationsButton = function () {
                        var buttonAnchor = $(conversationsClass),
                            topAction = function () {
                                $('html, body').animate({ scrollTop: topScrollTarget.offset().top -100 }, 500);
                                return false;
                            },
                            conversationsAction = function () {
                                var event,
                                    eventType = 'click';
                                if (window.CustomEvent && typeof window.CustomEvent === 'function') {
                                    event = new CustomEvent(eventType, {detail: {some: 'data'}});
                                } else {
                                    event = document.createEvent('CustomEvent');
                                    event.initCustomEvent(eventType, true, true, {some: 'data'});
                                }
                                var el = document.getElementsByClassName('notes-tab')[0].querySelector('a');
                                el.dispatchEvent(event);
                                $('html, body').animate({ scrollTop: conversationScrollTarget.offset().top -100 }, 500);
                            },
                            viewSiteAction = function () {
                                document.querySelector('[data-track-event="open_review_app"]').click();
                                return false;
                            };

                        // Conditionally add View Site Button
                        tm.getContainer({
                            'el': '[aria-label="deploy-reviewapp: passed"]',
                            'max': 100,
                            'spd': 250
                        }).then(function($container){
                            buttonAnchor.before('<a id="' + idViewSite + '" class="btn btn-default btn-headerly fingery">View</a>'); // --- VIEW SITE BUTTON
                            $('#' + idViewSite).click(viewSiteAction);
                        });
                        buttonAnchor.before('<a id="' + idConversations + '" class="btn btn-default btn-headerly fingery">Act</a>'); // --- ACT BUTTON
                        $('#' + idConversations).click(conversationsAction);
                        buttonAnchor.before('<a id="' + idTop + '" class="btn btn-default btn-headerly fingery">Top</a>'); // --- TOP BUTTON
                        $('#' + idTop).click(topAction);
                    },
                    addCollapseExpandButtonToDom = function(bId, bAnchor, bAction, bText) {
                        bAnchor.after('<a id="' + bId + '" class="btn btn-default append-right-8 fingery">' + bText + '</a>');
                        $('#' + bId).unbind('click').click(bAction);
                    },

                    idCollapse = 'idCollapse',
                    collapseClass = '.is-compare-versions-header',
                    addCollapseButton = function() {
                        var addCollapseButtonToDom = function () {
                            addCollapseExpandButtonToDom(idCollapse, buttonAnchor, collapseAction, 'Collapse All');
                        },
                            buttonAnchor = $(collapseClass),
                            collapseAction = function () {
                                _.each($('.diff-content'), (diff) => {
                                    if ($(diff).height() > 0) {
                                        $(diff).closest('.diff-file').find('.file-title').click();
                                    }
                                });
                                $(this).remove();
                                addExpandButton();
                            };
                        addCollapseButtonToDom();
                        $('a:contains("Expand all")').hide();
                    },

                    idExpand = 'idExpand',
                    expandClass = '.is-compare-versions-header',
                    addExpandButton = function() {
                        var addExpandButtonToDom = function () {
                            addCollapseExpandButtonToDom(idExpand, buttonAnchor, expandAction, 'Expand All');
                        },
                            buttonAnchor = $(expandClass),
                            expandAction = function () {
                                _.each($('.diff-collapsed'), (diff) => {
                                    $(diff).closest('.diff-file').find('.file-title').click();
                                });
                                $(this).remove();
                                addCollapseButton();
                            };
                        addExpandButtonToDom();
                    },

                    idComparisonFont = 'idComparisonFont',
                    comparisonFontClass = '.is-compare-versions-header',
                    addComparisonFontButton = function() {
                        var buttonAnchor = $(comparisonFontClass),
                            comparisonFontAction = function () {
                                var buttonText = $('#' + idComparisonFont).text();
                                if (global.mems.currentFontSize === global.mems.defaultLineSize) {
                                    global.mems.currentFontSize = global.mems.smallLineSize;
                                    $('#' + idComparisonFont).text(buttonText.replace('-', '+'));
                                } else {
                                    global.mems.currentFontSize = global.mems.defaultLineSize;
                                    $('#' + idComparisonFont).text(buttonText.replace('+', '-'));
                                    // actual setting of font size done during monitoring of page, so mouse movement can trigger it
                                }
                                tm.savePreferences(global.ids.memsName,global.mems);
                            };
                        buttonAnchor.after('<a id="' + idComparisonFont + '" class="btn btn-default append-right-8 fingery">Font -</a>'); //  Font +- button
                        $('#' + idComparisonFont).unbind('click').click( comparisonFontAction);
                        if (global.mems.currentFontSize !== global.mems.defaultLineSize) { // to fix UI if button was previously saved in alternate setting
                            global.mems.currentFontSize = global.mems.defaultLineSize;
                            comparisonFontAction();
                        }
                    },

                    idHeader = 'idHeader',
                    headerClass = '.header-message',
                    addHeaderButton = function() {
                        var buttonAnchor = $(headerClass),
                            headerAction = function () {
                                var msg = $(headerClass + ' p').text();
                                if (!_.contains(global.mems.archivedMessages, msg)) {
                                    global.mems.archivedMessages.push(msg);
                                    tm.savePreferences(global.ids.memsName,global.mems);
                                }
                                buttonAnchor.hide();
                                // special for header
                                $('.navbar').css('top', '0px');
                                $('.nav-sidebar').css('top', '40px');
                                $('.content-wrapper').css('margin-top', '40px');
                                return false;
                            };
                        buttonAnchor.prepend('<i id="' + idHeader + '" class="fa fa-times outlined fingery"></i>'); // "X" button
                        $('#' + idHeader).click(headerAction);
                        // if a previously-hidden header message is showing again
                        if ($(headerClass).css('display') !== 'none') {
                            _.each(global.mems.archivedMessages, function(msg) {
                                if ($(headerClass + ' p').text() == msg) {
                                    headerAction();
                                }
                            });
                        }
                    },

                    idFooter = 'idFooter',
                    footerClass = '.footer-message',
                    addFooterButton = function() {
                        var buttonAnchor = $(footerClass),
                            footerAction = function () {
                                var msg = $(footerClass + ' p').text();
                                if (!_.contains(global.mems.archivedMessages, msg)) {
                                    global.mems.archivedMessages.push(msg);
                                    tm.savePreferences(global.ids.memsName,global.mems);
                                }
                                buttonAnchor.hide();
                                return false;
                            };
                        buttonAnchor.prepend('<i id="' + idFooter + '" class="fa fa-times outlined fingery"></i>'); // "X" button
                        $('#' + idFooter).click(footerAction);
                        // if a previously-hidden footer message is showing again
                        if ($(footerClass).css('display') !== 'none') {
                            _.each(global.mems.archivedMessages, function(msg) {
                                if ($(footerClass + ' p').text() == msg) {
                                    footerAction();
                                }
                            });
                        }
                    },

                    idBroadcast = 'idBroadcast',
                    broadcastClass = '.broadcast-message',
                    addBroadcastButton = function() {
                        var buttonAnchor = $(broadcastClass),
                            broadcastAction = function () {
                                var msg = $(broadcastClass + ' p').text();
                                if (!_.contains(global.mems.archivedBroadcasts, msg)) {
                                    global.mems.archivedBroadcasts.push(msg);
                                    tm.savePreferences(global.ids.memsName,global.mems);
                                }
                                buttonAnchor.hide();
                                return false;
                            };
                        buttonAnchor.prepend('<i id="' + idBroadcast + '" class="fa fa-times outlined fingery"></i>'); // "X" button
                        $('#' + idBroadcast).click( broadcastAction);
                        // if a previously-hidden  broadcast message is showing again
                        if ($( broadcastClass).css('display') !== 'none') {
                            _.each(global.mems.archivedBroadcasts, function(msg) {
                                if ($( broadcastClass + ' p').text() == msg) {
                                    broadcastAction();
                                }
                            });
                        }
                    },

                    idUserTeams = 'idUserTeams',
                    userTeamsClass = '.user-popover',
                    addUserTeamsButton = function() {
                        var buttonAnchor = $(userTeamsClass);
                        buttonAnchor.append('<i id="' + idUserTeams + '" class="userTeamsLink fa fa-bullhorn outlined fingery" style="font-weight:bold;"></i>'); // "X" button
                        var emailName = document.querySelector(userTeamsClass).querySelector('.text-secondary').innerText.replace('@', '');
                        $('#' + idUserTeams).click( function() {
                            utils.userTeamsAction(emailName);
                        });
                    },

                    idFilterMerges = 'idFilterMerges',
                    filterMergesClass = '.top-area .nav-controls',
                    addFilterMergesButton = function() {
                        var buttonAnchor = $(filterMergesClass);
                        buttonAnchor.prepend('<button id="' + idFilterMerges + '" class="btn append-right-10">My Checklist</button>'); // FILTER MERGES
                        var filterMergeHref = document.URL + '?scope=all&utf8=%E2%9C%93&state=opened&approver_usernames[]=USERME&wip=no&not[author_username]=USERME&only=me';
                        filterMergeHref = filterMergeHref.replace(/USERME/g, global.ids.gitlabUserId);
                        $('#' + idFilterMerges).click( function() {
                            window.location.href = filterMergeHref;
                        });
                    },

                    idShowNeeds = 'idShowNeeds',
                    showNeedsClass = '.top-area .nav-controls',
                    addShowNeedsButton = function() {
                        var buttonAnchor = $(showNeedsClass);
                        buttonAnchor.prepend('<button id="' + idShowNeeds + '" class="btn append-right-10">Show Needed Approvals</button>'); // NEEDED APPROVALS

                        $('#' + idShowNeeds).click( function() {
                            var iAm = 'showNeeds',
                                merges = document.querySelectorAll('.issuable-reference'),
                                getApprovals = function(mergeId, callback) {
                                    // Set up our HTTP request
                                    var xhr = new XMLHttpRequest();

                                    // Setup our listener to process completed requests
                                    xhr.onload = function () {
                                        global.states.xhrBusy = false;

                                        // Process our return data
                                        if (xhr.status >= 200 && xhr.status < 300) {
                                            // What do when the request is successful

                                            var resp = xhr.response;
                                            if (resp) {
                                                resp = JSON.parse(resp);
                                                callback(resp.approval_rules_left);
                                            }
                                        } else {
                                            tm.log('XHR for ' + iAm + ' failed!');
                                        }
                                    };

                                    xhr.open('GET', 'https://gitlab.dell.com/api/v4/projects/' + document.querySelector('body').getAttribute('data-project-id') + '/merge_requests/' + mergeId + '/approvals');
                                    xhr.send();

                                };
                            _.each(merges, (thisMerge) => {
                                var thisMergeId = thisMerge.innerText.replace(/( |\!)/g, '');
                                getApprovals(thisMergeId, function(remainingRules) {
                                    remainingRules = remainingRules.slice().reverse();
                                    var mrNeeds;
                                    if (remainingRules.length > 0) {
                                        mrNeeds = '<div class="mrNeeds">Approval needed from: ';
                                    } else {
                                        mrNeeds = '<div class="mrNeeds"><div class="mrNeed mrReadytoMerge">Ready to Merge</div>';
                                    }
                                    _.each(remainingRules, (remainingRule) => {
                                        mrNeeds += '<div class="mrNeed mr' + remainingRule.name.replace(/ /g, '') + '">' + remainingRule.name + '</div>';
                                    });
                                    mrNeeds += '</div>';
                                    $('.issuable-reference:contains("!' + thisMergeId + '")').closest('.issuable-info-container').append(mrNeeds);
                                });
                            });
                        });
                    },
                    idAlert = 'idAlert',
                    alertClass = '.broadcast-banner-message',
                    addAlertButton = function() {
                        var buttonAnchor = $(alertClass),
                            alertAction = function () {
                                var msg = $(alertClass + ' p').text();
                                if (!_.contains(global.mems.archivedAlerts, msg)) {
                                    global.mems.archivedAlerts.push(msg);
                                    tm.savePreferences(global.ids.memsName,global.mems);
                                }
                                buttonAnchor.hide().attr("style", "display: none !important");;
                                return false;
                            };
                        buttonAnchor.prepend('<i id="' + idAlert + '" class="fa fa-times outlined fingery"></i>'); // "X" button
                        $('#' + idAlert).click(alertAction);
                        // if a previously-hidden alert message is showing again
                        if ($( alertClass).css('display') !== 'none') {
                            _.each(global.mems.archivedAlerts, function(msg) {
                                if ($( alertClass + ' p').text() == msg) {
                                    alertAction();
                                }
                            });
                        }
                    },

                    idPivotal = 'idPivotalComments',
                    pivotalAnchor = '.issuable-sidebar',
                    addPivotalButton = function () {
                        var buttonAnchor = $(pivotalAnchor),
                            pivotalAction = function () {
                                $('.participants .sidebar-collapsed-icon').click();
                            };

                        buttonAnchor.append('<div id="' + idPivotal + '" class="block pivotal-reference">' +
                                            global.templates.pivotalComment +
                                            '</div>'); // --- PIVOTAL BUTTON


                        $('#' + idPivotal).click(pivotalAction);
                    };

                if (document.URL.indexOf('merge_requests') < 0) {
                    $('#' + idConversations).remove();
                    $('#' + idCollapse).remove();
                    $('#' + idExpand).remove();
                    $('#' + idPivotal).remove();
                    $('#' + idFilterMerges).remove();
                    $('#' + idShowNeeds).remove();
                    global.states.arePrButtonsAdded = false;
                } else {
                    if (!global.states.arePrButtonsAdded) {
                        global.states.arePrButtonsAdded = true;

                        tm.getContainer({
                            'el': showNeedsClass,
                            'max': 100,
                            'spd': 1000
                        }).then(function($container){
                            addShowNeedsButton();
                        });

                        tm.getContainer({
                            'el': filterMergesClass,
                            'max': 100,
                            'spd': 1000
                        }).then(function($container){
                            addFilterMergesButton();
                        });

                        tm.getContainer({
                            'el': conversationsClass,
                            'max': 100,
                            'spd': 1000
                        }).then(function($container){
                            addConversationsButton();
                        });

                        tm.getContainer({
                            'el': collapseClass,
                            'max': 100,
                            'spd': 1000
                        }).then(function($container){
                            addComparisonFontButton();
                            addCollapseButton();
                        });

                        if (document.URL.indexOf('merge_requests/') > -1) { // we are on a specific merge review, not the index of reviews, when it has the slash
                            page.pivotal.getReviews();
                            tm.getContainer({
                                'el': pivotalAnchor,
                                'max': 100,
                                'spd': 1000
                            }).then(function($container){
                                addPivotalButton();
                            });
                        }
                    }

                    // outside of arePrButtonsAdded check for xhr allowance
                    if (document.URL.indexOf('merge_requests/') > -1) { // only process when on a specific merge_request
                        if (!global.states.xhrBusy && !$('.ptComment').length > 0) {
                            tm.getContainer({
                                'el': pivotalAnchor,
                                'max': 100,
                                'spd': 1000
                            }).then(function($container){
                                page.pivotal.getComments();
                            });
                        }
                    }
                }


                // Constantly poll for user profile popup
                setTimeout(function() {
                    if (document.querySelector(userTeamsClass) != null && document.querySelector('.userTeamsLink') == null) {
                        addUserTeamsButton();
                    }
                }, TIMEOUT*2);

                if (!global.states.areInterfaceButtonsAdded) {
                    global.states.areInterfaceButtonsAdded = true;
                    tm.getContainer({
                        'el': headerClass,
                        'max': 100,
                        'spd': 1000
                    }).then(function($container){
                        addHeaderButton();
                    });

                    tm.getContainer({
                        'el': footerClass,
                        'max': 100,
                        'spd': 1000
                    }).then(function($container){
                        addFooterButton();
                    });

                    tm.getContainer({
                        'el': broadcastClass,
                        'max': 100,
                        'spd': 1000
                    }).then(function($container){
                        addBroadcastButton();
                    });

                    tm.getContainer({
                        'el': alertClass,
                        'max': 100,
                        'spd': 1000
                    }).then(function($container){
                        addAlertButton();
                    });
                }

            },
            adjustMarkdown: function () {
                if (!global.prefs.useThumbnailImages) {
                    return;
                }
                if ($('.mdImg').length > 0) {
                    return;
                }
                tm.addGlobalStyle('.md img { max-width:25% !important; }');
                _.each($('.md img'), (mdImg) => {
                    $(mdImg).parent().addClass('mdImg');
                });
                $('.mdImg').click(function(e) {
                    e.preventDefault();
                    var modalBody = '<img id="tsImgPreview" src="' + e.target.src + '" onclick="$(this).parent().remove()" />' +
                        '<style>' +
                        '.popupDetailTitle, .tamperModalClose { display:none; } ' +
                        '.popupDetailWindow { width:95%; height:inherit; max-height:90%; ' +
                        'background-image:' +
                        '      linear-gradient(45deg, #EEE 25%, transparent 25%),' +
                        '      linear-gradient(45deg, transparent 75%, #EEE 75%),' +
                        '      linear-gradient(45deg, transparent 75%, #EEE 75%),' +
                        '      linear-gradient(45deg, #EEE 25%, transparent 25%);' +
                        'background-size:100px 100px;' +
                        'background-position:0 0, 0 0, -50px -50px, 50px 50px;' +
                        '}' +
                        '.popupDetailWindow img { ' +
                        'max-width:100%; ' +
                        'max-height:' + $(document).height() + 'px; ' +
                        'display:block; ' +
                        'margin:auto; ' +
                        '}' +
                        '</style>';
                    tm.showModal('imgCloseup', modalBody);
                });
            },
            appendClickFunctions: function () {
                if (document.URL.indexOf('merge_requests') > 0 && global.ids.pivotal.project != null) {
                    var approveSelector = '[data-qa-selector="approve_button"]';
//                     if (!document.querySelector(approveSelector)) {
//                         $('.merge-request-tabs-container').append('<button data-qa-selector="approve_button" class="fakey">FAKEY</button>');
//                     }
                    tm.getContainer({
                        'el': approveSelector,
                        'max': 100,
                        'spd': 1000
                    }).then(function($container){
                        var approveButton = document.querySelector(approveSelector);
                        if (!approveButton.classList.contains('tm-approveButton')) { // only do this once
                            approveButton.classList.add('tm-approveButton');
                            approveButton.addEventListener('click', function approveAppendActions() {
                                if (approveButton && !approveButton.classList.contains('btn-inverted')) { // YET TO APPROVE OR RE-APPROVE *on gitlab* // FAKEY REVERT !approveButton
                                    // approveButton.removeEventListener('click', approveAppendActions);
                                    if (document.querySelector('[data-reviewer_id="' + global.ids.pivotal.project.me.id + '"]')) { // already exists on PT; don't add another
                                        return;
                                    }
                                    var review_type_id;
                                    if (global.mems.pivotalData.my_review_type_id) {
                                        page.pivotal.postReview(global.mems.pivotalData.my_review_type_id);
                                    } else {
                                        var modalBody = '<div style="text-align:center; padding:2rem;"><p>Copying this to Pivotal Tracker.  Is this a CODE or DESIGN review?</p>' +
                                            '<p><button id="confirmCode" class="confirmReviewType" value="Code">CODE</button>&nbsp;&nbsp;&nbsp;' +
                                            '<button id="confirmDesign" class="confirmReviewType" value="Design Review">DESIGN</button></p>' +
                                            '<p><input id="checkRememberReviewType" type="checkbox">Remember my choice</input></p>' +
                                            '</div>' +
                                            '<style>.popupDetailTitle, .tamperModalClose { display:none; } .popupDetailWindow { width:95%; min-height:85% height:inherit; max-height:95%; }</style>';
                                        tm.showModal('confirmReviewType', modalBody);
                                        _.each(document.querySelectorAll('.confirmReviewType'), (confirmTypeButton) => {
                                            utils.listenOnce(confirmTypeButton, 'click', (e) => {
                                                review_type_id = JSON.parse(global.ids.pivotal.project.review_types).review_types.find((x) => x.name === e.target.value).id;
                                                if (document.getElementById('checkRememberReviewType').checked) {
                                                    utils.debug('Remembering your choice... ' + review_type_id);
                                                    global.mems.pivotalData.my_review_type_id = review_type_id;
                                                    tm.savePreferences(global.ids.memsName, global.mems);
                                                }
                                                $('#confirmReviewType').remove();
                                                page.pivotal.postReview(review_type_id);
                                            });
                                        });
                                    }
                                } else { // HAS BEEN APPROVED, so when un-approving, do this:
                                    var review_id = parseInt(document.querySelector('[data-reviewer_id="' + global.ids.pivotal.project.me.id + '"]').getAttribute('data-review_id'));
                                    $('[data-reviewer_id="' + global.ids.pivotal.project.me.id + '"]').remove();
                                    page.pivotal.deleteReview(review_id);
                                }
                            });
                        }
                    });
                }

                // APPEND ONLY ONCE:
                if (global.states.appendClickProcessed) {
                    return;
                }
                global.states.appendClickProcessed = true;

                // TODO: THINK ABOUT THIS.
//                 function appendDiffsClick() {
//                     var resetMergeRequestScan = function() {
//                         global.states.mergeRequestScanned = false;
//                     };
//                     $('[data-action="diffs"]').on('click', resetMergeRequestScan);
//                 }
//                 tm.getContainer({
//                     'el': '[data-action="diffs"]',
//                     'max': 100,
//                     'spd': 1000
//                 }).then(function($container){
//                     appendDiffsClick();
//                 });

                function appendFileTitleClicks() {
                    var scrollAfterCollapse = function() {
                        if ($(this).offset().top < $(window).scrollTop() + 125) {
                            $('html, body').animate({ scrollTop: $(this).offset().top-160 }, 1000);
                        }
                    };
                    $('.file-title').on('click', scrollAfterCollapse);
                };
                tm.getContainer({
                    'el': '.file-title',
                    'max': 100,
                    'spd': 1000
                }).then(function($container){
                    appendFileTitleClicks();
                });

            },
            collapseSidebarLowPriorities: function () {
                if (document.getElementById('lessImportant') != null || global.ids.pivotal.project == null) {
                    return;
                }
                $('.qa-assignee-block').css('border-bottom', '0px');
                $('.qa-assignee-block').after('<div id="lessImportant" class="lessImportantCollapsed"><button id="lessImpToggle" class="btn btn-default hide-collapsed" style="width:100%;">Show Tools</button><div id="aHackySpacer" style="width:100%; height:30px; background:#fafafa;"></div></div>');
                document.getElementById('lessImportant').appendChild(document.querySelector('.milestone'));
                document.getElementById('lessImportant').appendChild(document.querySelector('.time_tracker').parentElement);
                document.getElementById('lessImportant').appendChild(document.querySelector('.labels'));
                document.getElementById('lessImportant').appendChild(document.querySelector('#js-lock-issue-data'));
                document.getElementById('lessImportant').appendChild(document.querySelector('.lock'));
                document.getElementById('lessImportant').appendChild(document.querySelector('.project-reference'));
                document.getElementById('lessImportant').onclick = function(e) {
                    e.preventDefault();
                    if (document.getElementById('lessImportant').classList.contains('lessImportantCollapsed')) {
                        e.target.innerText = 'Hide Tools';
                        document.getElementById('lessImportant').classList.remove('lessImportantCollapsed');
                        $('#aHackySpacer').hide();
                    } else {
                        e.target.innerText = 'Show Tools';
                        document.getElementById('lessImportant').classList.add('lessImportantCollapsed');
                        $('#aHackySpacer').show();
                    }
                };
            },
            dimApprovedRequests: function () {
                if (!document.URL.indexOf('/merge_requests/') > 0) {
                    return;
                }
                _.each($('use[*|href*="approval-solid"]'), (svg) => {
                    if (document.URL.indexOf('only=me') > 0) {
                        $(svg).closest('.merge-request').hide();
                    } else {
                        $(svg).closest('.merge-request').css('background-color', global.prefs.colorDim1);
                    }
                });
                _.each($('a[data-qa-selector="assignee_link"]'), (assignee) => {
                    if (assignee.href.indexOf(global.ids.gitlabUserId) > -1) {
                        $(assignee).closest('.merge-request').css('background-color', global.prefs.colorDim2);
                    }
                });
            },
            expandBreadcrumb: function () {
                $('.breadcrumbs .dropdown li').prependTo('.breadcrumbs-list .dropdown');
                $('.breadcrumbs-list .identicon').hide();
                $('.breadcrumbs-list .dropdown button').hide();
            },
            pivotal: {
                defineProject: function () {
                    var cite;
                    if (global.ids.pivotal.project) {
                        return;
                    }
                    if (document.querySelector('cite')) {
                        cite = document.querySelector('cite').innerText.replace(/\n|\r/g, '');
                        cite = cite.substr(cite, cite.indexOf('!'))
                        global.ids.pivotal.gitlabRelation = global.prefs.pivotalMaps.find((x) => x.reference === cite);
                    }
                    if (document.querySelector('cite') && global.ids.pivotal.gitlabRelation != null) {
                        if (global.mems.pivotalData.projects.length > 0) {
                            global.ids.pivotal.project = global.mems.pivotalData.projects.find((x) => x.project_id === parseInt(global.ids.pivotal.gitlabRelation.project_id));
                            if (global.prefs.debugMode) {
                                tm.log('SETTING PIVOTALPROJECT OBJECT');
                                console.dir(global.ids.pivotal.project);
                            }
                        } else {
                            utils.debug('setPivotalInfo FAILURE: pivotalData.projects is empty!');
                            global.mems.pivotalData.timeUpdated = null;
                            page.pivotal.getMembers();
                        }
                    } else if (global.prefs.debugMode) {
                        tm.log('setPivotalInfo failed:\n' +
                               '   global.mems.pivotalData.projects.length = ' + global.mems.pivotalData.projects.length + '\n' +
                               '   cite = ' + cite + '\n' +
                               '   global.ids.pivotal.gitlabRelation = ' + global.ids.pivotal.gitlabRelation);
                    }
                },
                deleteReview: function(review_id) {
                    var iAm = 'deleteReview';
                    var whenDataReceived = function (resp) {
                        // does not call on a delete
                    };
                    utils.xhrAction(iAm, 'DELETE', 'stories/PIVOTALSTORYID/reviews/' + review_id, whenDataReceived);
                },
                getMe: function() {
                    var iAm = 'getMe';
                    if (!utils.pivotalHoursElapsed(iAm, 24)) {
                        return;
                    }
                    var whenDataReceived = function (resp) {
                        resp = JSON.parse(resp);
                        global.ids.pivotal.project.me = global.mems.pivotalData.projects.find(x => x.project_id === global.ids.pivotal.project.project_id).me = resp;
                    };
                    var finallyDoThis = function() {
                        tm.savePreferences(global.ids.memsName, global.mems);
                    };
                    utils.delayUntil(iAm, () => {return global.ids.pivotal.project != null;}, () => {
                        utils.xhrAction(iAm, 'GET', 'me', whenDataReceived, finallyDoThis);
                    });
                },
                getMembers: function () {
                    var iAm = 'getMembers';
                    if (!utils.pivotalHoursElapsed(iAm, 2)) {
                        return;
                    }
                    var whenDataReceived = function (resp) {
                        resp = JSON.parse(resp).slice().reverse();

                        if (!global.mems.pivotalData.projects.find(x => x.project_id === resp[0].project_id)) {
                            global.mems.pivotalData.projects.push(
                                {
                                    'project_id': resp[0].project_id,
                                    'members': resp
                                }
                            );
                        } else {
                            global.mems.pivotalData.projects.find(x => x.project_id === resp[0].project_id).members = resp;
                        }
                    };
                    var finallyDoThis = function() {
                        tm.savePreferences(global.ids.memsName, global.mems);
                    };
                    utils.xhrAction(iAm, 'GET', 'memberships', whenDataReceived, finallyDoThis); // DO NOT DELAY UNTIL global.ids.pivotal.project is defined. THIS DEFINES IT.
                },
                getComments: function () {
                    if (global.ids.pivotal.project == null || global.ids.pivotal.project.members == null || utils.getPivotalStoryId() == null) {
                        utils.debug('getComments failed; global.ids.pivotal.project must be defined.');
                        return;
                    }
                    var whenDataReceived = function (resp) {
                        var iAm = 'ptCommentary';
                        var comTitle = document.createElement('div');
                        comTitle.innerHTML = '<h5 class="hide-collapsed ptComment">Pivotal Tracker Comments</h5>';
                        document.querySelector('#idPivotalComments').appendChild(comTitle);

                        var comInput = document.createElement('div');
                        comInput.className = 'ptCommentInput hide-collapsed';
                        comInput.innerHTML = '<textarea id="ptSayText" style="width:250px; height:100px;"></textarea><br /><button id="ptSaySubmit" type="submit" class="btn btn-default" style="margin-left:184px;">Submit</button>';
                        document.querySelector('#idPivotalComments').appendChild(comInput);
                        document.getElementById('ptSaySubmit').onclick = function () {
                            if (document.getElementById('ptSayText').value.length > 0) {
                                var whenDataReceived = function(resp) {
                                    $('#idPivotalComments').html(global.templates.pivotalComment);
                                    page.pivotal.getComments();
                                };
                                utils.xhrAction(iAm, 'POST', 'stories/PIVOTALSTORYID/comments', whenDataReceived, null, {
                                    "text": document.getElementById('ptSayText').value,
                                    "person_id": global.ids.pivotal.project.me.id
                                });
                            }
                        };

                        var commentTop = document.getElementById('ptSayText').getBoundingClientRect().top - 100;

                        resp = JSON.parse(resp).slice().reverse();
                        var commentTotal = 0;
                        _.each(resp, (comment) => {
                            commentTotal++;
                            var person = global.ids.pivotal.project.members.find((x) => x.person.id === comment.person_id).person;
                            var comDiv = document.createElement('div');
                            comDiv.className = 'ptComment hide-collapsed';
                            comDiv.innerHTML = '<div class="ptTimestamp" title="' + moment(comment.updated_at).format('MMMM Do YYYY, h:mm:ss a') + '">' + moment(comment.updated_at).fromNow() + '</div>';
                            comDiv.innerHTML += global.templates.default.replace(/IMGID/g, comment.person_id).replace(/IMGALT/g, person.name);
                            comDiv.innerHTML += '<b>' + person.name + '</b> says:<br />' + comment.text;
                            if (person.username != global.ids.pivotal.project.me.username) {
                                comDiv.innerHTML += '<a href="javascript:void(0);" onclick="document.getElementById(\'ptSayText\').value+=\' @' + person.username + ' \';  document.querySelector(\'.issuable-sidebar\').scrollTo({top: ' + commentTop + ', behavior: \'smooth\'}); document.getElementById(\'ptSayText\').focus();" class="ptReply">Reply</a>';
                            }
                            if (comment.text && comment.text.indexOf('@') > -1) {
                                var replyAll = comment.text.match(/\B\@\w+/g);
                                if (replyAll.indexOf('@' + global.ids.pivotal.project.me.username) > -1) {
                                    replyAll.splice(replyAll.indexOf('@' + global.ids.pivotal.project.me.username), 1);
                                }
                                if (person.username != global.ids.pivotal.project.me.username) {
                                    replyAll.push('@' + person.username);
                                }
                                replyAll = replyAll.toString().replace(/,/g, ' ');
                                comDiv.innerHTML += '<a href="javascript:void(0);" onclick="document.getElementById(\'ptSayText\').value+=\' ' + replyAll + ' \'; document.querySelector(\'.issuable-sidebar\').scrollTo({top: ' + commentTop + ', behavior: \'smooth\'}); document.getElementById(\'ptSayText\').focus();" class="ptReply">Reply All</a>';
                            }
                            document.querySelector('#idPivotalComments').appendChild(comDiv);
                        });
                        if (commentTotal > 0) {
                            document.getElementById('pivotalParticipants').innerText = commentTotal;
                        }
                    };
                    utils.xhrAction('getComments', 'GET', 'stories/PIVOTALSTORYID/comments', whenDataReceived);
                },
                getReviews: function () {
                    var iAm = 'getReviews';
                    if ($('.reviewsEl').length > 0) {
                        return;
                    }
                    var whenDataReceived = function (resp) {
                        var reviewsEl = '<div class="reviewsEl">',
                            reviewEl = '';
                        resp = JSON.parse(resp);
                        if (resp.length === 0) {
                            reviewEl = '<div class="reviewEl"><i class="ptIcon fa fa-comment"></i></div>';
                            reviewsEl += reviewEl;
                        }
                        _.each(resp, (review) => {
                            reviewEl += '<div class="reviewEl" data-review_id="' + review.id + '">';
                            if (review.reviewer_id) {
                                reviewEl = reviewEl.replace('class="', 'data-reviewer_id="' + review.reviewer_id + '" class="');
                                var person = global.ids.pivotal.project.members.find((x) => x.person.id === review.reviewer_id).person;
                                var imgAlt = person ? person.name : review.reviewer_id;
                                reviewEl += global.templates.default.replace(/IMGID/g, review.reviewer_id).replace(/IMGALT/g, imgAlt).replace('s40', 's20');
                            }
                            var reviewTypeName = JSON.parse(global.ids.pivotal.project.review_types).review_types.find((x) => x.id === review.review_type_id).name;
                            switch (reviewTypeName) {
                                case 'Code':
                                    reviewEl += '<i title="' + reviewTypeName + '" class="ptIcon fa fa-code" style="font-weight:bold;"></i>';
                                    break;
                                case 'Design Review':
                                    reviewEl += '<i title="' + reviewTypeName + '" class="ptIcon fa fa-crop"></i>';
                                    break;
                                case 'Al11y Reqs':
                                    reviewEl += '<i title="' + reviewTypeName + '" class="ptIcon fa fa-universal-access"></i>';
                                    break;
                            }
                            if (review.status === 'pass') {
                                reviewEl += '<i title="PASS" class="ptIcon fa fa-thumbs-up pt' + reviewTypeName.replace(/ /g, '') + '" style="color:' + global.prefs.colorResolved + '" data-review_type_id="' + review.review_type_id + '"></i>';
                            } else if (review.status === 'fail') {
                                reviewEl += '<i title="FAIL" class="ptIcon fa fa-thumbs-down pt' + reviewTypeName.replace(/ /g, '') + '" style="color:' + global.prefs.colorUnresolved + '" data-review_type_id="' + review.review_type_id + '"></i>';
                            } else {
                                reviewEl += '<i title="UNSTARTED" class="ptIcon fa fa-hourglass-start pt' + reviewTypeName.replace(/ /g, '') + ' ptUnstarted"></i>';
                            }
                            reviewEl += '</div>';
                            reviewsEl += reviewEl;
                            reviewEl = '';
                        });
                        reviewsEl += '</div>';
                        $('.js-mr-approvals').append(reviewsEl);
                    };
                    utils.delayUntil(iAm, () => {return (global.ids.pivotal.project != null && global.ids.pivotal.project.project_id != null && global.ids.pivotal.project.review_types != null);}, () => {
                        utils.xhrAction(iAm, 'GET', 'stories/PIVOTALSTORYID/reviews', whenDataReceived);
                    });
                },
                getReviewTypes: function () {
                    var iAm = 'getReviewTypes';
                    if (!utils.pivotalHoursElapsed(iAm, 1) || global.ids.pivotal.gitlabRelation == null) {
                        return;
                    }
                    var whenDataReceived = function (resp) {
                        global.mems.pivotalData.projects.find(x => x.project_id === parseInt(global.ids.pivotal.gitlabRelation.project_id)).review_types = resp;
                        global.ids.pivotal.project.review_types = resp;
                    };
                    var finallyDoThis = function() {
                        tm.savePreferences(global.ids.memsName, global.mems);
                    };
                    utils.delayUntil(iAm, () => {return global.ids.pivotal.project != null;}, () => {
                        utils.xhrAction(iAm, 'GET', '?fields=review_types', whenDataReceived, finallyDoThis);
                    });
                },
                getStory: function () {
                    var iAm = 'getStory';
                    if (!utils.getPivotalStoryId() || global.ids.pivotal.story != null) {
                        return;
                    }
                    var whenDataReceived = function (resp) {
                        resp = JSON.parse(resp);
                        global.ids.pivotal.story = resp;
                        if (!document.getElementById('pivotalStoryDescription')) {
                            $('.issuable-discussion .detail-page-description').prepend('<div id="pivotalStoryDescription" class="fingery ' + (global.mems.pivotalData.states.storyExpanded ? 'pivotalStoryDescriptionExpanded' : '') + '">' +
                                                                                       '<div class="pivotalStoryTitle">Pivotal Story Description</div><div class="pivotalStoryDescriptionText">' + global.ids.pivotal.story.description.replace(/\n/g, '<br />') + '</div></div>');
                            $('.issuable-discussion .detail-page-description').append('<div style="clear:both;"></div>');
                            $('.pivotalStoryDescriptionText').on('click', function(e) {
                                e.preventDefault();
                                e.stopPropagation();
                            });
                            $('#pivotalStoryDescription').on('click', function () {
                                if ($('#pivotalStoryDescription').hasClass('pivotalStoryDescriptionExpanded')) {
                                    $('#pivotalStoryDescription').removeClass('pivotalStoryDescriptionExpanded');
                                    global.mems.pivotalData.states.storyExpanded = false;
                                } else {
                                    $('#pivotalStoryDescription').addClass('pivotalStoryDescriptionExpanded');
                                    global.mems.pivotalData.states.storyExpanded = true;
                                }
                                tm.savePreferences(global.ids.memsName, global.mems);
                            });
                        }
                        if (global.ids.pivotal.story.current_state.toLowerCase() == 'unstarted' && global.prefs.autoStartPivotalStories) {
                            page.pivotal.putStoryStart();
                        }
                    };
                    utils.delayUntil(iAm, () => {return global.ids.pivotal.project != null;}, () => {
                        utils.xhrAction(iAm, 'GET', 'stories/PIVOTALSTORYID/', whenDataReceived);
                    });
                },
                postReview: function (review_type_id) {
                    var iAm = 'postReview';
                    var whenDataReceived = function (resp) {
                        resp = JSON.parse(resp);
                        // remove an unstarted review of this type, since we just added one.
                        var reviewTypeName = JSON.parse(global.ids.pivotal.project.review_types).review_types.find((x) => x.id === resp.review_type_id).name;
                        if ($('.pt' + reviewTypeName + '.ptUnstarted').length > 0) {
                            var removeId = $('.pt' + reviewTypeName + '.ptUnstarted').parent().attr('data-review_id');
                            page.pivotal.deleteReview(removeId);
                            setTimeout(() => {
                                $('.reviewsEl').remove();
                                page.pivotal.getReviews();
                            }, TIMEOUT);
                            //                             var approveButton = document.querySelector(approveSelector);
                            //                             approveButton.classList.remove('tm-approveButton');
                        } else {
                            $('.reviewsEl').remove();
                            page.pivotal.getReviews();
                        }
                    };
                    utils.xhrAction(iAm, 'POST', 'stories/PIVOTALSTORYID/reviews?review_type_id=' + review_type_id + '&reviewer_id=' + global.ids.pivotal.project.me.id + '&status=Pass', whenDataReceived);
                },
                putStoryStart: function() {
                    var iAm = 'postStory';
                    if (!utils.getPivotalStoryId()) {
                        return;
                    }
                    var whenDataReceived = function (resp) {
                        resp = JSON.parse(resp);
                        var rememberActivity = global.ids.pivotal.story.activity;
                        global.ids.pivotal.story = resp;
                        global.ids.pivotal.story.activity = rememberActivity; // TODO: This is stupid. Do it better.
                    };
                    var params;
                    if (global.ids.pivotal.story.owner_ids.indexOf(global.ids.pivotal.project.me.id) > -1) {
                        params = {'current_state': 'started'};
                    } else {
                        global.ids.pivotal.story.owner_ids.push(global.ids.pivotal.project.me.id);
                        params = {
                            'current_state': 'started',
                            'owner_ids': global.ids.pivotal.story.owner_ids
                        }
                    };
                    utils.delayUntil(iAm, () => {return global.ids.pivotal.project != null;}, () => {
                        utils.xhrAction(iAm, 'PUT', 'stories/PIVOTALSTORYID/', whenDataReceived, null, params);
                    });
                }
            },
            scanMergeRequest() {
                if (global.states.mergeRequestScanned) {
                    return;
                }
                global.states.mergeRequestScanned = true;
                if (document.URL.indexOf('merge_requests/') > -1) {
                    document.querySelectorAll('.line').forEach((line) => {
                        if (line.innerText.indexOf('console.log') > -1) {
                            $.growl.error({'message': 'console.log found'});
                        };
                    });
                }
            },
            setAvatars: function () {
                if (!(global.prefs.useLocalAvatars)) {
                    return;
                }

                if (!global.states.avatarPingFailed && pingPhoto != null && global.prefs.avatarPreference[0] === 'localhost') {
                    tm.ping(avatarHost + pingPhoto + imageExt, function callback (response) {
                        if (response === 'responded') {
                            global.states.avatarPingFailed = false;
                        } else {
                            global.states.avatarPingFailed = true;
                        }
                        global.mems.avatarPingTimer = moment();
                        tm.savePreferences(global.ids.memsName, global.mems);
                    });
                }

                var avatarArray = [],
                    thisName = 'none';

                // gitlab
                var avatars = [
                    {
                        element: '.header-user-avatar', // main header (user) image
                        getImgSource: null,
                        getNameSource: function(el) { return $('.user-name').text(); }
                    },{
                        element: '.btn-link .author', // right side-bar (collapsed) author
                        getImgSource: function(el) { return $(el).parent().find('img'); },
                        getNameSource: function(el) { return $(el).next().text(); }
                    },{
                        element: '.participants-author img', // right side-bar, list of participants
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).next().find('div').text(); }
                    },{
                        element: '.issuable-meta .author-link img', // Opened X hours ago by...
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).next().text(); }
                    },{
                        element: '.author-link.inline img', // Merged by...
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).parent().prop('title'); }
                    },{
                        element: '.user-avatar-link img', // Approvers
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).prop('alt'); }
                    },{
                        element: '.header-user-dropdown-global img', // ????????
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).parent().prop('href'); }
                    },{
                        element: '.avatar-cell img', // ????????
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).prop('title'); }
                    },{
                        element: '.avatar-holder img', // ????????
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).parent().parent().next().find('.cover-title').text(); }
                    },{
                        element: '.list-item-name img', // ????????
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).next().find('.member').text(); }
                    },{
                        element: '.user-popover img', // ????????
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).parent().parent().next().find('h5').text(); }
                    },{
                        element: '.system-note-image img', // ????????
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).parent().prop('href'); }
                    },{
                        element: '.assignee .author-link img', // right side-bar, assigned-to
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).next().text(); }
                    },{
                        element: '.js-pipeline-url-user img', // Pipelines tab on merge request
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).next().find('div').text(); }
                    },{
                        element: '.issuable-meta .author-link img', // project's Merge Request page list
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).parent().prop('title'); }
                    },{
                        element: '.todo-avatar img', // TODO: page avatars
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).prop('alt').replace('\'s avatar', ''); }
                    },{
                        element: '.search-token-assignee img', // Merge Request list page
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).parent().text(); }
                    },{
                        element: '.ptComment img', // Merge Request page Pivotal Tracker Comments
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).prop('alt'); }
                    },{
                        element: '.sidebar-collapsed-icon .avatar', // Merge Request page sidebar collapsed assigned-to
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).prop('alt').replace("'s avatar", ''); }
                    },{
                        element: '.hide-collapsed .gl-link .avatar-inline:not(.js-lazy-loaded)', // Merge Request page sidebar expanded assigned-to
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).prop('alt').replace("'s avatar", ''); }
                    },{
                        element: '.author-link img.js-lazy-loaded', // Merge Request page sidebar expanded participants
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).parent().parent().prop('href'); }
                    },{
                        element: '.reviewEl img', // Merge Request page sidebar expanded participants
                        getImgSource: null,
                        getNameSource: function(el) { return $(el).prop('alt'); }
                    }
                ];

                avatars.forEach(avatar => {
                    tm.getContainer({
                        'el': avatar.element
                    }).then(function($container){
                        var iter = $(avatar.element).is('img') ? $(avatar.element) : avatar.getImgSource(avatar.element);
                        _.each(iter, function (img) {
                            thisName = utils.properName(avatar.getNameSource(img));
                            utils.updateImg(img, thisName);
                        });
                    });
                });

                $('img').each(function() {
                    var img = new Image(),
                        self = this;

                    img.onerror = function(){
                        $(self).prop('src', 'http://' + avatarHost + '!none' + imageExt);
                    }

                    img.src = this.src;
                });

            },
            monitorPipelines: function () {
                if (document.URL.indexOf('/jobs/') < 0 || $('.js-line span').length === 0 || global.states.arePipelinesChecked) {
                    return;
                }
                global.states.arePipelinesChecked = true;
                var growlHigh = '',
                    growlMed = '',
                    growlLow = '';
                _.each($('.js-line span'), (jsLine) => {
                    var lineContent = jsLine.innerHTML,
                        offset = $(jsLine).offset();
                    _.each(global.prefs.pipelineLogFilters, (pFilter) => {
                        if (lineContent.toLowerCase().indexOf(pFilter.key) > -1 ) {
                            jsLine.innerHTML = '<span class="pipelineLog-' + pFilter.name.replace(/ /g, '') + '">' + jsLine.innerHTML + '</span>';
                            var lineMessage = '<b><a style="color:black;" href="javascript:void(0)" onclick="window.scrollTo({top: ' + (offset.top - 100) + ', behavior: \'smooth\'});">See this line</a></b>' + lineContent;
                            if (pFilter.severity === "high" ) {
                                growlHigh += lineMessage + '<br /><br />';
                            } else if (pFilter.severity === "medium" ){
                                growlMed += lineMessage + '<br /><br />';
                            } else {
                                growlLow += lineMessage + '<br /><br />';
                            }
                        }
                    });
                });
                if (document.getElementById('showGrowls') == null) {
                    $('.retry-link').append('<div id="growlLow" style="display:none;">' + growlLow + '</div');
                    $('.retry-link').append('<div id="growlMed" style="display:none;">' + growlMed + '</div');
                    $('.retry-link').append('<div id="growlHigh" style="display:none;">' + growlHigh + '</div');
                    $('.retry-link').append('<button id="showGrowls" class="btn btn-default">Growl</button>');
                    $('#showGrowls').on('click', () => {
                        utils.showGrowls(document.getElementById('growlLow').innerHTML, document.getElementById('growlMed').innerHTML, document.getElementById('growlHigh').innerHTML)
                    });
                }
                utils.showGrowls(growlLow, growlMed, growlHigh);
            },
            monitorTodos: function () {
                if ($('#timerStats').length === 0) {
                    $('body').append('<span id="timerStats" style="display:none;"></span>');
                }
                if ($('#timerHiddenCount').length === 0) {
                    $('body').append('<span id="timerHiddenCount" style="display:none;"></span>');
                }
                var todoElement = '[aria-label="To-Do List"] .badge';
                var indicateSecondsTimer,
                    todosText = $(todoElement).eq(0).text().replace(/(\r\n\t|\n|\r\t)/gm,''),
                    todosCount = todosText == null || todosText.length === 0 ? 0 : Number(todosText),
                    notificationIcon = 'https://gitlab.dell.com/assets/favicon-7901bd695fb93edb07975966062049829afb56cf11511236e61bcf425070e36e.png',
                    indicateSeconds = function() {
                        var secondsRemaining = (Math.floor(global.reload.timespan/1000) - global.reload.lapsed);
                        $('#timerStats').text(todosCount + ' : (' + secondsRemaining + ')');
                        global.reload.lapsed++;
                        if (secondsRemaining > 0) {
                            indicateSecondsTimer = setTimeout(indicateSeconds, 1000);
                        } else {
                            $('#timerStats').text(global.reload.title);
                        }
                    },
                    triggerNotification = function(notifyMessage) {
                        var notification = new Notification(notifyMessage, {
                            icon: notificationIcon,
                            requireInteraction: todosCount === 0 ? false : !(global.prefs.autohideNotification),
                            body: todosCount
                        });
                        notification.onclick = function () {
                            window.open('https://gitlab.dell.com/dashboard/todos');
                        };
                        if (document.URL.indexOf('todos') > -1) {
                            window.location.reload(false);
                        }
                    }
                if (Notification.permission === 'default') {
                    Notification.requestPermission();
                } else {
                    if (!global.states.todoMonitorInitialized) {
                        global.states.todoMonitorInitialized = true;
                        global.reload.lapsed = 0;

                        var duration = moment.duration(moment().diff(global.mems.todosTimestamp)),
                            hours = duration.asHours(),
                            diffSeconds = duration.asSeconds();

                        if (Number(todosCount) > 0 && hours > 1) {
                            if (global.prefs.debugMode) console.dir({
                                '1reason': 'Been a while. Incrementing reloadTimesReminded',
                                '2mems': global.mems,
                                '3savedMems': utils.savedMems()
                            });
                            global.mems.todosTimestamp = moment();
                            global.mems.reloadTimesReminded = Number(global.mems.reloadTimesReminded) + 1;
                            if (global.mems.reloadTimesReminded > Number(utils.savedMems().reloadTimesReminded)) {
                                tm.savePreferences(global.ids.memsName, global.mems);
                                global.mems = utils.savedMems();
                            }
                        }

                        var currentMems = utils.savedMems();
                        if (todosCount !== global.mems.todosCount) {
                            // trigger notification on todo count change
                            if (currentMems != null && !_.isEmpty(currentMems)) {
                                global.mems.manyTabTimestamp = currentMems.manyTabTimestamp;
                            }
                            duration =  moment.duration(moment().diff(global.mems.manyTabTimestamp));
                            var seconds = Math.round(duration.asSeconds())
                            if (seconds > 30) { // to prevent multiple GitLab tabs all opening a notification each
                                utils.debug('Todos / Todos in memory: ' + todosCount + ':' + global.mems.todosCount);
                                global.mems.manyTabTimestamp = moment();
                                tm.savePreferences(global.ids.memsName,global.mems);
                                triggerNotification('TODOs on GitLab:');
                            }
                        } else if (Number(todosCount) > 0 && hours > 1 && Number(currentMems.reloadTimesReminded) > Number(currentMems.reloadReminderCount)) {
                            utils.debug('Time to remind user about existing Todos...');
                            // trigger notification on hourly timeout if there ARE any
                            global.mems.reloadTimesReminded = 0;
                            global.mems.reloadReminderCount = Number(global.mems.reloadReminderCount) + 1;
                            triggerNotification('Reminder- GitLab TODOs:');
                            global.mems.todosTimestamp = moment();
                            if (Number(global.mems.reloadReminderCount) > 8) {
                                global.mems.reloadReminderCount = 0;
                                global.mems.reloadTimesReminded = 0;
                            }
                            tm.savePreferences(global.ids.memsName,global.mems);
                        }

                        // update stored count
                        if(todosCount !== global.mems.todosCount) {
                            global.mems.todosCount = todosCount;
                            global.mems.reloadReminderCount = 0;
                            global.mems.reloadTimesReminded = 0;
                            tm.savePreferences(global.ids.memsName,global.mems);
                        }

                        // Reload in X seconds
                        global.reload.todoTimer = setTimeout(function() {
                            // "reload" the page
                            $('#timerHiddenCount').load( "https://gitlab.dell.com/dashboard/todos .todos-pending .badge", function(responseTxt, statusTxt, xhr){
                                if(statusTxt === 'success') {
                                    // External content loaded successfully
                                    if ($(todoElement).length > 0) {
                                        $(todoElement).text($('#timerHiddenCount').text()).removeClass('hidden');
                                        $(todoElement).addClass('beepboop');
                                        setTimeout(() => {
                                            $(todoElement).removeClass('beepboop');
                                        }, 250);
                                    }
                                    timeoutElement();
                                    global.states.todoMonitorInitialized = false;
                                    setTimeout(page.monitorTodos, TIMEOUT);
                                }
                                if(statusTxt === 'error')
                                    utils.debug('Error: ' + xhr.status + ': ' + xhr.statusText);
                            });
                        }, global.reload.timespan);

                        var buttonAnchor = $('.page-title');
                        var buttonCancelReload = 'Cancel-Reload';
                        var timeoutElement = function () {
                            clearTimeout(global.reload.todoTimer);
                            clearTimeout(indicateSecondsTimer);
                            $('#' + buttonCancelReload).css('display', 'none');
                            $('#timerStats').text(global.reload.title);
                            return false;
                        };
                        //buttonAnchor.after('<button id="' + buttonCancelReload + '" style="margin-left:50px; border-radius:15px; border:0px; background:lightgoldenrodyellow; padding:5px 15px; ">' + buttonCancelReload + '</button>');
                        //$('#' + buttonCancelReload).click(timeoutElement);

                        var buttonNotifyMe = 'Notify-Me';
                        var notifyMe = function() {
                            if (Notification.permission !== "granted") {
                                Notification.requestPermission();
                            } else {
                                var notification = new Notification('Permission Granted', {
                                    icon: notificationIcon,
                                    body: "Notifications have been allowed.",
                                });
                            }
                            $('#' + buttonNotifyMe).css('display', 'none');
                            return false;
                        }

                        if (Notification.permission !== 'granted') {
                            buttonAnchor.after('<button id="' + buttonNotifyMe + '" style="margin-left:50px; border-radius:15px; border:0px; background:lightgrey; padding:5px 15px; ">' + buttonNotifyMe + '</button>');
                            $('#' + buttonNotifyMe).click(notifyMe);
                        }

                        setTimeout(indicateSeconds, 1000);

                    }
                }
            },
            linkWorkItems: function () {
                if (!global.states.titlesLinked) {
                    global.states.titlesLinked = true;
                    var linkText, linkHref,
                        titleText = $('h2.title').text();
                    if (titleText.toUpperCase().indexOf('PT#') > -1) {
                        linkText = titleText.match(/PT#[0-9]*/gi).toString().split(',');
                        linkText.forEach(thisLink => {
                            if (utils.isNumeric(thisLink.substr(thisLink.length-1, 1))) {
                                linkHref = '<a href="https://www.pivotaltracker.com/story/show/' + thisLink.replace(/PT\#/gi, '') + '" target="blank">' + thisLink + '</a>';
                                titleText = titleText.replace(thisLink, linkHref);
                            }
                        });
                    }
                    if (titleText.toUpperCase().indexOf('TFS#') > -1) {
                        linkText = titleText.match(/TFS#[0-9]*/gi).toString().split(',');
                        linkText.forEach(thisLink => {
                            if (utils.isNumeric(thisLink.substr(thisLink.length-1, 1))) {
                                linkHref = '<a href="http://tfs2.dell.com:8080/tfs/eDell/eDellPrograms/_workitems?id=' + thisLink.replace(/TFS\#/gi, '') + '" target="blank">' + thisLink + '</a>';
                                titleText = titleText.replace(thisLink, linkHref);
                            }
                        });
                    }
                    $('h2.title').html(titleText);
                }
            },
            checkForInactivity: function () {
                let duration = moment.duration(moment().diff(global.activityTimestamp));
                let seconds = Math.round(duration.asSeconds())
                if (seconds > 300) {
                    global.states.arePrButtonsAdded = false;
                }
            }
        };

    setTimeout(function() {
        utils.initScript();
        document.addEventListener('mousemove', function handleMouseEvent () {
            if (!global.states.isMouseMoved) {
                global.states.isMouseMoved = true;
                setTimeout(function() {
                    global.states.isMouseMoved = false;
                }, TIMEOUT * 2);
                if (document.getElementById('GitlabModsOptions') == null) { // don't re-init the script when a popup is open
                    utils.initScript();
                }
            }
            //             if (global.mems != null & global.states.avatarPingFailed) { // reset ping timer every 15 seconds, I guess
            //                 var duration = moment.duration(moment().diff(global.mems.avatarPingTimer));
            //                 if (global.mems.avatarPingTimer != null && Math.round(duration.asSeconds()) > 15) {
            //                     global.states.avatarPingFailed = false;
            //                     global.mems.avatarPingTimer = null;
            //                     tm.savePreferences(global.memsName, global.mems);
            //                 }
            //             }
        });
    }, TIMEOUT);

})();