// ==UserScript==
// @name         Auto-endorse LinkedIn Connections
// @require      https://code.jquery.com/jquery-1.9.1.js
// @require      https://gist.github.com/raw/2625891/waitForKeyElements.js
// @version      0.6
// @description  Automatically endorse the user we are viewing for their top skills
// @author       Brandon Dixon (@9bplus)
// @grant        none
// @include      https://www.linkedin.com/*
// ==/UserScript==

var firstRun = true;

function skillCheck() {
    $(".button-secondary-medium-round").each(function() {
        $(this).click();
    });
    firstRun = true;
}

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.attributeName === "class") {
            var attributeValue = $(mutation.target).prop(mutation.attributeName);
            var url = window.location.href;
            if (typeof url === "undefined" || url.indexOf("/in/") === -1) {
                return;
            }
            if (((attributeValue === "ember-view") || (attributeValue === "lazy-image profile-picture loaded")) && firstRun) {
                if ($('.connect').length === 0) {
                    $("body").animate({ scrollTop: 10000 }, 1000);
                    $("body").animate({ scrollTop: 0 }, 1000);
                    firstRun = false;
                }
            }
        }
    });
});

$( document ).ready(function() {
    var profile = $(".application-outlet")[0];
    if (typeof profile !== "undefined") {
        observer.observe(profile,  {
            childList: true,
            subtree : true,
            attributes: true
        });
    }
});

waitForKeyElements(".pv-featured-skills-section", skillCheck);