amazonshubhamsdj / PhoneTool Enhanced - Mini

// ==UserScript==
// @name         PhoneTool Enhanced - Mini
// @namespace    http://amazon.com
// @version      0.1
// @description  Add Meeting request for managers with assistants, Google Map of Seattle Campus building locations, linkedin search links, and a visual job history widget. Also a new and improved stylesheet
// @author       wael@
// @include      https://phonetool.amazon.com/people/*
// @include      https://phonetool.amazon.com/users/*
// @include      https://connect.amazon.com/people/*
// @include      https://connect.amazon.com/users/*
// @grant        GM_xmlhttpRequest
// @downloadURL https://openuserjs.org/install/amazonshubhamsdj/PhoneTool_Enhanced_-_Mini.user.js
// @grant        GM_getResourceText
// @grant        GM_addStyle
// @license MIT
// @grant        GM.getValue
// @grant        GM.setValue
// @require      http://code.jquery.com/jquery-latest.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js
// @resource     ptCSS https://phonetool-enhance.s3-us-west-2.amazonaws.com/PhoneToolMini.css
// ==/UserScript==

(function() {

    'use strict';
    var url = window.location.href;
    var subdomainRE = RegExp('([^.//]+)','g');
    var subdomain = url.match(subdomainRE)[1];
    var params = {
        urlPrefix: `https://${subdomain}.amazon.com/users/`,
        urlPostfix: ".json",
        empId: $(location).attr("pathname").match(/[people|users]\/(\w+)/)[1],
        orgUrlPrefix: "https://ekarulf.corp.amazon.com/phone-widgets/job-history.cgi?format=greasemonkey&target=",
        linkedinSearchPrefix: "https://www.linkedin.com/search/results/people/?keywords="
    };
    var newCSS = GM_getResourceText ("ptCSS");
    GM_addStyle (newCSS);

    function getPersonalInfoWidgets (params) {
        $.ajax({
            url: params.urlPrefix + params.empId + params.urlPostfix,
            type: "GET",
            dataType: "json",
            success: function(data) {
                try {
                  displayMapLoc(data);
                  addPhoneNumber(data.mobile_number);
                  addLinkedinSearch(data, params.linkedinSearchPrefix);
                  addJobLevel(data.job_level);
                  addTenure(data.total_tenure_formatted);
                  addReports(data.direct_reports.length);
                  addLocation(data.building, data.city);
                  scheduleMeetingWithAssistant(params, data);
                } catch(e) {
                    console.log(e);
                }
            }
        });
    }
    function addTenure (tenure) {
      updateKeySummaryData("MINI-history", tenure);
    }
    function addLocation (building, city) {
      updateKeySummaryData("MINI-location", building + ", " + city);
    }
    function addReports (reports) {
      updateKeySummaryData("MINI-org", reports);
    }
    function addJobLevel (level) {
      $("#MINI-job-level").text(level);
      // $("dl.dl-horizontal").append(`<div class="TableRow jobLevelRow"><div class="TableProperty">Job Level:</div><div class="TableValue">${data.job_level}</div></div>`);
    }
    function addPhoneNumber (mobile_number) {
      if ((mobile_number != null) && (mobile_number != "")) {
        $("#MINI-actions-block").prepend(`
            <div class="PersonalLinkedinSearch MINI-Actions-Button" id="MINI-phone-button">
              <i class="fa fa-mobile" aria-hidden="true"></i>
              <a class="copyable" id="phone_nummber_holder">${mobile_number}
              </a>
            </div>`
          );
      }
      $("#phone_nummber_holder").on("click", makeCopyClickable);
      $("#phone_nummber_holder").hover(showTooltip, removeTooltip);
      $("#phone_nummber_holder").on("click", makeCopyClickable);
    }
    function addLinkedinSearch(data, searchURL) {
      $("#MINI-actions-block").append(`
          <div class="PersonalLinkedinSearch MINI-Actions-Button" id="MINI-linkedin-button">
            <i class="fa fa-linkedin" aria-hidden="true"></i>
            <a href="${searchURL}${data.first_name}+${data.last_name}+Amazon" target='_blank'>Search Linkedin</a>
          </div>`
        );
    }
    function scheduleMeetingWithAssistant (params, data) {
        var assistantLogin = data.assistant.login;
        if (assistantLogin != null) {
          $.ajax({
              url: params.urlPrefix + assistantLogin + params.urlPostfix,
              type: "GET",
              dataType: "json",
              success: function(moreData) {
                  try {
                    let name = moreData.first_name;
                    let mgrName = data.first_name;
                    let asstEmail = moreData.email;

                    var subjectStr = `Time with ${mgrName}`;
                    var mailToStr = "";

                    var emailTemplateHTML = "";

                    (async () => {
                      emailTemplateHTML = await GM.getValue('ptEnhanceEmailTemplate', false);

                      if (emailTemplateHTML == false) {
                        emailTemplateHTML = `
                        <span class="editable">Hello </span>
                        <span class="fixed" id="assistantNameSpan"></span>
                        <span class="editable">, hope all is well!\nCan you please help me get </span>
                        <span class="fixed" id="meetingLengthSpan"></span>
                        <span class="editable"> minutes with </span>
                        <span class="fixed" id="managerNameSpan"></span>
                        <span class="editable">? Subject is </span>
                        <span class="fixed" id="meetingSubjectSpan"></span>
                        <span class="editable">. My calendar is up to date.\nThanks</span>
                        `;
                      }
                      $("#emailTemplate").html(emailTemplateHTML);
                      $(updateEmail);
                    })();


                    $("#MINI-actions-block").append(`
                        <div class="RequestMeetingAssistant MINI-Actions-Button" id="MINI-meeting-button">
                          <i class="fa fa-calendar-o" aria-hidden="true"></i>
                          <a id="showMeetingDialog">Request meeting</a>
                        </div>`
                      );

                      $("#MINI-meeting-button").after(`
                        <div class="meetingInfo MINI-slate">
                        <div class="meetingInfoLine">
                          <div id="meetingLengthDiv">
                            <label for="meetingLength">Meeting Length (minutes)</label>
                            <input type="text" class="emailInput" id="meetingLength" value="30" size="5">
                          </div>
                          <div id="meetingSubjectDiv">
                            <label for="meetingSubject">Subject</label>
                            <input type="text" class="emailInput" id="meetingSubject" value="1:1" size="25">
                          </div>
                        </div>
                        <div class="meetingInfoLine">
                          <div id="meetingTemplateDiv">
                            <!-- <label for="emailTemplate">Template</label> -->
                            <div  id="emailTemplate">
                            </div>
                            <div class="EditTemplate">
                              <i class="fa fa-edit" aria-hidden="true"></i>
                              <span id="editEmailTemplate">Double click to edit default email template</span>
                            </div>
                          </div>
                          <div  id="meetingButtonDiv">
                            <div class="sendEmailButton" id="sendEmail">Create Email</div>
                            <div id="cancelEmail">Cancel</div>
                          </div>
                          </div>
                        </div>`
                      );

                      $("#showMeetingDialog").click(function(){
                        $(".meetingInfo").toggleClass("open");
                        $("#MINI-meeting-button").toggleClass("open");
                      });

                      $("#cancelEmail").click(function(){
                        $(".meetingInfo").toggleClass("open");
                        $(".editable").removeClass("active");
                        $("#MINI-meeting-button").toggleClass("open");
                      });

                      $("#emailTemplate").dblclick(function(){
                        $(".editable").attr("contenteditable", "true");
                        $(".editable").addClass("active");
                        $("#sendEmail").text("Save Template and Create Email");
                        // $(".EditTemplate").hide();
                      });

                      function updateEmail (){
                        var bodyParameters = {
                          assistantName: name,
                          meetingLength: $("#meetingLength").val(),
                          managerName: mgrName,
                          meetingSubject: $("#meetingSubject").val()
                        };
                        $("#assistantNameSpan").text(bodyParameters.assistantName);
                        $("#meetingLengthSpan").text(bodyParameters.meetingLength);
                        $("#managerNameSpan").text(bodyParameters.managerName);
                        $("#meetingSubjectSpan").text(bodyParameters.meetingSubject);

                         $("#sendEmail").click(function(){
                           mailToStr = `mailto:${asstEmail}?subject=${encodeURIComponent(subjectStr)}&body=${encodeURIComponent($("#emailTemplate").text().replace(/\s\s+/g, ' ').trim())}`;
                           window.open(mailToStr);
                           $(".editable").removeClass("active");
                           $(".meetingInfo").hide("slow");
                           (async () => {
                             await GM.setValue('ptEnhanceEmailTemplate', $("#emailTemplate").html());
                           })();
                           return false;
                         });

                     };

                    $(updateEmail);
                    $(".emailInput").on("keyup",updateEmail);

                  } catch(e) {
                      console.log(e);
                  }
              }
          });
        }
    }
    function displayMapLoc (data) {
        var building = data.building.substr(data.building.indexOf('-')+1);
        var search = "Amazon " + building + " building, " + data.city + ", " + data.country;
        var deskLoc = (data.building_room?data.building_room:"");
        var deskMapLink = $(".floor-map-link").attr("href");
        var buildingDetailsLink = $(".building-link").attr("href");
        var deskParams = deskLoc.split('.');
        var mapWidget = `<div class="map">
           <div id="MINI-desk-loc">
              <div class="MINI-loc-element"><a href="${buildingDetailsLink}"><div class="title">Building</div><div class="data">${building}</div></a></div>
              <div class="MINI-loc-element"><a href="${deskMapLink}"><div class="title">Floor</div><div class="data">${deskParams[1]}</div></a></div>
              <div class="MINI-loc-element"><a href="${deskMapLink}"><div class="title">Desk</div><div class="data">${deskParams[2]}${(deskParams[3] ? ("."+deskParams[3]):"")}</div></a></div>
           </div>
           <div class="mapouter">
             <div class="gmap_canvas">
               <iframe width="100%" height="400" id="gmap_canvas" src="https://maps.google.com/maps?q=${search}&t=&z=15&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"></iframe>
             </div>
           </div>
         </div>`;
        updateContentSection("MINI-location", mapWidget);
    }

    function removeOverlaps (rolesArray) {
      var resultArray = [];
      for (var i=0; i<rolesArray.length; i++) {
        if (rolesArray[i].end_date == "") rolesArray[i].end_date = moment().format("YYYY/MM/DD");
        var currentRoleStartDate = moment(rolesArray[i].start_date);
        var currentRoleStartDateStr = currentRoleStartDate.format("YYYY/MM/DD");
        var currentRoleEndDate = moment(rolesArray[i].end_date);
        var isSuperSet = false;
        for (var k=0; k<rolesArray.length; k++) {
          if ((k!=i) && !isSuperSet) {
            var testRoleStartDate = moment(rolesArray[k].start_date);
            var testRoleEndDate = moment(rolesArray[k].end_date);
            if (currentRoleStartDate.isBefore(testRoleStartDate) && currentRoleEndDate.isAfter(testRoleEndDate)) {
              isSuperSet = true;
              var post = JSON.parse(JSON.stringify(rolesArray[i]));
              var pre = JSON.parse(JSON.stringify(post));
              post.start_date = testRoleEndDate.format("YYYY/MM/DD");
              resultArray.push(post);
              var mid = resultArray[k];
              pre.start_date = currentRoleStartDateStr;
              pre.end_date = testRoleStartDate.format("YYYY/MM/DD");
              resultArray.push(pre);
            }
          }
        }
        if (!isSuperSet) resultArray.push(rolesArray[i]);
      }
      resultArray = _.sortBy(resultArray, 'end_date').reverse();
      return(resultArray);
    }
    function fillInGaps (incomingArray) {
        var targetData = [];
        //fill in data gaps
        var rolesArray = removeOverlaps(incomingArray);
        for (var r=0; r < rolesArray.length; r++) {
            var roleStartDate = moment(rolesArray[r].start_date);
            var roleEndDate = (rolesArray[r].end_date==""?moment():moment(rolesArray[r].end_date));
            var currentRole = rolesArray[r];
            if (roleEndDate.isSame('2015-02-02', 'day') && (r>0)) {
              roleEndDate = moment(rolesArray[r-1].start_date);
              currentRole.end_date = roleEndDate.format("YYYY/MM/DD");
            }
            var roleDays = roleEndDate.diff(roleStartDate, 'days');
            currentRole.roleDays = roleDays;
            targetData.push(currentRole);

            if ((r<rolesArray.length-1) && (roleStartDate > moment(rolesArray[r+1].end_date).add(7, 'd'))) {
                var prevRoleEndDate = moment(rolesArray[r+1].end_date);
                if (!(prevRoleEndDate.isSame('2015-02-02', 'day') && (r>=0))) {
                  roleDays = roleStartDate.diff(prevRoleEndDate, 'days');
                  targetData.push({
                      end_date: roleStartDate.format("YYYY/MM/DD"),
                      start_date: prevRoleEndDate.format("YYYY/MM/DD"),
                      gap: true,
                      job_family: "Data Gap",
                      roleDays: roleDays,
                      department_name: "",
                      supervisor_name: "",
                      business_title: ""
                });
              }
            }
        }
        return targetData;
    }
    function getUniqueJobFamilies (targetData) {
        var jobFamilies = new Set();
        for (var j =0; j < targetData.length; j++) {
            jobFamilies.add(targetData[j].job_family);
        }
        var jobFamilyClass = {};
        var l=0;
        jobFamilies.forEach(function(value){
            if (value == "Data Gap") {jobFamilyClass[value] = "_gap";}
            else {jobFamilyClass[value] = "_"+l++;}
        });
        return jobFamilyClass;
    }
    function consolidateAdjacent(targetData, titleField) {
        var adjChanges = [];
        for (var k = 0; k < targetData.length; k++) {
            if ((k>0) && (targetData[k][titleField] == adjChanges[adjChanges.length-1].title)) { //is the current dept name similar to previous one?
                adjChanges[adjChanges.length-1].days += targetData[k].roleDays;
            } else {
                adjChanges.push({
                    title: targetData[k][titleField],
                    days: targetData[k].roleDays,
                    mgrLogin: targetData[k].supervisor_login
                });
            }
        }
        return adjChanges;
    }
    function consolidateRoles(targetData) {
        var adjChanges = [];
        for (var k = 0; k < targetData.length; k++) {
            if (
                (k>0) &&
                ((
                  // (targetData[k].job_family == adjChanges[adjChanges.length-1].job_family) &&
                  (targetData[k].business_title == adjChanges[adjChanges.length-1].business_title)
                )
                || (targetData[k].roleDays <= 30))
            )
              {
                adjChanges[adjChanges.length-1].days += targetData[k].roleDays;
            } else {
                adjChanges.push({
                    department_name: targetData[k].department_name,
                    job_family: targetData[k].job_family,
                    business_title: targetData[k].business_title,
                    days: targetData[k].roleDays
                });
            }
        }
        return adjChanges;
    }
    function consolidateDates (targetData) {
        var adjChanges = [];
        for (var k = 0; k < targetData.length; k++) {
            if (
              (k>0) &&
              ((
                (targetData[k].department_name == adjChanges[adjChanges.length-1].department_name) &&
                (targetData[k].job_family == adjChanges[adjChanges.length-1].job_family) &&
                (targetData[k].supervisor_name == adjChanges[adjChanges.length-1].supervisor_name)
                && (targetData[k].business_title == adjChanges[adjChanges.length-1].business_title)
            ) || (
              targetData[k].roleDays <= 30
            ))
          ) {
                adjChanges[adjChanges.length-1].days += targetData[k].roleDays;
            } else {
                adjChanges.push({
                    department_name: targetData[k].department_name,
                    job_family: targetData[k].job_family,
                    supervisor_name: targetData[k].supervisor_name,
                    date: (targetData[k].end_date==""?moment():moment(targetData[k].end_date)).format("MMM YY"),
                    days: targetData[k].roleDays
                });
            }
        }
        return adjChanges;

    }
    function layoutRow (order, friendlyName, rowClassName, cellsArr, contentParamName, widthParamName, total, cellClassName, addlClass, searchURL) {
      var titleWidth = 50+"px";
        var rowHTML = "<div class='timeline-rows "+rowClassName+"'>";
        rowHTML += `<div class='${cellClassName} title' style='min-width: ${titleWidth}'>${friendlyName}</div>`;
        var rowStep = ((rowClassName == 'timeline-row')?0:0);
        // var lineShift = 20 * order;
        for (var i=0; i<cellsArr.length; i++) {
            var addLinkPre = "";
            var addLinkPost = "";
            var content = cellsArr[i][contentParamName];
            if ((cellClassName == "manager")) {
              if ((cellsArr[i].mgrLogin)) {
                addLinkPre += "<a href='"+params.urlPrefix+cellsArr[i].mgrLogin+"'>";
                addLinkPost += "</a>";
              } else {
                addLinkPre += `<a href="${searchURL}${content} Amazon" title='${content}. Former employee. Search for in Linkedin' target='_blank'><i>`;
                addLinkPost += "</i></a>";
              }
            }
            var wid = ((cellsArr[i][widthParamName] / total)*100)+"%";
            // var top = ((rowStep * i))+"px";
            rowHTML += `<div class='marker ${cellClassName} ${(addlClass?addlClass[cellsArr[i].job_family]:"")}' style='min-width: ${wid};' title='${content}'>${addLinkPre}${content}${addLinkPost}</div>`;
        }
        rowHTML += "</div>";
        return rowHTML;
    }
    function layoutLegend (legendObj) {
        var rowHTML = "<div class='legend'><div>Job Family:</div>";
        for (var property1 in legendObj) {
            rowHTML += `<div class='${legendObj[property1]}'><div class='swatch'></div>${property1}</div>`;
        }
        rowHTML += "</div>";
        return rowHTML;
    }
    function getyOrgHistoryWidgets (params) {
        GM_xmlhttpRequest({
            method: "GET",
            url: params.orgUrlPrefix + params.empId,
            onload: function(data) {
                try {
                    var historyData = JSON.parse(data.responseText);
                    var roles = historyData.length;
                    var today = moment();
                    var startHistory = moment(historyData[historyData.length-1].start_date);
                    var tenure = today.diff(startHistory, 'days');
                    var fixedHistory = fillInGaps(historyData);
                    var jobFamilyClass = getUniqueJobFamilies(fixedHistory);
                    //Consolidate similar adjacent cells
                    var depts = consolidateAdjacent (fixedHistory, "department_name");
                    var mgrs = consolidateAdjacent (fixedHistory, "supervisor_name");
                    var uniqueRoles = consolidateRoles(fixedHistory);
                    var dates = consolidateDates(fixedHistory);

                    // var timelineWidth = ((tenure/1000)*100)+"%";
                    var timelineWidth = "100%";
                    $("#MINI-history .MINI-section-content").append(`
                      <div class='role-history' style="width: ${timelineWidth};">
                        <div id='side-pan'></div>
                        <div class='timeline-holder'>
                          <div class='timeline'>
                            ${layoutRow(1, "Date", 'date-names', dates, 'date', 'days', tenure, 'date-marker')}
                            ${layoutRow(2, "Org", 'dept-names', depts, 'title', 'days', tenure, 'dept-marker')}
                            ${layoutRow(3, "Title", 'timeline-row', uniqueRoles, 'business_title', 'days', tenure, 'timeline-section', jobFamilyClass)}
                            ${layoutRow(4, "Manager", 'mgr-names', mgrs, 'title', 'days', tenure, 'manager', null, params.linkedinSearchPrefix)}
                          </div>
                          <div class = 'start-date-holder'><div class = 'dept-marker'>Start</div><div class='date-marker'>${startHistory.format("MMM YY")}</div></div>
                        </div>
                        ${layoutLegend(jobFamilyClass)}
                        <div id="timeline-helper"></div>
                      </div>`
                    );
                    $(".timeline-section").on("click", zoomIn);//, zoomOut);

                    function zoomIn (event){
                      var callingEl = this;

                      //Get the highlighting right
                      $(".timeline-section").addClass("unzoomed");
                      $(callingEl).removeClass("unzoomed");
                      $(callingEl).addClass("zoomed");
                      $(".timeline-row").addClass("zoomed");

                      //Disable actions
                      $(".timeline-section").unbind("click");
                      //Copy and keep left legend in place;
                      $("#tempTitleHolder").remove();
                      $("#side-pan").addClass("active");
                      $(".role-history").append("<div id='tempTitleHolder'></div>");
                      $(".timeline .title").each(function() {
                        var topPos = $(this).offset().top - $(this).offsetParent().offset().top ;
                        var leftPos = $(this).offset().left;
                        $(this).removeClass('timeline-section')
                        $(this).clone().addClass("tempTitle").appendTo("#tempTitleHolder").css({
                          position: 'absolute',
                          top: topPos,
                          left: 0
                        })
                      });

                      var containerWidth = $(".timeline-holder").width();
                      var callingElWidth = $(callingEl).width();
                      var ratio = callingElWidth/containerWidth;
                      var viewport = $(".timeline-holder").parent().width();
                      var elTargetWidth = 0.6 * viewport;
                      var containerTargetWidth = elTargetWidth / ratio;
                      var offset = (viewport-elTargetWidth)/2;


                      $(".timeline-holder").animate({width: containerTargetWidth+"px"}, 0, function() {
                        var startPos = ($(callingEl).offset().left - $(this).offset().left)*-1 ;
                        var centeredPos = startPos+offset;
                        if (centeredPos > 0) centeredPos = 0;
                        var marginToChange = "margin-left";
                        $(this).animate({'margin-left': centeredPos+"px"}, 200, function() {
                          //Enable actions again
                          $(".timeline-section").on("click", zoomIn);
                          $(callingEl).unbind("click");
                          $(callingEl).on("click", zoomOut);
                        });
                        $("#timeline-helper").addClass("active");
                      });

                    };
                    function zoomOut (){
                      $(".timeline-section").unbind("click");
                      $(".timeline-section").removeClass("zoomed unzoomed");
                      $(".timeline-row").removeClass("zoomed");
                      $("#timeline-helper, #side-pan").removeClass("active");
                      $("#tempTitleHolder").remove();
                      $(".timeline-holder").animate({
                        width: "100%",
                        'margin-left': "0px"
                      }, 300, function() {
                        $(".timeline-section").on("click", zoomIn);
                      });
                      //
                    }
                    // });
                } catch(e) {
                    console.log(e);
                }
            }
        });

    }

    //Remove everything
    function setupScaffolding () {
      $("body").append(`
        <div id='MINI-background-holder'></div>
        <div id="MINI-content" class="grid-container">
          <div id="MINI-config" class="config-block"></div>
          <div id="MINI-name-block" class="name-block">
            <div id='row1' class="MINI-row"></div>
            <div id='row2' class="MINI-row"></div>
            <div id='row3' class="MINI-row"></div>
          </div>
          <div id="MINI-image-block" class="side-bar">
            <div id='row1'></div>
            <div id='row2'>
              <div id="MINI-personal-actions"></div>
            </div>
            <div id='row3'>
              <div id="MINI-actions-block"></div>
            </div>
          </div>
          <div id="MINI-profile-info-block" class="main-content"></div>
          <div id="MINI-stickers" class="bottom-area"></div>
        </div>
        <div id="tooltiptext">
          <span>Copy to clipboard</span>
        </div>
      `);

      // Need to do it like this to avoid killing the modals
      $(".employee-container>*").eq(1).hide();
      $(".employee-badge").first().hide();
      $("div[data-react-class='UserDetails']").first().hide();
      // $("#content").hide();
    }
    function setupNameBlock () {
      //Copy name
      $(".PersonalInfoName>.name").clone().removeClass("name").attr("id", "MINI-name").addClass("copyable").appendTo("#MINI-name-block>#row1");
      //Copy login
      $(".worker-badge>.login").clone().removeClass("login").attr("id", "MINI-login").addClass("copyable").appendTo("#MINI-name-block>#row1");
      //Put a job level placeholder
      $("#MINI-name-block>#row2").append('<div id="MINI-job-level">8</div>')
      //Copy title
      $(".PersonalInfoJobTitle").clone().removeClass("PersonalInfoJobTitle").attr("id", "MINI-job-title").appendTo("#MINI-name-block>#row2");
      //Copy message
      $(".PersonalInfoMessage").clone().removeClass("PersonalInfoMessage").attr("id", "MINI-message").appendTo("#MINI-name-block>#row3");

      $("#MINI-name, #MINI-login").hover(showTooltip, removeTooltip);
      $("#MINI-name, #MINI-login").on("click", makeCopyClickable);
    }
    function setupImageBlock () {
      //Copy photo
      // $(".photo-frame").eq(1).clone().removeClass("photo-frame").attr("id", "MINI-photo-frame").appendTo("#MINI-image-block>#row1");
      $(".worker-badge").first().clone().attr("id", "MINI-photo-frame").appendTo("#MINI-image-block>#row1");
      if ($(".worker-badge .fake-link").length) {
        $(".worker-badge .fake-link").first().attr("id", "old-change-link");
        $("#MINI-content .fake-link").hide();
        $("#MINI-image-block>#row1").prepend(`<div id="MINI-change-photo-icon" title="Switch photo"><i class="fa fa-refresh" aria-hidden="true"></i></div>`);
        $("#MINI-change-photo-icon").click(enablePhotoToggle);
      }
      //Copy all default actions
      if ($("#update-info-toggle").length) {
        $(".PersonalInfoChime").clone().attr("id", "MINI-chime-button").addClass("MINI-Actions-Button").appendTo("#MINI-actions-block");
        $("#MINI-personal-actions").append(`
            <div class="MINI-Actions-Button" id="MINI-edit-profile">
              <i class="fa fa-pencil" aria-hidden="true"></i>
              <a>Edit my info</a>
            </div>`
          );
          $("#MINI-edit-profile").click(function(){
            // $("#update-info-modal").clone().appendTo("#MINI-edit-profile");
            $("#update-info-toggle").trigger("click");
          });
      }
      $(".PersonalInfoChime").clone().attr("id", "MINI-chime-button").addClass("MINI-Actions-Button").appendTo("#MINI-actions-block");
      $(".PersonalInfoEmail").clone().attr("id", "MINI-email-button").addClass("MINI-Actions-Button").appendTo("#MINI-actions-block");
      $(".PersonalInfoAccolades").clone().attr("id", "MINI-accolades-button").addClass("MINI-Actions-Button").appendTo("#MINI-actions-block");
      //Copy share your passion question
      if ($(".SharePassionResponse").length) {
        $("#MINI-image-block>#row1").append(`<div id="MINI-share-passion-icon"><i id="bubble-button" class="fa fa-comment-o" aria-hidden="true"></i></div>`)
        $("#MINI-image-block>#row1").append(`<div id="MINI-share-passion-holder"></div>`);
        $(".SharePassion").first().clone().attr("id", "MINI-share-passion").addClass("MINI-slate").appendTo("#MINI-share-passion-holder");
        $("#MINI-share-passion-icon").click(showPassionBubble);
      }
    }
    function enablePhotoToggle() {
      $("#old-change-link").trigger("click");
      var waitToExpand = setInterval(waitToExpandFn, 500);
      function waitToExpandFn () {
           clearInterval(waitToExpand);
           $("#MINI-photo-frame").remove();
           $(".worker-badge").first().clone().attr("id", "MINI-photo-frame").insertAfter("#MINI-change-photo-icon");
           $("#MINI-content .fake-link").hide();
           return false;
       }
    }
    function populateProfileInfoBlock (container, sectionName, sectionTitle, sectionKeySummary) {
      var blockStr = `
        <div class="MINI-profile-section" id="${sectionName}">
          <div class="MINI-section-header MINI-slate">
            <div class="title">${sectionTitle}</div>
            <div class="key-summary">
              <div class="key-summary-title">${sectionKeySummary}</div>
              <div class="key-summary-data"></div>
              <!--<span class="expand-arrow"><i class="fa fa-chevron-down" aria-hidden="true"></i></span>-->
            </div>
          </div>
          <div class="MINI-section-content"></div>
        </div>
      `;
      $(container).append(blockStr);
      $(`#${sectionName} .MINI-section-header`).on("click", toggleContentSection);
    }
    function toggleContentSection () {
      $(this).parent().toggleClass("open");
      // $(this).parent().find(".MINI-section-content").toggleClass("MINI-slate");
    }
    function updateContentSection (sectionName, jqObject) {
      $(`#${sectionName} .MINI-section-content`).append(jqObject);
    }
    function updateKeySummaryData (sectionName, summaryData) {
      $(`#${sectionName} .key-summary-data`).text(summaryData);
    }
    function addProfileDetails () {
      //Org
      populateProfileInfoBlock ("#MINI-profile-info-block", "MINI-org", "Organization", "Direct Reports");
      var checkExist = setInterval(waitToCopyOrgChart, 100);
      function waitToCopyOrgChart () {
         if ($('.org-chart-row').length) {
           clearInterval(checkExist);
           $(".well.org-chart div:first-child").children("div:nth-child(2)").first().attr("id", "old-org-widget");
           var expandablePos = 0;
           $("#old-org-widget").find(".expandable").each(function () {
             $(this).attr("id", "MINI-exapndable-pos-" + expandablePos++)
           })
           updateContentSection("MINI-org", $("#old-org-widget").clone().addClass("org-chart").attr("id", "MINI-org-widget"));
           // initaite button listeneres
           $("#MINI-org-widget .expandable").on("click", updateOrgChart);
         }
      }
      //Work History
      populateProfileInfoBlock ("#MINI-profile-info-block", "MINI-history", "Work History", "Tenure");
      //Location
      populateProfileInfoBlock ("#MINI-profile-info-block", "MINI-location", "Location", "Building/City");
      //Phnoe tool icons
      populateProfileInfoBlock ("#MINI-profile-info-block", "MINI-interests", "PhoneTool Icons", "Awards");
      updateKeySummaryData ("MINI-interests", $("#widget-2").find(".uppercase.muted").text().match(/\d+/)[0])
      updateContentSection("MINI-interests", $(".main-content.awards").first().clone().attr("id", "MINI-awards"));


      $(".main-content.communities").first().clone().attr("id", "MINI-communities").appendTo("#MINI-stickers");
      $("#MINI-communities .community-preview").each(function () {
        var scaleFactor = 1 + (Math.random() * 0.8);
        var opacity = 0.2 + (Math.random() * 0.8);
        var rotateFactor = -10 + (Math.random() * 20);

        // $(this).css("transform", ``);
        $(this).css("transform", `scale(${scaleFactor}) rotate(${rotateFactor}deg) translate(0)`);
        $(this).css("z-index", `5`);
        // $(this).css("opacity", opacity);
      })
    }
    function updateOrgChart () {
      var expandableTargetId = $(this).attr("id");
      var expandablePosToTrigger = $("#old-org-widget #" + expandableTargetId);
      expandablePosToTrigger.trigger("click");
      //wait for the org chart to expand
      var waitToExpand = setInterval(waitToExpandFn, 1000);
      function waitToExpandFn () {
         if (expandablePosToTrigger.hasClass("expanded") || expandablePosToTrigger.hasClass("expanded-top")) {
           clearInterval(waitToExpand);
           var expandablePos = 0;
           $("#old-org-widget").find(".expandable").each(function () {$(this).attr("id", "MINI-exapndable-pos-" + expandablePos++)});
           $("#MINI-org-widget").remove();
           updateContentSection("MINI-org", $("#old-org-widget").clone().addClass("org-chart").attr("id", "MINI-org-widget"));
           $("#MINI-org-widget .expandable").on("click", updateOrgChart);
           return false;
         }
       };
    }
    function makeCopyClickable () {
      var id = $(this).attr('id');
      var el = document.getElementById(id);
      var range = document.createRange();
      range.selectNodeContents(el);
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
      document.execCommand('copy');
      sel.removeAllRanges();

      $("#tooltiptext").text("Copied to clipboard!");
      $("#tooltiptext").addClass("copied");
      setTimeout(function() {
        $("#tooltiptext").removeClass("show");
      }, 800);

      return false;
    }
    function showTooltip () {
      $("#tooltiptext").removeClass("copied");
      $("#tooltiptext").addClass("show");
      // positioning
      var leftPos = $(this).offset().left + ($(this).width()/2) - 60;
      var topPos = $(this).offset().top - 30;
      $("#tooltiptext").offset({left: leftPos, top: topPos});
    }
    function removeTooltip () {
      $("#tooltiptext").removeClass("show");
      $("#tooltiptext").text("Copy to clipboard");
    }
    function showPassionBubble () {
      $("#MINI-share-passion-holder").toggleClass("active");
      $("#bubble-button").toggleClass("fa-comment-o");
      $("#bubble-button").toggleClass("fa-times");
    }
    function putInConfiguration () {
      var bodyColor;
      (async () => {
        bodyColor = await GM.getValue('ptMINIgetColor', false);

        if (bodyColor != false) {
          $("body").addClass(bodyColor);
        } else {
          $("body").addClass("orange");
        }
      })();
      $("#MINI-config").append(`
          <div id="MINI-color-swatches">
            <div class="swatch" id="white"></div>
            <div class="swatch" id="orange"></div>
            <div class="swatch" id="blue"></div>
            <div class="swatch" id="green"></div>
            <div class="swatch" id="red"></div>
          </div>
        `
      );
      $("#MINI-color-swatches .swatch").click(switchColor);
      function switchColor () {
        var newColor = $(this).attr("id");
        $("body").removeClass();
        $("body").addClass(newColor);
        (async () => {
          await GM.setValue('ptMINIgetColor', newColor);
        })();
      }
    }


    setupScaffolding();
    setupNameBlock();
    setupImageBlock();
    putInConfiguration();
    //Add profile details sections
    addProfileDetails();
    getPersonalInfoWidgets(params);
    getyOrgHistoryWidgets(params);
})();