JJJohan / Clear All Layers

// ==UserScript==
// @name         Clear All Layers
// @namespace    Roames
// @version      1.0.1
// @license      MIT
// @description  Clear all visualisation layers
// @author       Johan Rensenbrink
// @include      *://www.roames.net/*
// @include      *://rcw-uat.roames.com/*
// @include      *://rcw-dev.roames.com/*
// ==/UserScript==

(function() {
    'use strict';

    var timer = setInterval(function()
    {
        var buttons = document.getElementsByClassName('btn-circle');
        for (var i = 0; i < buttons.length; i++)
        {
            var button = buttons[i];
            if (button.innerText.indexOf("Add Layer") != -1)
            {
                insertDeleteButton(button);
                return;
            }
        }
    }, 1000);

    function insertDeleteButton(button)
    {
        // Insert 'remove all layers' button.
        var newButton = document.createElement("button");
        newButton.innerHTML = "<i class='icon-layers'></i><span translate='translate'><span>Clear All Layers</span></span>";
        newButton.className = "btn red btn-circle btn-outline btn-sm pull-right";
        newButton.addEventListener("click", function()
        {
            var result = confirm("Are you sure you want to delete all visualisation layers for this tenant?");
            if (result)
            {
                deleteLayer();
            }
        });

        var parent = button.parentElement;
        parent.insertBefore(newButton, button);
        clearInterval(timer);
    }

    function deleteLayer()
    {
        var removeButtons = document.getElementsByClassName('glyphicon-remove');
        if (removeButtons.length > 0)
        {
            var actualButton = removeButtons[0].parentElement;
            actualButton.click();
            setTimeout(confirmPress, 50);
        }
        else
        {
            alert('All layers removed.');
        }
    }

    function confirmPress()
    {
        var confirmButton = document.getElementsByClassName('confirm');
        if (confirmButton.length > 0)
        {
            confirmButton[0].click();
            setTimeout(deleteLayer, 50);
        }
        else
        {
            setTimeout(confirmPress, 50);
        }
    }
})();