ziep / RAPZ

// ==UserScript==
// @name        RAPZ
// @author      Michal "ceem" Kovac / ziep
// @namespace   com.heroesofnewerth.rap
// @description Updates to new RAP portal for HoN GMs. All credit goes to ceem for creating this, I merely updated it.
// @match     https://rap.heroesofnewerth.com/gm*
// @match     *://s3.amazonaws.com/*
// @updateURL https://openuserjs.org/install/ziep/RAPZ.user.js
// @downloadURL https://openuserjs.org/install/ziep/RAPZ.user.js
// @version  1.2.6
// @require  https://resources.patchworkklub.sk/js/jquery-2.2.4.min.js
// @require  https://raw.githubusercontent.com/mckamey/countdownjs/master/countdown.min.js
// @require  https://raw.githubusercontent.com/jeresig/jquery.hotkeys/master/jquery.hotkeys.js
// @require  https://resources.patchworkklub.sk/js/jquery-cookie.js
// @require  https://raw.githubusercontent.com/bunkat/later/master/later.min.js
// @require  https://raw.githubusercontent.com/jeresig/jquery.hotkeys/master/jquery.hotkeys.js
// @require  https://rap.heroesofnewerth.com/js/jquery.dataTables.min.js
// @require  https://rap.heroesofnewerth.com/js/dataTables.bootstrap.min.js
// @require  https://rap.heroesofnewerth.com/js/moment.js
// @require  https://code.jquery.com/ui/1.12.1/jquery-ui.js

// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_listValues
// @grant GM_openInTab
// @grant GM_setClipboard
// @grant GM_xmlhttpRequest
// @icon https://resources.patchworkklub.sk/rapp/icon.png
// @license MIT
// ==/UserScript==

// ========= Global variables ================================================================
//ziep
var $timeCalcDialog;
var $guilty_desc
var $warning_desc;
var $inno_desc
let afk_warning = 4, // Min time for warning for avoiding AFK (in minutes)
  afk_guilty = 7, // Min time for guilty for avoiding AFK (in minutes)
  warning_for_afk = 0,
  guilty_for_afk = 0;
//

var $gmName; // Name of logged in GM
var $reportedPlayerName; // Name of reported player
var $reportedPlayerAccountType; // Account type of reported player
var $reportedPlayerAccountStanding; // Account standing of reported player
var $reportedPlayerId; // ID of reported player
var $menu; // Parent navigation element
var $activeView; // Active view
var $timeZoneDifference; // Difference between server time and local time
var $settings = { // RAP+ settings
  gmDocs: "off",
  //ziep
  mentorDocs: "off",
  //
  chatlogExtendedCompatibility: "off",
  displayServerTime: "off",
  closeIndividualReports: "off",
  hidePastDecisions: "off",
  showViewSelection: "off",
  bolderText: "on",
  keyShortcuts: "off",
  hotkeys: [],
  colorScheme: "blue",
  ignoredOts: {}
};
var readyForNextRequest = true; // Asynchornous requests check
var requestsDone = 0; // Asynchornous requests count
var $lastRequestResponse; // Contains jQuery DOM for last asynch. request done
var $decisions; // Decisions made by GM
// Other settings
var soloInnocentCategories = ['Bad Nickname', 'Verbal abuse', 'Staff impersonation'];
var hotkeysPreset1 = ["shift+t", "shift+r", "shift+a", "shift+e", "shift+f", "shift+d", "shift+up", "shift+down", "shift+left", "shift+right", "shift+2", "shift+1", "shift+3", "shift+4", "shift+x", "alt+shift+x", "shift+v", "shift+b", "alt+shift+c", "alt+shift+down", "alt+shift+up"];
var hotkeysPreset2 = ["alt+shift+r", "shift+r", "shift+a", "shift+c", "shift+q", "shift+d", "shift+up", "shift+down", "shift+left", "shift+right", "shift+1", "alt+shift+1", "shift+2", "shift+3", "shift+x", "alt+shift+x", "shift+v", "shift+b", "alt+shift+s", "alt+shift+down", "alt+shift+up"];
var hotkeysDescription = ["Request all replays/chatlogs", "Request selected match replay/chatlog", "Chatlog Analysis for selected match", "Open Chat Log for selected match", "Copy Match ID of selected match", "Download replay for selected match", "Jump on previous ticket", "Jump on next ticket", "Jump on previous match", "Jump on next match",
  "Innocent selected ticket only (if possible)", "Innocent selected match", "Guilty decision", "Warning decision", "Close selected report", "Close selected match", "Report Throwaway account form", "Priority ticket form", "Get next available ticket", "Select previous category", "Select next category"
];

// Links, forms and IDs of form fields
var $reportBnURL = "https://confluence.hon.team/display/GM/REPORT%3A+Bad+Nicknames";
//var $loadingImage = "https://www.tripshock.com/img/loading.gif";
var $loadingImage = "https://resources.patchworkklub.sk/rapp/loading.gif";
var $copyToCliboardImage = "https://resources.patchworkklub.sk/rapp/clipboard_plus.png";
var $reportArrowImage = "https://resources.patchworkklub.sk/rapp/list_arrow_rm.gif";
var $gmDocsURL = "https://docs.google.com/spreadsheets/d/1BD69YhiVFDghUfpDLeE1M6MTZk1UYFgHXPbMmKu1Rlc/";
//ziep
var $mentorDocsURL = "https://docs.google.com/spreadsheets/d/1QPmry2FhcJkguvk2pxL0CAOsxfCONXS_dfoFFRUSmXQ/edit#gid=0";
//
var $priorityTicketURL = "https://docs.google.com/forms/d/e/1FAIpQLSfnPVNfMv-zaF59iQ540k9fZ9cLegutZqym3-xmg87EPop0gw/viewform";
var $throwawayURL = "https://docs.google.com/forms/d/e/1FAIpQLSfkxBuu5vMBynxXmBOlcywJTmz3xYaL2PnIMzXlRnnAeBPiWg/viewform";
var $priorityTicketFieldGM = "878209702";
var $throwawayFieldGM = "1074411029";
var $throwawayFieldReported = "1839907460";
var $throwawayFieldTicket = "1618775217";

// ===========================================================================================

// ========= Other initialisation ============================================================
initLoading();
//Initialize moment.js
moment().format();
updateSettings("object");
// ===========================================================================================

// ========= Decide which view we have active ================================================

if ($(".login-form h3:contains('Sign In')").length == 0) { // All the pages after logon
  $activeView = "global";
  var $expiredLi = $("li:contains('Your password has expired. It must be changed before you can continue')");
  if (window.location.pathname === "/gm/profile" || $expiredLi.length) {
    $("input[type='password']").attr("readonly", "");
    $(".page-content").prepend('<h1 style="color: red;">DISABLE ALL SCRIPTS BEFORE CHANGING YOUR PASSWORD, OR CHANGE YOUR PASSWORD IN AN INCOGNITO WINDOW!</h1>');
    $(".page-content").append("<img src='https://rap.heroesofnewerth.com/images/ajax/pika3.gif'>");
  }
  else {
    initGlobal();
  }
}

if ($("div.caption:contains('Open tickets')").length) { // Ticket View only
  $activeView = "ticket";
  initTicketView();
}

if ($("h1.page-title:contains('GM Dashboard')").length) { // Dashboard only
  $activeView = "dashboard";
  initDashboard();
}

// ===========================================================================================

// ========= CSS =============================================================================
function updateCSS() {
  var fontWeight = $settings.bolderText == "on" ? "" : "font-weight:100;";
  $('#rapp-style').remove();

  //                  0         1         2         3         4         5         6         7         8         9         10        11        12        13
  pinkPalette = ["#d45fc9", "#564755", "#d248c5", "#8a167f", "#ea5edd", "#ef8ee6", "#c72491", "#fff6fd", "#f1cbe8", "#a77f9d", "#e295d0", "#a5007e", "#ad699d", "#e6badc"];
  greenPalette = ["#65a530", "#4b5647", "#539e1e", "#328a16", "#7ec34e", "#92e278", "#183c06", "#ddffc6", "#a4e27a", "#aede86", "#53a90a", "#152d00", "#53a90a", "#8daf71"];
  bluePalette = ["#4b77be", "#374e63", "#3a64a9", "#374e63", "#6e9ae2", "#ebf5ff", "#0d3d88", "#ebf5ff", "#bfdaf5", "#a8c7e6", "#9cbff9", "#061e3c", "#9cbff9", "#9cbff9"];
  yellowPalette = ["#d6b715", "#565447", "#bd9910", "#a08406", "#e8cd00", "#e2d278", "#676009", "#ffffc6", "#f5e98c", "#cec36e", "#d8c33a", "#6f5b0d", "#d8c33a", "#d8c33a"];
  palette = ($settings.colorScheme == "pink" ? pinkPalette : ($settings.colorScheme == "blue" ? bluePalette : ($settings.colorScheme == "yellow" ? yellowPalette : greenPalette)));
  var colorNav1 = palette[0];
  var colorNav2 = palette[1];
  var colorNavIconBg = palette[2];
  var colorNavIconBorder = palette[3];
  var colorNavIconBgHover = palette[4];
  var colorNavIconBorderHover = palette[5];
  var colorActiveReport = palette[6];
  var colorMatchBg = palette[7];
  var colorMatchBtnBg = palette[8];
  var colorMatchBtnBgHover = palette[9];
  var colorMatchBtnBorder = palette[10];
  var colorMatchBtnText = palette[11];
  var colorMatchLine = palette[12];
  var colorMatchBorder = palette[13];

  $('head').append("<link rel='stylesheet' href='https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css'>" +
    "<style id='rapp-style' type='text/css'>" +
    "#rapp-version {padding: 10px 15px;background: " + colorNav1 + ";border-top: 3px solid white;color: white;" + fontWeight + "position: relative;font-size:15px}" +
    ".rapp-statsDl {font-size: 13px; margin-bottom:0px;}" +
    ".rapp-statsDt {float: left; clear: left; width: 140px; text-align: left; font-weight:100; position:relative}" +
    ".rapp-statsDd {margin: 0 0 0 150px; padding: 0 0 0.5em 0;}" +
    "span.rapp-title {visibility: hidden;font-size: 10px; width: 120px; background-color:rgba(0, 0, 0, 0.8);color: white;text-align: center;padding: 5px;border-radius:6px;z-index: 1; position:absolute;}" +
    "span.rapp-hover {border-bottom:1px dotted black;}" +
    ".rapp-statsDd span.rapp-title{  top:-5px;left:75px;}" +
    ".priors-indicator span.rapp-title {top:-25px;left:30px}" +
    ".priors-indicator span.prior-desc {margin-top:7px; color:white;display: block; float: left;margin-right:10px; font-size:14px;}" +
    ".priors-indicator {position:absolute;top:2px;right:20px;font-size:10px;background: #424242; color:#424242;border-radius: 6px; padding: 2px 2px 2px 15px;}" +
    ".priors-indicator div {line-height: 10px;float:right;text-align:center;height:33px; padding-top:5px; width: 40px; border-radius:6px;border:1px solid #424242;margin-left:2px;}" +
    ".rapp-prior {background: #ec971f;}" + //ffd400
    ".rapp-noprior {background: #5cb85c;}" + //#a2da19
    ".matchTitle {       margin-bottom: 5px; border-bottom: 1px solid #364150;    color: #364150;    height: 27px;    padding-top: 2px;    padding-left: 2px;}" +
    ".rapp-chaLink,.matchTitle .rapp-chatlogLink {    display: inline-block;    padding: 3px; " + fontWeight + "  font-size: 11px;    position: relative;top: -3px;margin: 0px 2px;float: right;background: #ebf2ff;border: 1px solid #a1b9dc;color: #536379;}" +
    ".rapp-activeMatch .rapp-chaLink,.rapp-activeMatch .matchTitle .rapp-chatlogLink {background: " + colorMatchBtnBg + ";border: 1px solid " + colorMatchBtnBorder + ";color: " + colorMatchBtnText + ";}" +
    ".rapp-activeMatch .matchTitle {border-color:" + colorMatchLine + "}" +
    ".matchTitle .rapp-chatlogLink {width:47px}" +
    ".matchTitle strong {float:left;margin:0; padding:0;}" +
    ".rapp-chaLink:hover, .rapp-chaLink:active, .rapp-chaLink:focus, .matchTitle .rapp-chatlogLink:hover, .matchTitle .rapp-chatlogLink:active, .matchTitle .rapp-chatlogLink:focus {color:white; text-decoration:none;background:#6d8fad;}" +
    ".rapp-activeMatch .rapp-chaLink:hover, .rapp-activeMatch .rapp-chaLink:active, .rapp-activeMatch .rapp-chaLink:focus, .rapp-activeMatch .matchTitle .rapp-chatlogLink:hover, .rapp-activeMatch .matchTitle .rapp-chatlogLink:active, .rapp-activeMatch .matchTitle .rapp-chatlogLink:focus {color:white; text-decoration:none;background: " + colorMatchBtnBgHover + ";}" +
    ".ui-widget-header {    background: " + colorNav1 + ";    " + fontWeight + "    color: #fff;}" +
    ".matchDiv {overflow:hidden;padding: 6px; margin: 10px 0px; border-bottom: 1px solid #f5f5f5; min-width:460px;}" +
    ".matchDiv .rapp-reportLink {padding-left: 30px; margin-left: 0; background:url('" + $reportArrowImage + "') 1px no-repeat;" + fontWeight + "   color: #3a79d0;    font-size: 13px;}" +
    ".matchDiv .rapp-reportLink.closable {padding-left: 5px; margin-left: 0; background-image:none;}" +
    ".rapp-activeMatch .matchDiv .rapp-reportLink {color:#ea73d;}" +
    ".styled-select {  display:inline;position:relative; width: 80px;   height: 20px;   overflow: hidden;   background: url(http://eur-lex.europa.eu/images/box-minimize.png) no-repeat right #fff;    border: 1px solid #a0a0a0;  }" +
    ".matchStatus {position:relative;margin-left: 5px;color: #364150;box-shadow: none;    background-color: transparent;    background-image: none;    -webkit-appearance: none;       -moz-appearance: none;appearance: none;border: none;font-size: 12px;width: 80px;top: -1px; " + fontWeight + "}" +
    ".matchStatus:focus {    outline: none;}" +
    ".mSinnocent {background-color: #5cb85c;border-color: #37a728;}" +
    ".mSeasyInno {background-color: rgb(54, 211, 198);    border-color: #2891a7;}" +
    ".mSwarning {background-color: #f1df54;    border-color: #c1bb2a;}" +
    ".mSbroken {background-color: #ddd;border-color: #ccc;}" +
    ".rapp-ticketGameTime{float:right;font-size:11px;}" +
    ".rapp-ticketViewers{font-size:11px; padding-left: 20px; margin: 3px 30px;color: #ce0000;border: 1px solid #ffb3b3;border-radius: 2px;background: #ffeeee;padding: 2px;}" +
    ".rapp-ticketDescription{font-size:11px; padding-left: 20px;}" +
    ".rapp-activeMatch .rapp-activeReport {text-decoration:underline;color:" + colorActiveReport + "}" +
    ".rapp-activeMatch {background-color: " + colorMatchBg + ";    border: 1px solid " + colorMatchBorder + ";border-radius: 9px; padding: 5px;}" +
    "#rapp-settings {position: absolute;border: 1px solid " + colorNavIconBorder + ";border-radius: 6px !important;margin: 0;padding: 4px 0px 6px 3px;background: " + colorNavIconBg + ";top: 6px;right: 19px;display: block;}" +
    "#rapp-settings:hover {border-color: " + colorNavIconBorderHover + ";background: " + colorNavIconBgHover + ";}" +
    "#rapp-settings i {color:white}" +
    "#rapp-settingsBox label{font-weight:normal}" +
    ".rapp-menuItem {padding: 8px 10px 0px !important;    color: #d2d5da;    " + fontWeight + "font-size: 13px;    background: " + colorNav2 + ";}" +
    "#rapp-priority_ticket_item, #rapp-throwaway_item {padding: 0 !important; border-top: 2px solid " + colorNav1 + ";}" +
    ".matchTitle strong {padding-right: 20px; " + fontWeight + "}" +
    ".matchTitle strong:hover {cursor:pointer; background:url('" + $copyToCliboardImage + "') no-repeat " + (fontWeight == "" ? "10.2" : "9.8") + "em;}" +
    ".rapp-closeTicket{float: left;    color: #c74a46;    width: 20px;    height: 21px;    font-size: 15px;    text-align: center;padding: 3px 5px 1px 2px;    margin: 0px 6px 0px 1px;}" +
    ".rapp-closeTicket:hover{color:#ff8985;cursor:pointer;}" +
    "#rapp-serverTime{color:white;padding-top: 8px;width:95px; " + fontWeight + "}" +
    "#rapp-serverTime span{color:#c6cfda; font-size:10px;}" +
    //"span#decisions_stats {margin-bottom:10px}"+
    "#rapp-statsDecisionsCycle, #rapp-statsTable {padding-bottom:4px}" +
    "#rapp-statsDecisionsCycle .glyphicon {color:#337ab7;}" +
    "#rapp-statsDecisionsCycle span.cycleCount {position:relative;left:30px;}" +
    "#rapp-statsDecisionsCycle span.cycleCount i {margin-left:5px;}" +
    "#rapp-statsTable {    " + fontWeight + " margin-left:10px; font-size:13px; color:#d2d5da;}" +
    "#rapp-statsTable td.statKey {width:140px}" +
    "#rapp-statsTable td.statValue {}" +
    ".hidden {display:none}" +
    "#rapp-decisionsMade.minimized {height:43px;}" +
    ".rapp-singleTicketSubmit {    margin-left: 2px;    color: #37a728;    display: inline-block;    width: 20px;    padding: 1px 0px 0px 2px;    font-size: 17px;    height: 20px;    position: relative;    top: 2px;}" +
    ".rapp-singleTicketSubmit:hover,.rapp-singleTicketSubmit:active,.rapp-singleTicketSubmit:focus {color:#31e419;}" +
    ".rapp-singleTicketSubmit.innoVA {color:#2891a7}" +
    ".rapp-singleTicketSubmit.innoVA:hover,.rapp-singleTicketSubmit.innoVA:active,.rapp-singleTicketSubmit.innoVA:focus {   color: #36d3c6;}" +
    ".rapp-column-left {width:50%;float:left;padding-right:10px;border-right: 1px solid #f5f5f5; clear:right;}" +
    ".rapp-column-right {width:50%;float:right;padding-left:10px;}" +
    ".rapp-closeReport {cursor: pointer;    color: #c74a46;    margin-left: 10px;    width: 16px;    display: inline-block;    font-size: 14px;    text-align: center;    position: relative;bottom: -1px;}" +
    ".rapp-closeReport:hover {color:#ff8985}" +
    "#rapp-showDecisionsMade {margin: 6px 5px 0 0;font-size: 12px;cursor: pointer;color: white;background: #337ab7;padding: 4px;border-bottom: 1px solid #424242;border-radius: 6px;}" +
    "#rapp-decisionsMadeDialog.ui-dialog-content a {color:#337ab7}" +
    "#rapp-openTickets,#rapp-decisionsMade {position:relative}" +
    "#rapp-innoTicketDialog .disclaimer {color: #ce0000;border: 1px solid #ffb3b3;border-radius: 5px;background: #ffeeee;padding: 5px;}" +
    "#rapp-innoTicketDialog .wait {color: #d4a314;border: 1px solid #ffd958;border-radius: 5px;background: #fdf6dc;padding: 5px;}" +
    "#rapp-innoAllBn, #rapp-reportBn {font-size: 13px; " + fontWeight + "padding: 4px 5px;position: relative;top: -2px;border-radius: 4px;background: linear-gradient(to top right, #1f801f , #80cc80);border: 1px solid #7cca89;color: white;}" +
    "#rapp-reportBn {background: #ed6b75;    border: 1px solid #ca6260;}" +
    "#rapp-innoAllBn:hover,#rapp-innoAllBn:active,#rapp-innoAllBn:focus {background: #ca6260;    border: 1px solid #ca6260;}" +
    "#rapp-reportBn:hover,#rapp-reportBn:active,#rapp-reportBn:focus {background: #c54b4b;color: #d2baba;}" +
    "#rapp-requestAllReplays {" + fontWeight + " text-transform:uppercase;display: inline-block;color: #e4f2ff;background: #6e9ae2;padding: 5px;position: absolute;top: 8px;border-radius: 5px;left: 170px;font-size: 11px;}" +
    "#rapp-requestAllReplays i {font-size:15px;    position: relative;    top: 3px;}" +
    "#rapp-requestAllReplays:hover {background:#506786}" +
    '.blueScheme,.yellowScheme,.pinkScheme,.greenScheme {position:relative; display:inline-block;width:15px;height:15px; margin-left:5px; padding:5px; cursor:pointer}' +
    '.blueScheme {background:' + bluePalette[0] + ';}' +
    '.pinkScheme {background:' + pinkPalette[0] + ';}' +
    '.greenScheme {background:' + greenPalette[0] + ';}' +
    '.yellowScheme {background:' + yellowPalette[0] + ';}' +
    'div.colorSchemeSelected {padding:8px;top:2px;border:1px solid black;}' +
    '#colorSchemeSelection {padding-top:10px;}' +
    '.selColumn {background: ' + palette[4] + ';}' +
    '#rapp-configureKeys table {font-size:11px;}' +
    '#rapp-configureKeys table td, #rapp-configureKeys table th {padding: 2px;border: 1px solid #d8d8d8;}' +
    '.dec-circle {display: inline-block;transform: translateZ(1px);}' +
    '.dec-circle > div {display: inline-block;width: 20px;height: 20px;margin: -4px 0 -4px -8px;border-radius: 50%!important;background: #fff;animation: dec-circle 2.4s cubic-bezier(0, 0.2, 0.8, 1) infinite;}' +
    '@keyframes dec-circle {0%, 100% {animation-timing-function: cubic-bezier(0.5, 0, 1, 0.5);}0% {transform: rotateY(0deg);}50% {transform: rotateY(1800deg);animation-timing-function: cubic-bezier(0, 0.5, 0.5, 1);}100% {transform: rotateY(3600deg);}}' +
    //".col-xs-6 {width:auto;}" +
    ".ui-dialog-content{width: 800px; height: 1000px;}" +
    ".gmPopupContainer .ui-dialog-content .ui-widget-content{width: auto; height: auto;padding: 5%;}" +
    ".ui-dialog {position: absolute;top: 0;left: 0;padding: .2em;outline: 0;width: 800;height:auto;}" +
    "</style>");
}

// ===========================================================================================

// ======== Initialization functions =========================================================

// Initialize loading image
function initLoading() {
  $("#loading").html("<div class='dec-circle'><div></div></div>");
}

// Initialize settings for RAP+
function updateSettings(target) {
  if (!$.cookie("rapp-settings-gmDocs")) {
    $.cookie("rapp-settings-gmDocs", "off", {
      expires: 666,
      path: '/'
    });
  }
  //ziep
  if (!$.cookie("rapp-settings-mentorDocs")) {
    $.cookie("rapp-settings-mentorDocs", "off", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapz-settings-autoCopyMID")) {
    $.cookie("rapz-settings-autoCopyMID", "off", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapz-settings-autoRequest")) {
    $.cookie("rapz-settings-autoRequest", "off", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapz-settings-TSCalc")) {
    $.cookie("rapz-settings-TSCalc", "on", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapz-settings-disableAlert")) {
    $.cookie("rapz-settings-disableAlert", "off", {
      expires: 666,
      path: '/'
    });
  }
  //
  if (!$.cookie("rapp-settings-displayServerTime")) {
    $.cookie("rapp-settings-displayServerTime", "off", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapp-settings-chatlogExtendedCompatibility")) {
    $.cookie("rapp-settings-chatlogExtendedCompatibility", "off", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapp-settings-closeIndividualReports")) {
    $.cookie("rapp-settings-closeIndividualReports", "off", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapp-settings-hidePastDecisions")) {
    $.cookie("rapp-settings-hidePastDecisions", "off", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapp-settings-showViewSelection")) {
    $.cookie("rapp-settings-showViewSelection", "off", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapp-settings-bolderText")) {
    $.cookie("rapp-settings-bolderText", "on", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapp-settings-keyShortcuts")) {
    $.cookie("rapp-settings-keyShortcuts", "off", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapp-settings-hotkeys")) {
    $.cookie("rapp-settings-hotkeys", JSON.stringify({}), {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapp-settings-colorScheme")) {
    $.cookie("rapp-settings-colorScheme", "blue", {
      expires: 666,
      path: '/'
    });
  }
  if (!$.cookie("rapp-settings-ignoredOts")) {
    $.cookie("rapp-settings-ignoredOts", JSON.stringify({}), {
      expires: 666,
      path: '/'
    });
  }

  if (target == "object" || target == "obj" || target == "o") {
    $settings.gmDocs = $.cookie("rapp-settings-gmDocs");
    //ziep
    $settings.mentorDocs = $.cookie("rapp-settings-mentorDocs");
    $settings.autoCopyMID = $.cookie("rapz-settings-autoCopyMID");
    $settings.autoRequest = $.cookie("rapz-settings-autoRequest");
    $settings.TSCalc = $.cookie("rapz-settings-TSCalc");
    $settings.disableAlert = $.cookie("rapz-settings-disableAlert");
    //
    $settings.chatlogExtendedCompatibility = $.cookie("rapp-settings-chatlogExtendedCompatibility");
    $settings.displayServerTime = $.cookie("rapp-settings-displayServerTime");
    $settings.closeIndividualReports = $.cookie("rapp-settings-closeIndividualReports");
    $settings.hidePastDecisions = $.cookie("rapp-settings-hidePastDecisions");
    $settings.showViewSelection = $.cookie("rapp-settings-showViewSelection");
    $settings.bolderText = $.cookie("rapp-settings-bolderText");
    $settings.keyShortcuts = $.cookie("rapp-settings-keyShortcuts");
    $settings.hotkeys = JSON.parse($.cookie("rapp-settings-hotkeys"));
    $settings.colorScheme = $.cookie("rapp-settings-colorScheme");
    $settings.ignoredOts = JSON.parse($.cookie("rapp-settings-ignoredOts"));
  }
  if (target == "cookies" || target == "c") {
    $.cookie("rapp-settings-gmDocs", $settings.gmDocs, {
      expires: 666,
      path: '/'
    });
    //ziep
    $.cookie("rapp-settings-mentorDocs", $settings.mentorDocs, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapz-settings-autoCopyMID", $settings.autoCopyMID, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapz-settings-autoRequest", $settings.autoRequest, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapz-settings-TSCalc", $settings.TSCalc, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapz-settings-disableAlert", $settings.disableAlert, {
      expires: 666,
      path: '/'
    });
    //
    $.cookie("rapp-settings-chatlogExtendedCompatibility", $settings.chatlogExtendedCompatibility, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapp-settings-displayServerTime", $settings.displayServerTime, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapp-settings-closeIndividualReports", $settings.closeIndividualReports, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapp-settings-hidePastDecisions", $settings.hidePastDecisions, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapp-settings-showViewSelection", $settings.showViewSelection, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapp-settings-bolderText", $settings.bolderText, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapp-settings-keyShortcuts", $settings.keyShortcuts, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapp-settings-hotkeys", JSON.stringify($settings.hotkeys), {
      expires: 666,
      path: '/'
    });
    $.cookie("rapp-settings-colorScheme", $settings.colorScheme, {
      expires: 666,
      path: '/'
    });
    $.cookie("rapp-settings-ignoredOts", JSON.stringify($settings.ignoredOts), {
      expires: 666,
      path: '/'
    });
  }
}

// Initialize every page of portal, after logon
function initGlobal() {
  updateCSS();

  // --------- Parse GM name ---------------------------------------------------------------
  var $logoffButtonText = $('span.username').text();
  $gmName = $logoffButtonText.substring($logoffButtonText.indexOf("GM: ") + 4).trim();
  // ---------------------------------------------------------------------------------------

  // --------- Define new menu items  ------------------------------------------------------
  var $newMenuItemCountdown = "<li class='rapp-menuItem' id='rapp-cycle_countdown'><i class='icon-hourglass'></i><span><div class='dec-circle'><div></div></div></span> left</li>";
  var $newMenuItemDecisionsStats = "<li class='rapp-menuItem'><span id='decisions_stats'><div class='dec-circle'><div></div></div><span style='display:inline-block;margin:7px'>Fetching decisions...</span></span></li>";
  var $newMenuItemVersion = "<li class='nav-item' id='rapp-version'><span class='title'>RAPZ v" + GM_info.script.version + "</span><a href='#' id='rapp-settings'><i class='icon-settings'></i></a></li>";
  var $priorityTicketFields = "?entry." + $priorityTicketFieldGM + "=" + $gmName;
  //var $newMenuItemPriorityTicket = "<li class='rapp-menuItem' id='rapp-priority_ticket_item'><a id='priority_ticket_link' target='_blank' href='"+$priorityTicketURL+$priorityTicketFields+"'><i class='icon-energy'></i><span class='title'>Submit Priority Ticket<span></a></li>";

  $menu = $('ul.page-sidebar-menu');
  $menu.append($newMenuItemVersion);
  $menu.append($newMenuItemCountdown);
  $menu.append($newMenuItemDecisionsStats);
  $("#priority_ticket_link").click(function ($event) {
    var $link = $(this).attr("href");
    if ($link.length > 0) {
      GM_openInTab($link);
    }
    $event.preventDefault();
  });
  // ---------------------------------------------------------------------------------------

  // --------- Manage settings -------------------------------------------------------------
  $("body").append('<div id="rapp-settingsBox">' +
    '<input type="checkbox" id="checkbox-gmDocs" name="checkbox-gmDocs" ' + ($settings.gmDocs == "on" ? "checked" : "") + '>' +
    '<label for="checkbox-gmDocs">Display GM Docs on Dashboard</label>' + '<br />' +
    //ziep
    '<input type="checkbox" id="checkbox-mentorDocs" name="checkbox-mentorDocs" ' + ($settings.mentorDocs == "on" ? "checked" : "") + '>' +
    '<label for="checkbox-mentorDocs">Display Mentor Docs on Dashboard (Mentor)</label>' + '<br />' +
    //
    '<input type="checkbox" id="checkbox-chatlogCompat" name="checkbox-chatlogCompat" ' + ($settings.chatlogExtendedCompatibility == "on" ? "checked" : "") + '>' +
    '<label for="checkbox-chatlogCompat">Compatibility mode with GM Chatlog Extended Script</label>' + '<br />' +
    '<input type="checkbox" id="checkbox-hidePastDecisions" name="checkbox-hidePastDecisions" ' + ($settings.hidePastDecisions == "on" ? "checked" : "") + '>' +
    '<label for="checkbox-hidePastDecisions">Hide "Decisions made" and only show priors indicator</label>' + '<br />' +
    '<input type="checkbox" id="checkbox-keyShortcuts" name="checkbox-keyShortcuts" ' + ($settings.keyShortcuts == "on" ? "checked" : "") + '>' +
    '<label for="checkbox-keyShortcuts">Activate key shortcuts ' + '<input type="button" id="configureKeys" value="Configure...">' + '</label> ' + '<br />' +
    '<input type="checkbox" id="checkbox-bolderText" name="checkbox-bolderText" ' + ($settings.bolderText == "on" ? "checked" : "") + '>' +
    '<label for="checkbox-bolderText">Use bolder text</label>' + '<br />' +
    '<input type="checkbox" id="checkbox-closeIndividualReports" name="checkbox-closeIndividualReports" ' + ($settings.closeIndividualReports == "on" ? "checked" : "") + '>' +
    '<label for="checkbox-closeIndividualReports">Individual report closing (SGM)</label>' + '<br />' +
    '<input type="checkbox" id="checkbox-serverTime" name="checkbox-serverTime" ' + ($settings.displayServerTime == "on" ? "checked" : "") + '>' +
    '<label for="checkbox-serverTime">Show server time (SGM)</label>' + '<br />' +
    '<input type="checkbox" id="checkbox-showViewSelection" name="checkbox-showViewSelection" ' + ($settings.showViewSelection == "on" ? "checked" : "") + '>' +
    '<label for="checkbox-showViewSelection">Show view selection (SGM)</label>' + '<br />' +
    '<input type="button" id="manageOverturns" value="Manage overturns in stats" />' +

    '<br><br>' + '<input type="button" id="zettings" value="RAPZettings">' + '<br />' +

    '<div id="colorSchemeSelection">' +
    '<span>Color Scheme :</span><div class="blueScheme"></div>' +
    '<div class="pinkScheme"></div>' +
    '<div class="greenScheme"></div>' +
    '<div class="yellowScheme"></div>' +
    '</div>' +
    '</div>' +
    '<div id="rapp-manageOverturns"><p>Select overturns to ignore during stats calculation:</p><div id="rapp-otList"></div></div>' +
    '<div id="rapz-zettings"><p>RAPZ settings</p></div>' +
    '<div id="rapp-configureKeys"><p>Select shortcut configuration:</p></div>');
  $('#colorSchemeSelection div').each(function (e) {
    if ($(this).hasClass($settings.colorScheme + 'Scheme')) {
      $(this).addClass('colorSchemeSelected');
    }
  });

  $('#colorSchemeSelection div').click(function (e) {
    $('#colorSchemeSelection div').removeClass('colorSchemeSelected');
    $(this).addClass('colorSchemeSelected');
  });

  updateKeyShortcuts();

  var $rappSettingsDialog = $("#rapp-settingsBox").dialog({
    autoOpen: false,
    height: "auto",
    width: 450,
    modal: true,
    title: "RAP+ Settings",
    buttons: {
      "Save & apply settings": function () {
        $.cookie("rapp-cycle_end", $cycleEnd.toUTCString(), {
          expires: 28,
          path: '/'
        });
        $settings.gmDocs = $("#checkbox-gmDocs").is(':checked') ? "on" : "off";
        //ziep
        $settings.mentorDocs = $("#checkbox-mentorDocs").is(':checked') ? "on" : "off";
        $settings.autoCopyMID = $("#checkbox-autoCopyMID").is(':checked') ? "on" : "off";
        $settings.autoRequest = $("#checkbox-autoRequest").is(':checked') ? "on" : "off";
        $settings.TSCalc = $("#checkbox-TSCalc").is(':checked') ? "on" : "off";
        $settings.disableAlert = $("#checkbox-disableAlert").is(':checked') ? "on" : "off"

        //
        $settings.chatlogExtendedCompatibility = $("#checkbox-chatlogCompat").is(':checked') ? "on" : "off";
        $settings.displayServerTime = $("#checkbox-serverTime").is(':checked') ? "on" : "off";
        $settings.hidePastDecisions = $("#checkbox-hidePastDecisions").is(':checked') ? "on" : "off";
        $settings.showViewSelection = $("#checkbox-showViewSelection").is(':checked') ? "on" : "off";
        $settings.closeIndividualReports = $("#checkbox-closeIndividualReports").is(':checked') ? "on" : "off";
        $settings.bolderText = $("#checkbox-bolderText").is(':checked') ? "on" : "off";
        $settings.keyShortcuts = $("#checkbox-keyShortcuts").is(':checked') ? "on" : "off";
        $settings.colorScheme = $('div.colorSchemeSelected').attr('class').substring(0, $('div.colorSchemeSelected').attr('class').indexOf('Scheme'));
        updateSettings("cookies");
        updateGmDocsDisplay();
        //ziep
        updateMentorDocsDisplay();
        //
        updateZettings();
        updateCurrentTicket();
        updateDecisionsDisplay(null);
        updateDisplayOfServerTime();
        updateViewSelection();
        updateKeyShortcuts();
        updateCSS();
        $rappSettingsDialog.dialog("close");
      },
      "Cancel": function () {
        $rappSettingsDialog.dialog("close");
      }
    }
  });

  $("#rapp-settings").click(function ($event) {
    $event.preventDefault();
    $rappSettingsDialog.dialog("open");
  });

  // ---------------------------------------------------------------------------------------

  // --------- Update left menu with cycle countdown & decision stats ----------------------
  var $cycleEnd;
  var $cycleStart;

  $timeZoneDifference = new Date(new Date("Fri 3 Dec 2020 00:00:00 EST") - new Date("Fri 3 Dec 2020 00:00:00"));

  if ($.cookie("rapp-cycle_end")) { // Initialize $cycleEnd & validate cookie
    $cycleEnd = new Date($.cookie("rapp-cycle_end"));
    if ($cycleEnd.toString() == "Invalid Date") {
      $cycleEnd = new Date("Fri 3 Dec 2020 00:00:00 EST");
      $.cookie("rapp-cycle_end", $cycleEnd.toUTCString(), {
        expires: 2,
        path: '/'
      });
    }
  }
  else {
    $cycleEnd = new Date("Fri 4 Dec 2020 00:00:00 EST");
  }

  var $now = new Date();
  if ($cycleEnd < $now) {
    while ($cycleEnd < $now) {
      $cycleEnd.setDate($cycleEnd.getDate() + 7);
    }
  }
  $cycleStart = new Date();
  $cycleStart.setTime($cycleEnd.getTime());
  $cycleStart.setDate($cycleEnd.getDate() - 7);
  $.cookie("rapp-cycle_end", $cycleEnd.toUTCString(), {
    expires: 7,
    path: '/'
  });
  countdown(function (ts) {
    $("#rapp-cycle_countdown span").html(ts.toString());
  }, $cycleEnd, countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS, 2);
  // <Update decision stats & management of overturns in stats display>
  updateCycleDecisions($gmName, $cycleStart, $timeZoneDifference, "#decisions_stats");
  updateSettings("cookies");

  var $manageOverturnsDialog = $("#rapp-manageOverturns").dialog({
    autoOpen: false,
    height: "auto",
    width: 550,
    modal: true,
    title: "RAP+ Settings - Manage overturns in stats",
    buttons: {
      "Save & apply settings": function () {
        $settings.ignoredOts = {};
        $('#rapp-otList select').each(function (index) {
          $settings.ignoredOts[$(this).attr('id').replace('sel-ot-', '')] = $(this).val();
        });
        updateSettings("cookies");
        updateCycleDecisions($gmName, $cycleStart, $timeZoneDifference, "#decisions_stats");
        updateSettings("cookies");
        $manageOverturnsDialog.dialog("close");
      },
      "Cancel": function () {
        $manageOverturnsDialog.dialog("close");
      }
    }
  });

  $("input[type='button']#manageOverturns").click(function ($event) {
    $event.preventDefault();
    $('#rapp-otList').html('');
    $decisions.forEach(function ($decision) {
      if ($decision.status == "Undone") {
        $('#rapp-otList').append('<p>Overturned decision ' + $decision.id + ' (' + new Date(Date.parse($decision.time) + Date.parse($timeZoneDifference)).toISOString().slice(0, 10) + ') ' +
          '<select id="sel-ot-' + $decision.id + '">' +
          '<option value="ot">No change (count as OT)</option>' +
          '<option value="count">Count as a valid decision</option>' +
          '<option value="ignore">Ignore completely</option>' +
          '</select>' +
          '</p>');
        $('#sel-ot-' + $decision.id).val($settings.ignoredOts[$decision.id]);

      }
    });
    $manageOverturnsDialog.dialog("open");
  });
  //ziep ----------------------------------------------------------------------
  var $zettingsDialog = $("#rapz-zettings").dialog({
    autoOpen: false,
    height: "auto",
    width: 550,
    modal: true,
    title: "RAPZ Settings",
    buttons: {
      "OK": function () {

        updateSettings("cookies");
        $zettingsDialog.dialog("close");
      },
      "Cancel": function () {
        $zettingsDialog.dialog("close");
      }
    }
  });
  $("input[type='button']#zettings").click(function ($event) {
    //$event.preventDefault();
    $('#rapz-zettings').children().remove();
    $("#rapz-zettings").append('<input type="checkbox" id="checkbox-autoRequest" name="checkbox-autoRequest" ' + ($settings.autoRequest == "on" ? "checked" : "") + '>' +
      '<label for="checkbox-autoRequest">Auto request replays</label>' +
      '<br>' + '<input type="checkbox" id="checkbox-autoCopyMID" name="checkbox-autoCopyMID" ' + ($settings.autoCopyMID == "on" ? "checked" : "") + '>' +
      '<label for="checkbox-autoCopyMID">Auto copy match ID</label>' +
      '<br>' + '<input type="checkbox" id="checkbox-TSCalc" name="checkbox-TSCalc" ' + ($settings.TSCalc == "on" ? "checked" : "") + '>' +
      '<label for="checkbox-TSCalc">Enable timestamp calculator</label>' +
      '<br>' + '<input type="checkbox" id="checkbox-disableAlert" name="checkbox-disableAlert" ' + ($settings.disableAlert == "on" ? "checked" : "") + '>' +
      '<label for="checkbox-disableAlert">Disable replays requested alert </label>');

    if ($("#checkbox-autoRequest").is(':checked')) {
      $("rapp-zettings").append('<br>' + '<input type="checkbox" id="checkbox-disableAlert" name="checkbox-disableAlert" ' + ($settings.disableAlert == "on" ? "checked" : "") + '>' +
        '<label for="checkbox-disableAlert">Disable replays requested alert </label>');
    };

    $zettingsDialog.dialog("open");
  });
  // ----------------------------------------------------
  var $configureKeysDialog = $("#rapp-configureKeys").dialog({
    autoOpen: false,
    height: "auto",
    width: 550,
    modal: true,
    title: "RAP+ Settings - Configure keyboard shortcuts",
    buttons: {
      "Save & apply settings": function () {
        $settings.hotkeys = [];
        $('#rapp-configureKeys tbody td.selColumn').each(function (index) {
          var value = '';
          if ($(this).is('.colCustom')) {
            value = $(this).find('input').val();
          }
          else {
            value = $(this).text();
          }
          $settings.hotkeys.push(value);
        });
        updateSettings("cookies");
        updateKeyShortcuts();
        $configureKeysDialog.dialog("close");
      },
      "Cancel": function () {
        $configureKeysDialog.dialog("close");
      }
    }
  });

  $("input[type='button']#configureKeys").click(function ($event) {
    //$event.preventDefault();
    $("#rapp-configureKeys table").remove();

    if ($settings.hotkeys.length != hotkeysDescription.length) {
      $settings.hotkeys = hotkeysPreset1;
    }

    $("#rapp-configureKeys").append('<table><thead><tr><th class="colDescription">Description</th><th class="colPreset1">Preset #1</th><th class="colPreset2">Preset #2</th><th class="colCustom">Custom</th></tr></thead><tbody></tbody></table>');
    for (i = 0; i < hotkeysDescription.length; i++) {
      $("#rapp-configureKeys tbody").append('<tr><td class="colDescription">' + hotkeysDescription[i] + '</td><td class="colPreset1">' + hotkeysPreset1[i] + '</td><td class="colPreset2">' + hotkeysPreset2[i] + '</td><td class="colCustom"><input type="text" id="hotkey' + i + '" value="' + ($settings.hotkeys.length > i ? $settings.hotkeys[i] : '') + '" /></td></tr>');
    }
    var stringCustom = JSON.stringify($settings.hotkeys);
    var stringPreset1 = JSON.stringify(hotkeysPreset1);
    var stringPreset2 = JSON.stringify(hotkeysPreset2)
    if (stringCustom == stringPreset1) {
      $("#rapp-configureKeys .colPreset1").addClass('selColumn');
    }
    else {
      if (stringCustom == stringPreset2) {
        $("#rapp-configureKeys .colPreset2").addClass('selColumn');
      }
      else {
        $("#rapp-configureKeys .colCustom").addClass('selColumn');
      }
    }

    $("#rapp-configureKeys").find('.colPreset1,.colPreset2,.colCustom,input').click(function ($event) {
      $event.preventDefault();
      $('.selColumn').removeClass('selColumn');
      if ($(this).is('.colPreset1')) {
        $("#rapp-configureKeys").find('.colPreset1').addClass('selColumn');
      }
      if ($(this).is('.colPreset2')) {
        $("#rapp-configureKeys").find('.colPreset2').addClass('selColumn');
      }
      if ($(this).is('.colCustom')) {
        $("#rapp-configureKeys").find('.colCustom').addClass('selColumn');
      }
    });
    $configureKeysDialog.dialog("open");
  });

  // ---------------------------------------------------------------------------------------

  // --------- Add server time display to top panel ----------------------------------------
  updateDisplayOfServerTime();
  // ---------------------------------------------------------------------------------------

}

// Initialize dashboard
function initDashboard() {
  // --------- Add GM Documents iFrame -----------------------------------------------------
  updateGmDocsDisplay();
  // ---------------------------------------------------------------------------------------
  //ziep
  updateMentorDocsDisplay();
  //---------------------------------------------------------------------------------------
}

// Initialize ticket view
function initTicketView() {

  // --------- Get reported player name & ID -----------------------------------------------
  var $ticketHeader = $("h1.page-title").text().trim();
  $reportedPlayerName = $ticketHeader.substring(0, $ticketHeader.indexOf(" ")).trim();
  $reportedPlayerId = $ticketHeader.substring($ticketHeader.indexOf("ID: ") + 4, $ticketHeader.length);
  // ---------------------------------------------------------------------------------------

  // --------- Get active ticket ID --------------------------------------------------------
  var $ticketURL = window.location.href;
  var $activeTicketID = window.location.href.substring(window.location.href.lastIndexOf('/') + 1);
  if ($('#ticketContent .portlet-title:contains("Ticket view")').length) {
    $activeTicketID = $('#ticketContent .portlet-title:contains("Ticket view")').text().trim().substring(12, 19);
  }
  // ---------------------------------------------------------------------------------------

  // --------- Add new menu item - Report Throwaway Account Link ---------------------------
  var $throwawayURL = "https://docs.google.com/forms/d/e/1FAIpQLSfkxBuu5vMBynxXmBOlcywJTmz3xYaL2PnIMzXlRnnAeBPiWg/viewform";
  var $throwawayFields = "?entry." + $throwawayFieldGM + "=" + $gmName + "&entry." + $throwawayFieldReported + "=" + $reportedPlayerName;
  var $newMenuItemReportThrowaway = "<li class='rapp-menuItem' id='rapp-throwaway_item'><a id='throwaway_link' target='_blank' href='" + $throwawayURL + $throwawayFields + "'><i class='icon-trash'></i><span class='title'>Report Throwaway Account</span></a></li>";

  $menu.append($newMenuItemReportThrowaway);

  $("#throwaway_link").click(function ($event) {
    var $link = $(this).attr("href").concat("&entry." + $throwawayFieldTicket + "=" + $activeTicketID);
    if ($link.length > 0) {
      GM_openInTab($link);
    }
    $event.preventDefault();
  });
  // ---------------------------------------------------------------------------------------

  // --------- Reformat 'Open tickets' panel -----------------------------------------------
  var $openTicketsHeader = $("div.portlet-title:contains('Open tickets')");
  var $openTickets = $openTicketsHeader.parent().find('.portlet-body');
  var $decisionsMadeHeader = $("div.portlet-title:contains('Decisions made')");
  var $decisionsMade = $decisionsMadeHeader.parent().find('.portlet-body');
  //$('.col-sm-1').remove();
  $openTickets.closest('.col-lg-5').css('width', '49.0%');
  $openTickets.closest('.col-lg-5').css('padding-left', '0');
  $openTickets.closest('.col-lg-5').css('padding-right', '0');
  $decisionsMade.closest('.col-lg-6').css('width', '49.0%');
  $decisionsMade.closest('.col-lg-6').css('padding-left', '8');
  $decisionsMade.closest('.col-lg-6').css('padding-right', '0');
  var $matchNames = $openTickets.find("strong:contains('Match ID')");
  $matchNames.wrap("<div class='matchTitle' />");
  $matchNames.parent().each(function (i) {
    var $matchElements = $(this).nextUntil("hr").addBack();
    $matchElements.wrapAll("<div class='matchDiv' />");
  });
  $('.matchDiv').next("hr").remove();
  $('.matchDiv .col-sm-1').remove();
  $('.matchTitle + br').remove();

  // Dropdown menu to mark individual matches & cookies
  $('.matchTitle strong').each(function () {
    var $markedMatch = $(this).text().replace("Match ID: ", "").trim();
    var $markAs = "NA";
    if ($.cookie("rapp-pid" + $reportedPlayerId + "mid" + $markedMatch + "-mark")) {
      $markAs = $.cookie("rapp-pid" + $reportedPlayerId + "mid" + $markedMatch + "-mark");
    }
    var hasSomeButNotOnlyEzReports = ($(this).closest(".matchDiv").find("a:contains('Verbal abuse'),a:contains('Bad Nickname'),a:contains('Staff impersonation')").length) &&
      ($(this).closest(".matchDiv").find("a:contains('Verbal abuse'),a:contains('Bad Nickname'),a:contains('Staff impersonation')").length !== $(this).closest(".matchDiv").find('a:contains(" - P")').length);

    $(this).after("<div class='styled-select'><select class='matchStatus' >" +
      "<option " + ($markAs == 'NA' ? "selected='selected'" : "") + " value=''></option>" +
      "<option " + ($markAs == 'W' ? "selected='selected'" : "") + " value='W'>Warning</option>" +
      "<option " + ($markAs == 'I' ? "selected='selected'" : "") + " value='I'>Innocent</option>" +
      (hasSomeButNotOnlyEzReports ? ("<option " + ($markAs == 'IVA' ? "selected='selected'" : "") + " value='IVA'>I:Va/Bn/Si</option>") : "") +
      "<option " + ($markAs == 'B' ? "selected='selected'" : "") + " value='B'>Broken</option></select></div>");
    $(this).next(".styled-select").addClass((($markAs === "NA") ? "" : (($markAs == "I") ? "mSinnocent" : (($markAs == "W") ? "mSwarning" : (($markAs == "IVA") ? "mSeasyInno" : "mSbroken")))));
    toggleSubmitButtonDisplay($(this).next(".styled-select"));
    $(this).click(function ($event) {
      $event.preventDefault();
      GM_setClipboard($markedMatch);
    });
  });

  function toggleSubmitButtonDisplay($select) {
    if ($select.next('.rapp-singleTicketSubmit').length) {
      $select.next('.rapp-singleTicketSubmit').remove();
    }
    var val = $select.find("select option:selected").attr('value');
    if (val == "I" || val == "IVA") {
      $select.after("<a class='rapp-singleTicketSubmit" + (val == "IVA" ? " innoVA" : "") + "' href='#'><i class='icon-check'></i></a>");
      $select.next('.rapp-singleTicketSubmit').click(function ($event) {
        $event.preventDefault();
        innocentButton($(this))
      });
    }
  }

  $('.matchStatus').change(function () {
    var $markedMatch = $(this).closest('.matchDiv').find("strong:first").text().replace("Match ID: ", "").trim();
    $.cookie("rapp-pid" + $reportedPlayerId + "mid" + $markedMatch + "-mark", $(this).find("option:selected").attr("value"), {
      expires: 1,
      path: '/'
    });
    var val = $(this).find("option:selected").attr('value');
    $(this).parent().removeClass("mSinnocent");
    $(this).parent().removeClass("mSwarning");
    $(this).parent().removeClass("mSbroken");
    $(this).parent().removeClass("mSeasyInno");
    $(this).parent().addClass((val === "") ? "" : ((val == "I") ? "mSinnocent" : ((val == "W") ? "mSwarning" : (val == "IVA") ? "mSeasyInno" : "mSbroken")));
    toggleSubmitButtonDisplay($(this).parent());
  });

  // --------- Replace chatlog analyser with dialog & update links -------------------------
  $('a:contains("Chatlog analyser")').addClass("rapp-chaLink");

  $('#chatContent').before("<div id='chatlogDialog'></div>");
  $('#chatContent').remove();

  // <Mark all the chatlog analyser links with rapp-chaLink class>
  $('a:contains("Chatlog analyser")').each(function (i) {
    $(this).prevAll(".matchTitle").first().append("<a href='javascript:void(0);' onclick=" + $(this).attr("onclick") + " class='rapp-chaLink'>Chatlog Analysis</a>");
    $(this).remove();
  });
  $('a:contains("Chatlog analyser")').each(function (i) {
    $(this).prevAll(".matchTitle").first().append("<a href='javascript:void(0);' onclick=" + $(this).attr("onclick") + " class='rapp-chaLink'>ca</a>");
    $(this).remove();
  });

  // <Mark all the active report links with rapp-reportLink class>
  $('.matchDiv a:not([class^="rapp"])').addClass('rapp-reportLink');

  $('.rapp-reportLink').each(function (i) {
    $(this).text($(this).text().replace("Priority:  ", "P:"));
  });

  $('a.rapp-chaLink').click(function (event) {
    $("body").css("cursor", "progress");
    // Show chatlog analyser popup
    showChatlogAnalyzer($(this).attr("onclick").substring($(this).attr("onclick").indexOf("http"), $(this).attr("onclick").indexOf("')")), "#chatlogDialog", "Chatlog analysis for " + $(this).prevAll("strong").first().text());
    // Switch the ticket view to first report of analysed match, if analysed match is not currently active
    if ($(this).parent(".matchTitle strong").text() != ($(".rapp-activeMatch").find("strong").text())) {
      rappGetTicketAjax($(this).parent(".matchTitle").parent(".matchDiv").find("a.rapp-reportLink:first"));
    }
  });

  $('a.rapp-reportLink').click(function (event) {
    event.preventDefault();
    $activeTicketID = $(this).text().substring(0, $(this).text().indexOf(" - ")).trim();
    rappGetTicketAjax($(this));
  });
  // Addd cyrillic chatlog
  var $matchInfo = $("a:contains('Download replay')")[0].href.replace('.honreplay', '').split('replays/')[1],
    $cyrillicLink = "http://honportal.adr.com.ua/test.php?name=" + $reportedPlayerName + "&link=" + $matchInfo,
    $cyrillicLogButton = '<a href="' + $cyrillicLink + '"target="_blank" class="rapp-chaLink cyrillic">Cyrillic Chatlog</a>'
  $('.rapp-chaLink:not(.cyrillic)').after($cyrillicLogButton);

  //ziep

  // ---------------------------------------------------------------------------------------

  // --------- Update ticket view of pre-loaded tickets based on settings ------------------

  updateCurrentTicket();

  // ---------------------------------------------------------------------------------------

  // --------- Load report game time and description ---------------------------------------

  updateReportDetails();
  updateViewSelection();

  // ---------------------------------------------------------------------------------------

  // --------- Check prior decisions and update priors indicator ---------------------------

  // ---------------------------------------------------------------------------------------

  // Close ticket button for each match
  $('.matchTitle').prepend("<div class='rapp-closeTicket'><i class='icon-close'></i></div>");
  $('.rapp-closeTicket').click(function (event) {
    event.preventDefault();
    closeMatch($(this).closest(".matchDiv"));
  });

  // --------- Highlight active report & match  --------------------------------------------
  $(".rapp-reportLink:contains('" + $activeTicketID + "'):first").parent().addClass("rapp-activeMatch");
  $(".rapp-reportLink:contains('" + $activeTicketID + "'):first").addClass("rapp-activeReport");
  // ---------------------------------------------------------------------------------------

  $('.portlet-title:contains("Open tickets")').parent().attr('id', 'rapp-openTickets');
  $('.portlet-title:contains("Decisions made")').parent().attr('id', 'rapp-decisionsMade');

  //Add position to allow scrolling of hidden matches to view
  $('#rapp-openTickets .portlet-body').css('position', 'relative');

  updateDecisionsDisplay(null);

  $(window).resize(function ($event) {
    adjustOpenTicketColumns(false);
  });
  $('a:contains("Request all replays")').attr('id', 'rapp-requestAllReplays');
  $('#rapp-openTickets div:first').append($('#rapp-requestAllReplays'));
  $('#rapp-requestAllReplays').prepend('<i class="icon-cloud-download"></i>')
  $('#rapp-openTickets div.portlet-body').css("padding-top", "0");
  $('#rapp-openTickets div.portlet-body br:first').remove();

  // Report nickname button
  $('h1').append('<a id="rapp-reportBn" href="#">Report Bad Nickname</a>');
  $('#rapp-reportBn').click(function ($event) {
    $event.preventDefault();
    GM_setClipboard($reportedPlayerName);
    GM_openInTab($reportBnURL);
  });

  // Check whether there are queued decisions
  // - Initial check
  var handlingGm = checkForQueuedDecisions($('body'));
  if (handlingGm.length) {
    alert(handlingGm.join(' & ') + ' made decisions on this case recently and might be working on it! Contact them to avoid double work.');
  }

  // Check whether player is muted or suspended
  var $suspensionMessage = $('.alert-danger:contains("This account is currently suspended")');
  if ($suspensionMessage.length) {
    // Get latest guilty prior

    var $latestGuilty = $('#rapp-decisionsMade p');
    var isMuted = false;
    for (i = 0; i < $latestGuilty.length; i++) {
      var priorText = $latestGuilty.eq(i).text();
      var judgement = priorText.substring(priorText.indexOf('|') + 1, priorText.lastIndexOf('|'));
      // Can not use only 'judged on' time, between 'suspension' and 'mute' there is a bit of a space
      var judgedOn = priorText.substring(priorText.indexOf('judged on') + 10, priorText.indexOf('|')).trim();
      var judgedOn_moment = moment(judgedOn, "YYYY-MM-DD HH:mm:ss");
      // So we have to get 'Currently suspended till' note from any ticket visible in portal
      // However, this show ends of suspension separately for 'suspension' and for 'mute', while calling both 'suspension'... Cool!
      var suspendedTill = $('span:contains("Currently suspended till ")').text().substring(25);
      var suspendedTill_moment = moment(suspendedTill, "YYYY-MM-DD HH:mm:ss");
      var duration = priorText.substring(priorText.lastIndexOf('|') + 1, priorText.lastIndexOf('\n')).trim();
      if ((judgement.indexOf(' Guilty\n') > -1) &&
        (suspendedTill_moment.isValid())) {
        if ((judgement.indexOf('for Verbal abuse') > -1) &&
          (duration.indexOf('mute') > -1)) {
          if (duration.indexOf('suspension') < 0) {
            // Account is just muted, without any suspension
            isMuted = true;
          }
          else {
            var suspensionDuration = duration.substring(0, duration.indexOf(' suspension')).trim();
            var muteDuration = duration.substring(duration.indexOf('then ') + 5, duration.indexOf('mute')).trim();
            var sD = suspensionDuration.split('-');
            var mD = muteDuration.split('-');
            var server_moment = moment(new Date(Date.parse(new Date()) - Date.parse($timeZoneDifference)));
            // Testing for that cool thing described above - is this 'suspended till' for 'suspension', or for 'mute'?
            var suspensionExpiry_moment = moment(suspendedTill_moment).subtract(sD[0], sD[1] + 's');
            var dayAfterJudgement_moment = moment(judgedOn_moment).add(1, "days");
            if (suspensionExpiry_moment > dayAfterJudgement_moment) {
              // 'Currently suspended till' refers to 'mute', not to 'suspension', so let's recalculate the expiration of suspension.
              suspensionExpiry_moment = moment(suspendedTill_moment).subtract(mD[0], mD[1] + 's');
              if (suspensionExpiry_moment < server_moment) {
                isMuted = true;
              }
            }
            else {
              console.log('VA guilty, but still suspended');
            }
            console.log(server_moment.format("YYYY-MM-DD HH:mm:ss"));
            console.log(suspensionExpiry_moment.format("YYYY-MM-DD HH:mm:ss"));
          }
        }
        break;
      }
    }

    if (isMuted) {
      $suspensionMessage.html($suspensionMessage.html().split('suspended').join('serving <b>mute</b> part of Verbal abuse suspension. You are free to Guilty or Warn for non-chat related offenses'));
    }
  }

}
// ===========================================================================================

// ======== Other functions ==================================================================

function isSoloInnocent($reportLink) {
  return soloInnocentCategories.some(category => $reportLink.text().includes(category));
}

// Remove report from the page (not close/innocent on the server!)
// Innocenting and closing should be evnetually rewrote to use this but fuck if I'm not getting cunfused by all this mess
function removeReportFor($reportLink, type) {
  //<-v- Collect data -v->
  var $matchDiv = $reportLink.closest('.matchDiv');
  var $openMatchDivs = $("div.portlet-title:contains('Open tickets')").parent().find(".matchDiv");
  var lastMatchLeft = ($openMatchDivs.length == 1);
  var removeMatchDiv = false;
  var soloInnocentReportSelector = '.rapp-reportLink:contains(' + soloInnocentCategories.join('),.rapp-reportLink:contains(') + ')';

  if (type == "innocent") {
    var isSoloInnocentReport = isSoloInnocent($reportLink);
    removeMatchDiv = (isSoloInnocentReport && ($matchDiv.find('.rapp-reportLink').length == 1)) || !isSoloInnocentReport;
  }
  if (type == "close") {
    removeMatchDiv = ($matchDiv.find('.rapp-reportLink').length == 1);
  }
  console.log('Removal of matchDiv? ' + removeMatchDiv);

  var $newMatchDiv = null;
  var $newReportLink = null;

  var changeActiveReportLink = ($reportLink.is('.rapp-activeReport') || ($matchDiv.is('.rapp-activeMatch') && removeMatchDiv)) && !(lastMatchLeft && removeMatchDiv);

  console.log('Change active link? ' + changeActiveReportLink);
  if (changeActiveReportLink) {
    if (!removeMatchDiv) {
      var $matchReportLinks = $matchDiv.find('.rapp-reportLink');
      var index = $matchReportLinks.index($reportLink);
      if (index == ($matchReportLinks.length - 1)) {
        index--;
      }
      $newReportLink = $matchReportLinks.not($reportLink).eq(index);
      $newMatchDiv = $matchDiv;
    }
    else {
      var index = $openMatchDivs.index($matchDiv);
      if (index == ($openMatchDivs.length - 1)) {
        index--;
      }
      $newMatchDiv = $openMatchDivs.not($matchDiv).eq(index);
      $newReportLink = $newMatchDiv.find('a.rapp-reportLink').first();
    }
  }
  //<-^- Collect data -^->
  //ziep

  //<-v- Get rid of the elements -v->
  if (removeMatchDiv) {
    // If this is the only match, disable ticket view
    if (lastMatchLeft) {
      $('h1').first().after('<div class="alert alert-success"><ul><li>No more reports for this player!</li></ul></div>')
      $("#ticketContent").remove();
    }
    $matchDiv.remove();
  }
  if (!(lastMatchLeft && removeMatchDiv)) {

    // Remove report & details
    var $reportDetails = $reportLink.nextUntil("a.rapp-reportLink");
    $reportDetails.remove();
    $reportLink.prev('i.rapp-closeReport').remove();
    $reportLink.remove();

    // Update match status options
    if ($matchDiv.find('option:selected').val() == 'IVA') {
      if (!$matchDiv.find(soloInnocentReportSelector).length || ($matchDiv.find(soloInnocentReportSelector).length == $matchDiv.find('.rapp-reportLink').length)) {
        $matchDiv.find('option:selected').remove();
        $matchDiv.find('select').val('');
        $matchDiv.find('select').trigger('change');
      }
    }

    // Switch to another report
    if (changeActiveReportLink) {
      console.log('clickiiing on ' + $newReportLink); /// doenst select match
      $newReportLink.trigger("click");
    }
  }
  //<-^- Get rid of the elements -^->
}

function checkForQueuedDecisions($source) {
  var $priorsDiv = $source.find('div.portlet-title').find('div.caption:contains("Decisions made")').closest('div.portlet').find('div.portlet-body');
  var $ps = $priorsDiv.find('p');
  var result = [];
  $ps.each(function (i) {
    var $p = $(this);
    if ($p.find('strong span:contains("queued")').length) {
      var $handlingGm = $p.text().trim().substring($p.text().trim().lastIndexOf('(') + 1, $p.text().trim().lastIndexOf(')')).trim();
      console.log($handlingGm);
      if ($handlingGm != $gmName) {
        console.log(' not you!');
        result.push($handlingGm);
      }
    }
  });
  return result;
}

function updateAfterReportsRemoval() {
  if ($(".rapp-reportLink:contains('Bad Nickname')").length == 0) {
    $("#rapp-innoAllBn").remove();
  }
  updateReportDetails();
  updateDecisionsDisplay($lastRequestResponse);
}

function innocentSingleReport($reportLink) {
  if (isSoloInnocent($reportLink)) {
    var dialogText = "Verbal Abuse/Bad Nickname/Staff Impersonation reports listed below for " + $reportLink.closest('.matchDiv').find('.matchTitle strong').text() + " will be marked Innocent (1 decision towards quota).";
    var wait = "Please wait while the decision is being submitted and confirmed by server, it takes a while";
    $("body").append('<div id="rapp-innoTicketDialog" style="display:none">  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>' + dialogText + '</p><ul></ul>' +
      '<p class="wait hidden"><div class="dec-circle"><div></div></div>' + wait + '(<span class="inprogress">0</span>/<span class="total">1</span>)</p></div>');
    $("#rapp-innoTicketDialog ul").append("<li>" + $reportLink.text() + "</li>");

    $("#rapp-innoTicketDialog").dialog({
      resizable: false,
      height: "auto",
      width: 450,
      modal: true,
      close: function (event, ui) {
        $('#rapp-innoTicketDialog').remove();
      },
      title: "Innocent decision",
      buttons: {
        "Confirm": function () {
          // Disable buttons until finished
          $('#rapp-innoTicketDialog').next().find('.ui-dialog-buttonset .ui-button').prop('disabled', true);
          rappInnocentTicketAjax($reportLink);
          $('#rapp-innoTicketDialog .wait').removeClass('hidden');
          var finished = setInterval(function () {
            if (requestsDone == 1) {
              clearInterval(finished);
              requestsDone = 0;
              removeReportFor($reportLink, "innocent");
              updateAfterReportsRemoval();
              $("#rapp-innoTicketDialog").dialog("close");
            }
          }, 200);
        },
        Cancel: function () {
          result = false;
          $(this).dialog("close");
        }
      }
    });
  }
  else {
    innocentButton($reportLink);
  }
}

function innocentButton($button) {
  var innoAllBn = null;
  var onlyInnoEz = null;
  var $matchDiv = null;
  var singleInno = false;
  if ($button.is('.rapp-reportLink')) {
    innoAllBn = false;
    onlyInnoEz = false;
    singleInno = $('.rapp-reportLink').data('single');
    $matchDiv = $button.closest(".matchDiv");
  }
  else {
    innoAllBn = $button.is('#rapp-innoAllBn');
    onlyInnoEz = innoAllBn ? true : $button.hasClass("innoVA");
    $matchDiv = innoAllBn ? $('#rapp-openTickets') : $button.closest(".matchDiv");
  }
  var $matchReports = $matchDiv.find(".rapp-reportLink");
  var $ezMatchReports = $matchDiv.find(innoAllBn ? ".rapp-reportLink:contains('Bad Nickname')" : ".rapp-reportLink:contains('Verbal abuse'),.rapp-reportLink:contains('Bad Nickname'),.rapp-reportLink:contains('Staff impersonation')");
  if (singleInno && ($button.text().includes('Bad Nickname') || $button.text().includes('Verbal abuse') || $button.text().includes('Staff impersonation'))) {
    $matchReports = $button;
    onlyInnoEz = true;
    $ezMatchReports = $button;
  }
  var ezReportsCount = $ezMatchReports.length;

  var dialogText = "";
  var $activeMatch = "";
  var $activeReport = "";
  var changeActiveMatch = false;
  var closeMatch = true;
  var changeActiveReport = false;
  var innocentReports;

  var totalDecisions = 0;

  if (onlyInnoEz) {
    totalDecisions = ezReportsCount;
    if (innoAllBn) {
      dialogText = "All opened Bad Nickname reports (listed below) for " + $reportedPlayerName + " will be marked Innocent (" + ((totalDecisions > 1) ? (totalDecisions + " separate decisions") : "1 decision") + " towards quota).";
    }
    else {
      dialogText = "Verbal Abuse/Bad Nickname/Staff Impersonation reports listed below for " + $matchDiv.find('.matchTitle strong').text() + " will be marked Innocent (" + ((totalDecisions > 1) ? (totalDecisions + " separate decisions") : "1 decision") + " towards quota).";
    }
    innocentReports = $ezMatchReports;
    if (isReporLinkInSelection($('.rapp-activeReport'), innocentReports)) {
      $activeReport = $matchReports.filter('a:contains("Ability or item abuse"),a:contains("Avoiding AFK detection"),a:contains("Feeding")').first();
      changeActiveReport = true;
    }
    closeMatch = false;
  }
  else {
    dialogText = $matchDiv.find('.matchTitle strong').text() + " will be marked Innocent"
    if (ezReportsCount > 0 && (ezReportsCount !== $matchReports.length)) {
      totalDecisions = ezReportsCount + 1;
      dialogText += ". In addition, following Verbal Abuse/Bad Nickname/Staff Impersonation reports will be marked Innocent (in total " + totalDecisions + " separate decisions towards quota):";
      innocentReports = $ezMatchReports;
      innocentReports = innocentReports.add($matchReports.filter('a:contains("Ability or item abuse"),a:contains("Avoiding AFK detection"),a:contains("Feeding")').first());
    }
    if (ezReportsCount > 0 && (ezReportsCount == $matchReports.length)) {
      totalDecisions = ezReportsCount;
      dialogText += " by closing following Verbal Abuse/Bad Nickname/Staff Impersonation reports as Innocent (in total " + (totalDecisions) + " separate decisions towards quota):";
      innocentReports = $ezMatchReports;
    }
    if (ezReportsCount === 0) {
      totalDecisions = 1;
      dialogText += " (1 decision towards quota).";
      innocentReports = $matchReports.first();
    }
    if (sameMatchDiv($('.rapp-activeMatch'), $matchDiv)) {
      changeActiveMatch = true;
      changeActiveReport = true;
      var index = $('.matchDiv').index($matchDiv);
      if (index == ($('.matchDiv').length - 1)) {
        index--;
      }
      $activeMatch = $('.matchDiv').not($matchDiv).eq(index);
      $activeReport = $activeMatch.find('a.rapp-reportLink').first();
    }
  }
  var disclaimer = "Performing this action without finishing the entire ticket is considered Ticket skipping and is being investigated during spotchecks. If you already know you do not have time for watching replays, leave the 'easy tickets' (Bad Nickname, Verbal Abuse, Staff Impersonation) to the GM who ";
  var wait = "Please wait while the decisions are being submitted and confirmed by server, it takes a while";
  $("body").append('<div id="rapp-innoTicketDialog" style="display:none">  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>' + dialogText + '</p><ul></ul>' + (innoAllBn ? ('<p class="disclaimer">' + disclaimer + '</p>') : '') +
    '<p class="wait hidden"><div class="dec-circle"><div></div></div>' + wait + '(<span class="inprogress">0</span>/<span class="total">' + totalDecisions + '</span>)</p></div>');
  if (ezReportsCount > 0) {
    $ezMatchReports.each(function () {
      $("#rapp-innoTicketDialog ul").append("<li>" + $(this).text() + "</li>");
    });
  }

  $("#rapp-innoTicketDialog").dialog({
    resizable: false,
    height: "auto",
    width: 450,
    modal: true,
    close: function (event, ui) {
      $('#rapp-innoTicketDialog').remove();
    },
    title: (innoAllBn ? "Innocent all Bad Nickname tickets" : "Innocent decision"),
    buttons: {
      "Confirm": function () {
        // Disable buttons until finished
        $('#rapp-innoTicketDialog').next().find('.ui-dialog-buttonset .ui-button').prop('disabled', true);
        innocentReports.filter("a:contains('Verbal abuse'),a:contains('Bad Nickname'),a:contains('Staff impersonation')").each(function (i) {
          rappInnocentTicketAjax($(this));
        })
        innocentReports.filter('a:contains("Ability or item abuse"),a:contains("Avoiding AFK detection"),a:contains("Feeding")').each(function (i) {
          rappInnocentTicketAjax($(this));
        })
        $('#rapp-innoTicketDialog .wait').removeClass('hidden');
        var finished = setInterval(function () {
          if ($('#rapp-innoTicketDialog .wait .total').text() == requestsDone) {
            clearInterval(finished);
            requestsDone = 0;
            if (closeMatch) {
              // If this is the only match, disable ticket view
              if ($("div.portlet-title:contains('Open tickets')").parent().find(".matchDiv").length == 1) {
                $('h1').first().after('<div class="alert alert-success"><ul><li>No more reports for this player!</li></ul></div>');
                // Close match or report
                $matchDiv.remove();
                adjustOpenTicketColumns(true);
                $("#ticketContent").remove();
              }
              else {
                // Close match or report
                $matchDiv.remove();
                adjustOpenTicketColumns(true);
                // Switch to another match or report
                if (changeActiveReport) {
                  $activeReport.trigger("click");
                }
                if ($(".rapp-reportLink:contains('Bad Nickname')").length == 0) {
                  $("#rapp-innoAllBn").remove();
                }
              }
              updateReportDetails();
              updateDecisionsDisplay($lastRequestResponse);
              $("#rapp-innoTicketDialog").dialog("close");

            }
            else {
              innocentReports.each(function (i) {
                removeReport($(this));
              });
              if (innoAllBn) {
                // Remove all matches which contain no reports
                $('.matchDiv').addClass('removeForBeingWithoutReports');
                $('.matchDiv .rapp-reportLink').closest('.matchDiv').removeClass('removeForBeingWithoutReports');
                $('.removeForBeingWithoutReports').remove();

                // If this is the only match, disable ticket view
                if ($("div.portlet-title:contains('Open tickets')").parent().find(".matchDiv").length == 0) {
                  $('h4').first().after('<div class="alert alert-success"><ul><li>No more reports for this player!</li></ul></div>');
                  $("#ticketContent").addClass('hidden');
                }

                // Remove options for innocenting ez tikcets if they no longer apply
                $('.matchDiv option[value="IVA"]').each(function (i) {
                  var $ivaOption = $(this);
                  var $mDiv = $ivaOption.closest('.matchDiv');
                  if ($mDiv.find(".rapp-reportLink:contains('Verbal abuse'),.rapp-reportLink:contains('Bad Nickname'),.rapp-reportLink:contains('Staff impersonation')").length == 0) {
                    $ivaOption.remove();
                    $ivaOption.closest('select').val('');
                  }
                });
                adjustOpenTicketColumns(true);
                $('#rapp-innoAllBn').remove();
              }
              else {
                $matchDiv.find('option:selected').remove();
                $matchDiv.find('select').val('');
                $matchDiv.find('select').trigger('change');
              }
              // Switch to another match or report
              if (changeActiveReport) {
                $activeReport.trigger("click");
              }
              if ($(".rapp-reportLink:contains('Bad Nickname')").length == 0) {
                $("#rapp-innoAllBn").remove();
              }
              updateReportDetails();
              updateDecisionsDisplay($lastRequestResponse);
              $("#rapp-innoTicketDialog").dialog("close");
            }
          }
        }, 200);
      },
      Cancel: function () {
        result = false;
        $(this).dialog("close");
      }
    }
  });
}

function adjustOpenTicketColumns(removed) {
  var totalHeight = 0;
  $('.matchDiv').each(function (index) {
    totalHeight += $(this).outerHeight();
    $(this).data("heightFromTop", totalHeight);
  })

  if (($("#rapp-openTickets").outerWidth() < 1022) || removed) {
    if ($(".rapp-column-left").length && $(".rapp-column-right").length) {
      var cnt = $(".rapp-column-left").contents();
      $(".rapp-column-left").replaceWith(cnt);
      cnt = $(".rapp-column-right").contents();
      $(".rapp-column-right").replaceWith(cnt);
    }
  }

  if ($("#rapp-openTickets").outerWidth() >= 1022) {
    if (!$(".rapp-column-left").length && !$(".rapp-column-right").length) {
      var columnsDone = false;
      $('.matchDiv').each(function (index) {
        if (!columnsDone) {
          if ($(this).data("heightFromTop") > (totalHeight / 2)) {
            columnsDone = true;
            $(this).prevAll('.matchDiv').wrapAll('<div class="rapp-column-left">');
            $(this).nextAll('.matchDiv').wrapAll('<div class="rapp-column-right">');
            if (index === 0) {
              $(this).wrap('<div class="rapp-column-left">');
            }
            else {
              $('.rapp-column-left').append(this);
            }
          }
        }
      });

    }
  }
}

function getTicketUrl(onclickAttr) {
  return onclickAttr.substring(onclickAttr.indexOf("http"), onclickAttr.indexOf("')"));
}

function sameMatchDiv($matchDiv1, $matchDiv2) {
  return $matchDiv1.find('.matchTitle strong').text() == $matchDiv2.find('.matchTitle strong').text();
}

function getReportLinkId($reportLink) {
  return $reportLink.text().substring(0, $reportLink.text().indexOf(' - ')).trim();
}

function isReporLinkInSelection($reportLink, $selection) {
  var id = getReportLinkId($reportLink);
  var result = false;
  $selection.each(function (i) {
    if (getReportLinkId($(this)) == id) {
      result = true;
    }
  });
  return result;
}

function removeReport($reportLink) {
  var remove = $reportLink.nextUntil("a.rapp-reportLink");
  remove.remove();
  $reportLink.prev('i.rapp-closeReport').remove();
  $reportLink.remove();
}

function showPriorsIndicator($container, $source) {
  var $priorsIndicator = "<div class='priors-indicator'>Checking priors... <div class='dec-circle'><div></div></div></div>";
  $container.append($priorsIndicator);

  var $priors = checkPriors($source);
  var $priorsIndicatorTable = "<span class='prior-desc'>Priors</span><div class='prior-any'><br>" +
    ($priors.priorAnything > 0 ? "<span class='rapp-hover'><i class='glyphicon'>&#xe209;</i></span>" :
      "<i class='glyphicon'>&#xe014;</i>") +
    "<span class='rapp-title'>'anything' prior: " + $priors.priorAnything + "</span></div>";

  $(".priors-indicator").html($priorsIndicatorTable);
  if ($priors.priorAnything > 0) {
    $(".prior-any").addClass("rapp-prior");
  }
  else {
    $(".prior-any").addClass("rapp-noprior");
  }

  updateTooltips();
}

function preventDoubleSubmit() {
  $('form').on('submit', function (e) {
    var $form = $(this);
    if ($form.data('submitted') === true) {
      e.preventDefault();
    }
    else {
      $form.data('submitted', true);
      $('#btnGuilty').addClass('disabled');
      $('#btnWarning').addClass('disabled');
      $('#btnInnocent').addClass('disabled');
      $('#btnClose').addClass('disabled');
    }
  });
}

function updateReportDetails() {
  $('.matchDiv .rapp-reportLink').each(function (i) {
    var link = this;
    var $onclick = $(this).attr("onclick");
    var $url = $onclick.substring($onclick.indexOf("https:"), $onclick.indexOf("')"));
    $.ajax({
      url: $url,
      dataType: 'html',
      type: 'GET',
      success: function (data) {
        var $gameTime = "";
        var $description = "";
        var $viewers = "";
        var $chatlogUrl = "";

        var text = $(data).find('div.portlet-title:contains("Viewers")').text();
        var viewers = text.substring(text.indexOf('Viewers: ') + 9).trim().split(', ');
        viewers.forEach(function (viewer) {
          if (viewer != $gmName) {
            $viewers += viewer + ",";
          }
        });
        $viewers = $viewers.substring(0, $viewers.length - 1);
        $chatlogUrl = $(data).find('a[href*="chat.php"]').attr("href");
        $gameTime = $(data).find('td:contains("Game time:")').next().next().text().trim();
        $description = $(data).find('td:contains("Description:")').next().next().text().trim();

        $(link).next(".rapp-ticketGameTime").remove();
        $(link).next("br").next(".rapp-ticketViewers").remove();
        $(link).next("br").next(".rapp-ticketDescription").remove();
        $(link).closest('.matchDiv').find('.matchTitle .rapp-chatlogLink').remove();

        if ($description !== "") {
          $(link).next("br").after("<div class='rapp-ticketDescription'>" + $description + "</div>");
        }
        if ($viewers !== "") {
          $(link).next("br").after("<div class='rapp-ticketViewers'>Ticket viewed by: " + $viewers + "</div>");
        }
        if ($gameTime !== "") {
          $(link).after("<div class='rapp-ticketGameTime'>" + $gameTime + "</div>");
        }
        if ($chatlogUrl !== "") {
          if (!$(link).closest('.matchDiv').find('.matchTitle .rapp-chatlogLink').length) {
            if ($settings.chatlogExtendedCompatibility == "on") {
              $chatlogUrl = $chatlogUrl + "&items=off&apm=off";
            }
            $(link).closest('.matchDiv').find('.matchTitle').append('<a class="rapp-chatlogLink" href=' + $chatlogUrl + '>Chatlog</a>');
            $(link).closest('.matchDiv').find('.matchTitle .rapp-chatlogLink').click(function ($event) {
              $event.preventDefault();
              var $link = $(this).attr("href");
              if ($link.length > 0) {
                GM_openInTab($link);
              }
            });
          }
        }
      }

    });
  });
}

function updateDecisionsDisplay($source) {
  if ($activeView == "ticket") {
    $('.priors-indicator').remove();
    showPriorsIndicator($('#rapp-' + (($settings.hidePastDecisions == "on") ? 'openTickets' : 'decisionsMade') + ' div.portlet-title:first'), $source);
    if ($settings.hidePastDecisions == "on" && !$('#rapp-openTickets').hasClass('maximized')) {
      $('#rapp-openTickets').parent().css("width", "100%");
      $('#rapp-decisionsMade').parent().addClass('hidden');
      $('#rapp-openTickets').addClass('maximized');
    }

    if ($settings.hidePastDecisions == "on" && !$('#rapp-showDecisionsMade').length) {
      $('.prior-desc').after("<i id='rapp-showDecisionsMade' class='glyphicon'>&#xe003;</i>");
      var $priorDecisionsDialog;
      $('body').append('<div id="rapp-decisionsMadeDialog"></div>');
      var $decisionsMadeDiv = $('#rapp-decisionsMadeDialog');
      $decisionsMadeDiv.html($(".portlet-title:contains('Decisions made')").next('div').html());
      if ($decisionsMadeDiv.text().trim() === "") {
        $decisionsMadeDiv.html("No decisions");
        $priorDecisionsDialog = $decisionsMadeDiv.dialog({
          resizable: false,
          height: "auto",
          autoOpen: false,
          width: 200,
          modal: true,
          title: "Decisions made"
        });
      }
      else {
        $priorDecisionsDialog = $decisionsMadeDiv.dialog({
          resizable: false,
          autoOpen: false,
          height: 400,
          width: 650,
          modal: true,
          title: "Decisions made"
        });
      }

      $('#rapp-showDecisionsMade').click(function ($event) {
        $event.preventDefault();
        $priorDecisionsDialog.dialog("open");
      });
    }

    if ($settings.hidePastDecisions == "off" && $('#rapp-openTickets').hasClass('maximized')) {
      $('#rapp-openTickets').parent().css("width", "50%");
      $('#rapp-decisionsMade').parent().removeClass('hidden');
      $('#rapp-openTickets').removeClass('maximized');
      $('#rapp-showDecisionsMade').remove();
      $('#rapp-decisionsMadeDialog').remove();
    }
    adjustOpenTicketColumns(false);
  }
}

function updateCurrentTicket() {
  if ($activeView == "ticket") {
    $('#ticketContent td a:eq(1)').addClass("rapp-chatlogLink");
    if ($('.rapp-chatlogLink').length) {
      if ($settings.chatlogExtendedCompatibility == "on" && !$('.rapp-chatlogLink').attr("href").includes("&items=on&apm=on")) {
        $('.rapp-chatlogLink').attr("href", ($('.rapp-chatlogLink').attr("href") + "&items=on&apm=on"));
        if (!$('#updateVerification').length) {
          $('body').append("<div id='updateVerification'></div>");
        }
      }
      if ($settings.chatlogExtendedCompatibility == "off" && $('.rapp-chatlogLink').attr("href").includes("&items=on&apm=on")) {
        $('.rapp-chatlogLink').attr("href", ($('.rapp-chatlogLink').attr("href").replace("&items=on&apm=on", "")));
      }
    }

    if ($settings.closeIndividualReports == "off" && $('.rapp-closeReport').length) {
      $('.rapp-closeReport').remove();
      $('.rapp-reportLink').removeClass('closable');
    }
    if ($settings.closeIndividualReports == "on" && $('.rapp-reportLink').length) {
      $('.rapp-reportLink').addClass('closable');

      // Close ticket button for each report
      $('span.rapp-closeReport').remove();
      $('a.rapp-reportLink').before("<span class='rapp-closeReport'><i class='icon-close'></i></span>");
      $('.rapp-closeReport').click(function (event) {
        event.preventDefault();
        closeReport($(this).next(".rapp-reportLink"));
      });
    }
  }
}

function confirmDecision(decision) {
  var categoryValue = $('select[name="category"]').val();
  var category = $('option[value=' + categoryValue + ']').text().trim();
  var description = $('#ticketDesc').val();
  var matchId = $('.rapp-activeMatch').find('.matchTitle strong').text().substring(10);

  $('#rapp-confirmDecision').remove();
  $("body").append('<div id="rapp-confirmDecision" style="display:none">  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 12px 0 0;"></span>' +
    'Confirm action:</br>' +
    'Player: <b>' + $reportedPlayerName + '</b></br>' +
    'Match ID: <b>' + matchId + '</b></br>' +
    '<b style="color:' + (decision == "Guilty" ? "red" : "orange") + ';">' + decision + ' (' + category + ')</b></br>' +
    '<p>Description: <pre>' + description + '</pre>');
  $("#rapp-confirmDecision").dialog({
    resizable: false,
    height: "auto",
    width: 600,
    modal: true,
    title: "Confirm decision",
    buttons: {
      "Submit": function () {
        $('#rapp-confirmDecision').parent().find(":button").prop("disabled", true).addClass("ui-state-disabled");
        $('#btn' + decision).trigger('click');
      },
      Cancel: function () {
        result = false;
        $(this).dialog("close");
        $('#rapp-confirmDecision').remove();
      }
    }
  });
  $("#rapp-confirmDecision").dialog('option', 'position', 'center');
}

function closeMatch($closeMatchDiv) {
  var $closeMatchReports = $closeMatchDiv.find(".rapp-reportLink");
  $('#rapp-closeTicketDialog').remove();
  $("body").append('<div id="rapp-closeTicketDialog" style="display:none">  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>Following tickets for ' + $closeMatchDiv.find('.matchTitle strong').text() + ' will be permanently closed and can not be reopened. Are you sure?</p><ul></ul></div>');
  $closeMatchReports.each(function () {
    $("#rapp-closeTicketDialog ul").append("<li>" + $(this).text().substring(0, $(this).text().indexOf(' - ')) + "</li>");
  });

  $("#rapp-closeTicketDialog").dialog({
    resizable: false,
    height: "auto",
    width: 400,
    modal: true,
    title: "Confirm closing of tickets",
    buttons: {
      "Close reports": function () {
        result = true;
        $(this).dialog("close");
        $('#rapp-closeTicketDialog').remove();
        // If this is the only match, disable ticket view
        if ($("div.portlet-title:contains('Open tickets')").parent().find(".matchDiv").length == 1) {
          $('h1').first().after('<div class="alert alert-success"><ul><li>All active tickets closed</li></ul></div>');

          // Actually close the tickets
          $closeMatchReports.each(function () {
            rappCloseTicketAjax($(this));
          });
          // Remove match from the view
          $closeMatchDiv.remove();
          adjustOpenTicketColumns(true);
          $("#ticketContent").remove();
        }
        // Otherwise switch to next available match
        else {
          if ($closeMatchDiv.hasClass("rapp-activeMatch")) {
            var index = $('.matchDiv').index($closeMatchDiv);
            if (index == ($('.matchDiv').length - 1)) {
              index--;
            }
            var $activeMatch = $('.matchDiv').not($closeMatchDiv).eq(index);
            var $activeReport = $activeMatch.find('a.rapp-reportLink').first();
            $activeReport.trigger("click");
          }
          // Actually close the tickets
          $closeMatchReports.each(function () {
            rappCloseTicketAjax($(this));
          });
          // Remove match from the view
          $closeMatchDiv.remove();
          adjustOpenTicketColumns(true);
        }

      },
      Cancel: function () {
        result = false;
        $(this).dialog("close");
        $('#rapp-closeTicketDialog').remove();
      }
    }
  });
}

function closeReport($reportLink) {
  var reportId = $reportLink.attr("onclick").substring($reportLink.attr("onclick").indexOf("ticket_id/") + 10, $reportLink.attr("onclick").indexOf("')"));
  $('#rapp-closeReportDialog').remove();
  $("body").append('<div id="rapp-closeReportDialog" style="display:none">  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>Report ' + reportId + ' will be permanently closed and can not be reopened. Are you sure?</p><ul></ul></div>');

  $("#rapp-closeReportDialog").dialog({
    resizable: false,
    height: "auto",
    width: 400,
    modal: true,
    title: "Confirm closing of ticket",
    buttons: {
      "Close report": function () {
        result = true;
        $(this).dialog("close");
        $('#rapp-closeReportDialog').remove();
        // If this is the only report, remove match and switch to another available.
        if (!$reportLink.siblings(".rapp-reportLink").length) {
          // If this was the only match, disable ticket view
          if ($("div.portlet-title:contains('Open tickets')").parent().find(".matchDiv").length == 1) {
            $('h1').first().after('<div class="alert alert-success"><ul><li>All active tickets closed</li></ul></div>');
            // Actually close the ticket
            rappCloseTicketAjax($reportLink);
            // Remove match from the view
            $reportLink.parent().remove();
            $("#ticketContent").remove();
          }
          // Otherwise switch to next available match if we are closing active match
          else {
            if ($reportLink.closest('.matchDiv').hasClass("rapp-activeMatch")) {
              var index = $('.matchDiv').index($reportLink.closest('.matchDiv'));
              if (index == ($('.matchDiv').length - 1)) {
                index--;
              }
              var $activeMatch = $('.matchDiv').not($reportLink.closest('.matchDiv')).eq(index);
              var $activeReport = $activeMatch.find('a.rapp-reportLink').first();
              $activeReport.trigger("click");
            }
            // Actually close the ticket
            rappCloseTicketAjax($reportLink);
            // Remove match from the view
            $reportLink.parent().remove();
          }
        }
        // Otherwise switch to next available report in the match if we are closing the active one
        else {
          if ($reportLink.hasClass("rapp-activeReport")) {
            if ($reportLink.next(".rapp-reportLink").length) {
              $reportLink.next(".rapp-reportLink").trigger("click");
            }
            else {
              $reportLink.prev(".rapp-reportLink").trigger("click");
            }
          }
          // Actually close the ticket
          rappCloseTicketAjax($reportLink);

          // Remove report from the view
          $reportLink.prev('.rapp-closeReport').remove();
          $reportLink.nextUntil('.rapp-closeReport').remove();
          $reportLink.prev('i.rapp-closeReport').remove();
          $reportLink.remove();
        }
      },
      Cancel: function () {
        result = false;
        $(this).dialog("close");
        $('#rapp-closeReportDialog').remove();
      }
    }
  });
}

function updateGmDocsDisplay() {
  if ($activeView == "dashboard") {
    var $docsHTML = '<div id="gm_docs_div" style="width: 100%; margin-bottom: 5px; margin-top: 15px;"><iframe frameborder="0" width="100%" height="600" src="' + $gmDocsURL + '"></iframe></div>';

    if (($settings.gmDocs == "on") && (!$("#gm_docs_div").length)) {
      $('div.page-content').append($docsHTML);

    }
    if (($settings.gmDocs == "off") && ($("#gm_docs_div").length)) {
      $("#gm_docs_div").remove();
    }
  }
}

//ziep
function updateZettings() {
  if (($settings.TSCalc == "on") && (!$("#TSCButton").length)) {
    TSCButton();
  };

}

function updateMentorDocsDisplay() {
  if ($activeView == "dashboard") {

    //ziep
    var $mentorDocsHTML = '<div id="mentor_docs_div" style="width: 100%; margin-bottom: 5px; margin-top: 15px;"><iframe frameborder="0" width="100%" height="600" src="' + $mentorDocsURL + '"></iframe></div>';
    if (($settings.mentorDocs == "on") && (!$("#mentor_docs_div").length)) {

      //ziep
      $('div.page-content').append($mentorDocsHTML);
    }
    if (($settings.mentorDocs == "off") && ($("#mentor_docs_div").length)) {
      $("#mentor_docs_div").remove();
    }
  }
}
//

function updateViewSelection() {
  if ($settings.showViewSelection == "on" && $('.nav-pills').hasClass('hidden')) {
    $('.nav-pills').removeClass('hidden');
  }
  if ($settings.showViewSelection == "off" && !$('.nav-pills').hasClass('hidden')) {
    $('.nav-pills').addClass('hidden');
  }
}

function updateDisplayOfServerTime() {
  if (($settings.displayServerTime == "on") && (!$("#rapp-serverTime").length)) {
    $('.top-menu .nav').prepend('<li id="rapp-serverTime"><span>Server time</span><br></li>');
    setInterval(function () {
      updateClock('#rapp-serverTime', '<span>Server time</span><br>');
    }, 1000);
  }
  if (($settings.displayServerTime == "off") && ($("#rapp-serverTime").length)) {
    $("#rapp-serverTime").remove();
  }
}

// Returns object containing decision IDs for 'Verbal abuse' and 'Everything else' recent prior guilty/warning. Returns 0 for respective type of prior if none is found.
function checkPriors($source) {
  var $result = {
    priorAnything: 0
  };
  var $source;
  var updateDisplay = false
  if ($source == null || $source == "") {
    $source = $("html");
  }
  else {
    updateDisplay = true;
  }
  var $9monthsAgo = new Date((new Date()).setMonth((new Date()).getMonth() - 9));
  var $decisionsMadePanel = $source.find(".portlet-title:contains('Decisions made')");
  var $priors = $decisionsMadePanel.parent().find("p");

  $priors.each(function (i) {

    var $priorDecision = {
      id: 0,
      verdict: "Innocnet",
      ticket: 0,
      judgedOn: 0,
      category: "",
    };

    $priorDecision.id = $(this).find("a:eq(0)").text().trim();
    var $priorDetails = $source.find("#decisionModal-" + $priorDecision.id + " .modal-body").text();
    $priorDecision.ticket = $priorDetails.substring($priorDetails.indexOf("Ticket id:") + 10, $priorDetails.indexOf("Match id:")).trim();
    $priorDecision.verdict = $(this).text().substring($(this).text().indexOf("|") + 1, $(this).text().lastIndexOf("(")).trim();
    var $priorTicketDetail = $(this).nextUntil("p").filter("a:contains('" + $priorDecision.ticket + "')").text();
    $priorDecision.category = $priorTicketDetail.substring($priorTicketDetail.indexOf(" - ") + 3).trim();
    $priorDecision.judgedOn = new Date($(this).text().substring(($(this).text().indexOf("judged on") + 10), ($(this).text().indexOf("|") - 1)).trim());

    //Add category of the decision to the description in Decisions Made
    if (($priorDecision.verdict !== "Innocent") && ($priorDecision.verdict !== "Undone")) {
      $(this).find("a:eq(1):not(:contains(' for '))").append("for " + $priorDecision.category);
    }

    //Check if the prior is more recent than 9 months
    if (($priorDecision.judgedOn > $9monthsAgo) && ($priorDecision.verdict !== "Innocent") && ($priorDecision.verdict !== "Undone") && ($priorDecision.category !== "Bad Nickname")) {
      if ($result.priorAnything === 0) {
        $result.priorAnything = $priorDecision.id;
      }

    }
  });
  if (updateDisplay) {
    $(".portlet-title:contains('Decisions made')").parent().find('.portlet-body').remove();
    $(".portlet-title:contains('Decisions made')").parent().append($decisionsMadePanel.parent().find('.portlet-body'));
  }
  return $result;
}

function updateCycleDecisions(gmNameString, cycleStartDateTime, timeZoneDifference, outputSelectorString) {
  $.ajax({
    url: 'https://rap.heroesofnewerth.com/gm/dashboard',
    success: function (data) {
      var $cycleCounter = $(data).find('small:contains("Cycle count:")');
      var cycleCount = $cycleCounter.text().substring($cycleCounter.text().indexOf(':') + 2).trim();

      var $cycleTicketsStatusIcons =
        (cycleCount > 29 ? "<i class='glyphicon' style='color:#53c653'>&#xe013;</i>" :
          (cycleCount > 15 ? "<i class='glyphicon' style='color:#ff9966'>&#xe014;</i>" :
            "<i class='glyphicon' style='color:#ff6666'>&#xe014;</i>")) +
        (cycleCount > 89 ? "<i class='glyphicon' style='color:#ffe066'>&#xe006;</i>" : "") +
        (cycleCount > 119 ? "<i class='glyphicon' style='color:#ff80bf'>&#xe102;</i>" : "");

      var $cycleAndDropdown = "<div id='rapp-statsDecisionsCycle'><span>Decisions this cycle</span><span class='cycleCount'><b>" + cycleCount + "</b>" + $cycleTicketsStatusIcons + "</span></div>" +
        "<div id='rapp-statsTable'><span id='decisions_stats'><div class='dec-circle'><div></div></div><span style='display:inline-block;margin:7px'>Fetching decisions...</span></span></div>";

      $(outputSelectorString).html($cycleAndDropdown);

      $('#rapp-statsDecisionsCycle').prepend("<i class='icon-arrow-down'></i> ");
      $('#rapp-statsTable').slideUp();
      $('#rapp-statsDecisionsCycle').click(function ($event) {
        $event.preventDefault();
        if ($('#rapp-statsDecisionsCycle i:first').hasClass('icon-arrow-down')) {
          updateDecisionsStats(gmNameString, cycleStartDateTime, timeZoneDifference, outputSelectorString);
          $('#rapp-statsDecisionsCycle i:first').removeClass('icon-arrow-down');
          $('#rapp-statsDecisionsCycle i:first').addClass('icon-arrow-up');
        }
        else {
          $('#rapp-statsDecisionsCycle i:first').removeClass('icon-arrow-up');
          $('#rapp-statsDecisionsCycle i:first').addClass('icon-arrow-down');
        }
        $('#rapp-statsTable').slideToggle();
      });
    }
  });
}

function updateDecisionsStats(gmNameString, cycleStartDateTime, timeZoneDifference, outputSelectorString) {
  // --------- Update decisions stats ------------------------------------------------------
  var $decisionStats = {
    innocent: 0,
    guilty: 0,
    warning: 0,
    ots: 0,
    lastOt: "0",
    sinceLastOt: 0,
    total: 0,
    cycle: 0
  };

  console.log('Requesting stats..');
  //Access filtered results from query
  $.ajax({
    url: 'https://rap.heroesofnewerth.com/gm/tickets/judged/data?columns%5B0%5D%5Bdata%5D=id&columns%5B0%5D%5Bname%5D=id&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=time&columns%5B1%5D%5Bname%5D=time&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=offenderAction&columns%5B2%5D%5Bname%5D=offenderAction&columns%5B2%5D%5Bsearchable%5D=false&columns%5B2%5D%5Borderable%5D=false&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=gmAction&columns%5B3%5D%5Bname%5D=gmAction&columns%5B3%5D%5Bsearchable%5D=false&columns%5B3%5D%5Borderable%5D=false&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=status&columns%5B4%5D%5Bname%5D=status&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=true&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=desc&search%5Bvalue%5D=&search%5Bregex%5D=false&search_filter=gm&search_query=' + gmNameString,
    success: function (data) {
      console.log('Stats fetched.');
      $decisions = data.data;
      $decisionStats.total = $decisions.length;
      $decisions.forEach(function ($decision) {
        var $decisionTime = new Date(Date.parse($decision.time) + Date.parse(timeZoneDifference));
        if ($decisionTime > cycleStartDateTime) {
          $decisionStats.cycle += 1;
        }
        if ($decision.status == "Undone") {
          if ($settings.ignoredOts[$decision.id] === undefined) {
            $settings.ignoredOts[$decision.id] = 'ot';
          }
          if ($settings.ignoredOts[$decision.id] == 'ot') {
            $decisionStats.sinceLastOt = 0;
            $decisionStats.ots += 1;
            $decisionStats.lastOt = $decisionTime.toISOString().slice(0, 10);
          }
          if ($settings.ignoredOts[$decision.id] == 'count') {
            $decisionStats.sinceLastOt += 1;
          }
        }
        else {
          $decisionStats.sinceLastOt += 1;
        }
        if ($decision.status == "Innocent") {
          $decisionStats.innocent += 1;
        }
        if ($decision.status == "Guilty") {
          $decisionStats.guilty += 1;
        }
        if ($decision.status == "Warning") {
          $decisionStats.warning += 1;
        }
      });

      var $statsTable =
        "<table id='rapp-statsTable'>" +
        "<tr><td class='statKey'>Total decisions</td><td class='statValue'>" + $decisionStats.total + "</td></tr>" +
        ($decisionStats.lastOt == "0" ? "" : ("<tr><td class='statKey'>Since <span class='rapp-hover'>last OT</span><span class='rapp-title'>" + $decisionStats.lastOt + "</span></td><td class='statValue'>" + $decisionStats.sinceLastOt + "</td></tr>")) +
        "<tr><td class='statKey'>Overturns</td><td class='statValue'>" + $decisionStats.ots + "</td></tr>" +
        "<tr><td class='statKey'>Guilty</td><td class='statValue'>" + $decisionStats.guilty + "</td></tr>" +
        "<tr><td class='statKey'>Warning</td><td class='statValue'>" + $decisionStats.warning + "</td></tr>" +
        "<tr><td class='statKey'>Innocent</td><td class='statValue'>" + $decisionStats.innocent + "</td></tr>" +
        "<tr><td>" +
        "</table>";
      $('#rapp-statsTable').html($statsTable);

      updateTooltips();
    }
  });
}

function rappGetTicketAjax(reportLink) {
  var error = false;
  try {
    var desc = document.getElementById("ticketDesc").value;
  }
  catch (err) {
    error = true;
  }
  $.ajax({
    url: getTicketUrl(reportLink.attr("onclick")),
    type: 'GET',
    success: function (data) {
      $('#ticketContent').html($(data));
      preventDoubleSubmit();
      $('#ticketContent td a:eq(1)').addClass("rapp-chatlogLink");
      // Mark active match in "Open tickets"
      $(".rapp-activeMatch").removeClass("rapp-activeMatch");
      $(".rapp-activeReport").removeClass("rapp-activeReport");
      reportLink.addClass("rapp-activeReport");
      reportLink.parent().addClass("rapp-activeMatch");
      // Add compatibility with Chatlog Extended if desired
      if ($settings.chatlogExtendedCompatibility == "on") {
        $('#ticketContent .rapp-chatlogLink').attr("href", ($('#ticketContent .rapp-chatlogLink').attr("href") + "&items=on&apm=on"));
        $('#updateVerification').trigger("click");
      }
      if (error == false) {
        document.getElementById("ticketDesc").value = desc;
      }
    }
  });
}

function rappCloseTicketAjax(reportLink) {

  console.log(reportLink);

  $.ajax({
    url: getTicketUrl(reportLink.attr("onclick")),
    type: 'GET',
    success: function (data) {
      $.post($(data).find("form").attr("action").trim(), "btnClose=Close+ticket&" + $(data).find("form").serialize());
    }
  });
}

function rappInnocentTicketAjax(reportLink) {
  var interval = setInterval(function () {
    if (readyForNextRequest) {
      readyForNextRequest = false;
      clearInterval(interval);

      $('#rapp-innoTicketDialog .wait .inprogress').html(requestsDone + 1);

      var error = false;
      var category = reportLink.text().substring(reportLink.text().indexOf(' - ') + 3, reportLink.text().lastIndexOf(' - '));
      var categoryValue = '';
      switch (category) {
        case 'Ability or item abuse':
          categoryValue = "ability_item_abuse";
          break;
        case 'Avoiding AFK detection':
          categoryValue = "afk";
          break;
        case 'Bad Nickname':
          categoryValue = "bad_nick";
          break;
        case 'Feeding':
          categoryValue = "feeding";
          break;
        case 'Staff impersonation':
          categoryValue = "staff_impersonation";
          break;
        case 'Verbal abuse':
          categoryValue = "verbal_abuse";
          break;
      }
      try {
        var desc = document.getElementById("ticketDesc").value;
      }
      catch (err) {
        error = true;
      }
      $.ajax({
        url: getTicketUrl(reportLink.attr("onclick")),
        type: 'GET',
        success: function (data) {
          var $html = $(data);
          $html.find("form").find('input[name="singleDecision"]').prop('checked', true);
          $html.find("form").find('select[name="category"]').val(categoryValue);
          $.post($html.find("form").attr("action").trim(), "btnInnocent=Innocent&" + $html.find("form").serialize()).done(function (data) {
            readyForNextRequest = true;
            requestsDone++;
            $lastRequestResponse = $(data);
          });
          if (error == false) {
            document.getElementById("ticketDesc").value = desc;
          }

        }
      });
    }
  }, 250, interval);
}

function showChatlogAnalyzer(url, output, title) {
  var $chatlogAnalyserDialog = $(output).dialog({
    autoOpen: false,
    height: 400,
    width: 500,
    modal: false,
    title: title
  });
  $.ajax({
    url: url,
    type: 'GET',
    success: function (data) {
      $(output).html($(data).find("div.portlet-body").html());
      $chatlogAnalyserDialog.dialog("open");
    }
  });
  addButton();
}

function updateTooltips() {
  $("span.rapp-hover").hover(
    function () {
      $(this).siblings(".rapp-title").css("visibility", "visible");
    },
    function () {
      $(this).siblings(".rapp-title").css("visibility", "hidden");
    }
  );
}

function updateKeyShortcuts() {
  $(document).unbind('keydown');

  if ($settings.hotkeys.length) {
    var error = false;
    $settings.hotkeys.forEach(function (key) {
      if (key === undefined || key.trim() == '') {
        error = true;
      }
    });
  }

  if ($settings.hotkeys.length != hotkeysDescription.length || error) {
    $settings.hotkeys = hotkeysPreset1;
  }

  keySet = $settings.hotkeys;
  if ($settings.keyShortcuts == "on") {

    //Requests all matches/replays/chatlogs
    $(document).bind('keydown', keySet[0], function () {
      $('#rapp-requestAllReplays').trigger('click');
    });
    //If match is selected

    //Request match/replay/chatlog for selected Match only
    $(document).bind('keydown', keySet[1], function () {
      if ($('.rapp-activeMatch').length) {
        $('#ticketContent a:contains("Request replay")').trigger('click');
      }
    });
    //Chatlog Analysis for selected match
    $(document).bind('keydown', keySet[2], function () {
      if ($('.rapp-activeMatch').length) {
        $('.rapp-activeMatch .rapp-chaLink').trigger('click');
      }
    });
    //Open Chat Log for selected match
    $(document).bind('keydown', keySet[3], function () {
      if ($('.rapp-activeMatch').length) {
        $('.rapp-activeMatch .rapp-chatlogLink').trigger('click');
      }
    });
    //Copy Match ID for selected match
    $(document).bind('keydown', keySet[4], function () {
      if ($('.rapp-activeMatch').length) {
        $('.rapp-activeMatch strong:contains("Match ID")').trigger('click');
      }
    });
    //Download replay for selected match
    $(document).bind('keydown', keySet[5], function () {
      if ($('.rapp-activeMatch').length) {
        var $link = $('#ticketContent a:contains("Download replay")').attr("href");
        if ($link.length > 0) {
          GM_openInTab($link);
        }
      }
    });

    //Jump one Ticket up/back
    $(document).bind('keydown', keySet[6], function () {
      if ($('.rapp-activeReport').length) {
        var currPos = $('.rapp-reportLink').index($('.rapp-activeReport'));
        var count = $('.rapp-reportLink').length - 1;
        var newPos = 0;
        if (currPos > 0) {
          newPos = currPos - 1
        }
        if (currPos != newPos) {
          $($('.rapp-reportLink').get(newPos)).trigger('click');
        }
      }
      else {
        if ($('.rapp-reportLink').length) {
          ('.rapp-reportLink').first().trigger('click');
        }
      }
      $('#rapp-openTickets .portlet-body').scrollTop($('#rapp-openTickets .portlet-body').scrollTop() + $('.rapp-activeMatch').position().top);
    });
    //Jump one Ticket down/forward
    $(document).bind('keydown', keySet[7], function () {
      if ($('.rapp-activeReport').length) {
        var currPos = $('.rapp-reportLink').index($('.rapp-activeReport'));
        var count = $('.rapp-reportLink').length - 1;
        var newPos = count;
        if (currPos < count) {
          newPos = currPos + 1
        }
        if (currPos != newPos) {
          $($('.rapp-reportLink').get(newPos)).trigger('click');
        }
      }
      else {
        if ($('.rapp-reportLink').length) {
          ('.rapp-reportLink').first().trigger('click');
        }
      }
      $('#rapp-openTickets .portlet-body').scrollTop($('#rapp-openTickets .portlet-body').scrollTop() + $('.rapp-activeMatch').position().top);
    });
    //Jump one Match up/back
    $(document).bind('keydown', keySet[8], function () {
      if ($('.rapp-activeReport').length) {
        var currPos = $('.matchDiv').index($('.rapp-activeMatch'));
        var count = $('.matchDiv').length - 1;
        var newPos = 0;
        if (currPos > 0) {
          newPos = currPos - 1
        }
        if (currPos != newPos) {
          $($('.matchDiv').get(newPos)).find('.rapp-reportLink:first').trigger('click');
        }
      }
      else {
        if ($('.rapp-reportLink').length) {
          ('.rapp-reportLink').first().trigger('click');
        }
      }
      $('#rapp-openTickets .portlet-body').scrollTop($('#rapp-openTickets .portlet-body').scrollTop() + $('.rapp-activeMatch').position().top);
    });
    //Jump one Match down/forward
    $(document).bind('keydown', keySet[9], function () {
      if ($('.rapp-activeReport').length) {
        var currPos = $('.matchDiv').index($('.rapp-activeMatch'));
        var count = $('.matchDiv').length - 1;
        var newPos = count;
        if (currPos < count) {
          newPos = currPos + 1
        }
        if (currPos != newPos) {
          $($('.matchDiv').get(newPos)).find('.rapp-reportLink:first').trigger('click');
        }
      }
      else {
        if ($('.rapp-reportLink').length) {
          ('.rapp-reportLink').first().trigger('click');
        }
      }
      $('#rapp-openTickets .portlet-body').scrollTop($('#rapp-openTickets .portlet-body').scrollTop() + $('.rapp-activeMatch').position().top);
    });

    //Single Innocent Decision
    $(document).bind('keydown', keySet[10], function () {
      if ($('.rapp-activeReport').length) {
        innocentSingleReport($('.rapp-activeReport'));
      }
    });

    //Innocent Whole Match
    $(document).bind('keydown', keySet[11], function () {
      if ($('.rapp-activeReport').length) {
        innocentButton($('.rapp-activeReport'));
      }
    });

    //Guilty Decision
    $(document).bind('keydown', keySet[12], function () {
      if ($('.rapp-activeReport').length) {
        confirmDecision("Guilty");
      }
    });

    //Warning Decision
    $(document).bind('keydown', keySet[13], function () {
      if ($('.rapp-activeReport').length) {
        confirmDecision("Warning");
      }
    });

    //Close currently viewed ticket
    $(document).bind('keydown', keySet[14], function () {
      if ($('.rapp-activeReport').length) {
        closeReport($('.rapp-activeReport'));
      }
    });

    //Close currently viewed match
    $(document).bind('keydown', keySet[15], function () {
      if ($('.rapp-activeReport').length) {
        closeMatch($('.rapp-activeReport').closest(".matchDiv"));
      }
    });

    //Report throw-away
    $(document).bind('keydown', keySet[16], function () {
      if ($('#throwaway_link').length) {
        $('#throwaway_link').trigger('click');
      }
    });

    //Priority Ticket Report
    $(document).bind('keydown', keySet[17], function () {
      if ($('#priority_ticket_link').length) {
        $('#priority_ticket_link').trigger('click');
      }
    });

    //Get Next Available Ticket
    $(document).bind('keydown', keySet[18], function () {
      if ($('a.nav-link:contains("Get next available ticket")').length) {
        $('a.nav-link:contains("Get next available ticket")').get(0).click();
      }
    });

    //Change category, up
    $(document).bind('keydown', keySet[19], function () {
      if ($('.rapp-activeReport').length) {
        var $select = $('select[name="category"]');
        var $option = $select.find('option:selected');
        if ($select.find('option').index($option) > 0) {
          $select.val($option.prev().val());
        }
      }
    });
    //Change category, down
    $(document).bind('keydown', keySet[20], function () {
      if ($('.rapp-activeReport').length) {
        var $select = $('select[name="category"]');
        var $option = $select.find('option:selected');
        if ($select.find('option').index($option) < $select.find('option').length - 1) {
          $select.val($option.next().val());
        }
      }
    });
  }
}

function updateClock(output, text) {
  var year = new Date().getFullYear();
  var currentTime = (new Date(Date.now() - 18000000)).toUTCString().replace("GMT", "").split(year + " ")[1];
  $(output).html(text + currentTime);
}

/* Read

https://css-tricks.com/use-button-element/
*/
//ziep
var keyCode = 13;
if ($settings.disableAlert == "on") {
  unsafeWindow.alert = function () {};
}
if ($settings.autoRequest == "on") {
  $('#ticketContent a:contains("Request replay")').trigger('click');
}

// ===========================================================================================
if ($settings.autoCopyMID == "on") {
  $('.rapp-activeMatch strong:contains("Match ID")').trigger('click');
}

$(function () {
  $timeCalcDialog = $("#gmPopupContainer").dialog({
    autoOpen: false,
    maxWidth: 1000,
    maxHeight: 1000,
    height: 760,
    width: 700,

  });
});

function TSCButton() {
  if ($settings.TSCalc == "on") {
    addButton("Timestamp Calc");
  }

  function addButton(text, onclick, cssObj) {
    cssObj = cssObj || {
      /*       position: "fixed",
            top: "680px",
            right: "200px", */
      "z-index": "999",
      fontWeight: "600",
      fontSize: "14px",
      cursor: "pointer",
      //backgroundColor: "#00cccc",
      color: "#0000FF",
      border: "none",
      padding: "10px 20px"
    };
    let button = document.createElement("a"),
      btnStyle = button.style;
    if ($('#ticketContent ').length) {

      document.querySelector("#ticketContent > div.row.top5 > div > div.portlet-body > div > div.col-lg-6.col-xs-6.col-sm-6 > table > thead > tr:nth-child(5) > td:nth-child(3)").innerHTML += " |";
      document.querySelector("#ticketContent > div.row.top5 > div > div.portlet-body > div > div.col-lg-6.col-xs-6.col-sm-6 > table > thead > tr:nth-child(5) > td:nth-child(3)").appendChild(button);
      button.innerHTML = text;
      button.id = "TSCButton";
    }
    // Settin function for button when it is clicked.

    button.onclick = selectReadFn;
    Object.keys(cssObj).forEach((key) => (btnStyle[key] = cssObj[key]));
    return button;
  }

  function selectReadFn() {
    var txt = document.getElementById("ember3822");
    // Just to show button is pressed
    $timeCalcDialog.dialog("open");

  }
};
TSCButton();

$("body").append('                                                          \
    <div id="gmPopupContainer" scrolling = "yes" class="gmPopupContainer"> \
<head><title>Timestamp Calculator</title>\
<p id="start" style="display: inline-block;">Start -----------------------------------------</p> <p id="finish" style="display: inline-block;">Finish</p>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input style="cursor: pointer;padding:2px;"type="button"id="resetButton"value="Reset">\
<br>\
1:   <input class="calc-elem tstart" type = "text" id = "tsOneOne" placeholder="mm ss">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="calc-elem tfinish" type = "text" id = "tsOneTwo" placeholder="mm ss"><br><br>\
2:   <input class="calc-elem tstart" type = "text" id = "tsTwoOne" placeholder="mm ss">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="calc-elem tfinish" type = "text" id = "tsTwoTwo" placeholder="mm ss"><br><br>\
3:   <input class="calc-elem tstart" type = "text" id = "tsThreeOne" placeholder="mm ss">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="calc-elem tfinish" type = "text" id = "tsThreeTwo" placeholder="mm ss"><br><br>\
4:   <input class="calc-elem tstart" type = "text" id = "tsFourOne" placeholder="mm ss">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="calc-elem tfinish" type = "text" id = "tsFourTwo" placeholder="mm ss"><br><br>\
5:   <input class="calc-elem tstart" type = "text" id = "tsFiveOne" placeholder="mm ss">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="calc-elem tfinish" type = "text" id = "tsFiveTwo" placeholder="mm ss"><br><br>\
6:   <input class="calc-elem tstart" type = "text" id = "tsSixOne" placeholder="mm ss">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="calc-elem tfinish" type = "text" id = "tsSixTwo" placeholder="mm ss"><br><br>\
7:   <input class="calc-elem tstart" type = "text" id = "tsSevenOne" placeholder="mm ss">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="calc-elem tfinish" type = "text" id = "tsSevenTwo" placeholder="mm ss"><br><br>\
8:   <input class="calc-elem tstart" type = "text" id = "tsEightOne" placeholder="mm ss">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="calc-elem tfinish" type = "text" id = "tsEightTwo" placeholder="mm ss"><br><br>\
9:   <input class="calc-elem tstart" type = "text" id = "tsNineOne" placeholder="mm ss">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="calc-elem tfinish" type = "text" id = "tsNineTwo" placeholder="mm ss"><br><br>\
10:<input class="calc-elem tstart" type = "text" id = "tsTenOne" placeholder="mm ss">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="calc-elem tfinish" type = "text" id = "tsTenTwo" placeholder="mm ss"><br><br>\
\
\
<input style="cursor: pointer;padding: 10px;" type="Button" id="calcButton" value="Calculate"><br><b style="display: inline-block;font-size: 2em; left: 0;">Result: </b><p class="calc-elem" id="result" style="font-size: 2em; display: inline-block;"></p>\
<b><p>Buttons for the description</p></b>\
<input class="btn btn-success"type="button"id="innoButton"value="Innocent">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="btn btn-danger"type="button"id="guiltyButton"value="Guilty">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp\
<input class="btn btn-warning"type="button"id="warningButton"value="Warning"></div>\
</div> \
');

function calculateTotalTime() {
  let times = [],
    times_for_desc = [],
    startInputs = document.getElementById("gmPopupContainer").querySelectorAll(".tstart"),
    finishInputs = document.getElementById("gmPopupContainer").querySelectorAll(".tfinish");
  let number = Math.min(startInputs.length, finishInputs.length);
  for (let i = 0; i < number; i++) {
    let start = startInputs[i].value,
      finish = finishInputs[i].value;
    if (start.length > 0 && finish.length > 0) {
      times_for_desc[i] = [start, finish];
      times[i] = calculateOneTime(start, finish);
    }
  }
  if (times.length > 0) {
    let totalSeconds = 0;
    for (let i = 0; i < times.length; i++) {
      totalSeconds += times[i][0] * 60 + times[i][1];
    }
    let fMinutes = Math.floor(totalSeconds / 60),
      fSeconds = totalSeconds - (fMinutes * 60);

    /* Let's check if they have priors */
    let priors = document.querySelectorAll(".rapp-prior");
    if (priors[0]) {
      if (fMinutes >= afk_warning) {
        guilty_for_afk = 1;
      }
    }
    else {
      if (fMinutes >= afk_warning) {
        warning_for_afk = 1;
      }
      if (fMinutes >= afk_guilty) {
        guilty_for_afk = 1;
      }
    }

    let reported_username = document.getElementsByClassName("page-title")[0].textContent.split(" ")[1].trim();
    document.getElementById("result").textContent = " " + fMinutes + "  min and " + fSeconds + " seconds";

    for (let i = 0; i < times_for_desc.length; i++) {
      times_for_desc[i] = times_for_desc[i][0].match(/([0-9]+)([^a-zA-Z0-9])([0-9]+)/)[1] + ":" + times_for_desc[i][0].match(/([0-9]+)([^a-zA-Z0-9])([0-9]+)/)[3] + " - " + times_for_desc[i][1].match(/([0-9]+)([^a-zA-Z0-9])([0-9]+)/)[1] + ":" + times_for_desc[i][1].match(/([0-9]+)([^a-zA-Z0-9])([0-9]+)/)[3];
    }
    $guilty_desc = reported_username + " is avoiding the afk detection at [" + times_for_desc.join(", ") + "].";
    $warning_desc = "Please refrain from avoiding the AFK detection, as seen at [" + times_for_desc.join(", ") + "].";
    $inno_desc = "Timestamps: [" + times_for_desc.join(", ") + "]. Total time: " + fMinutes + " min and " + fSeconds + " seconds";

  }
}

function warning() {
  document.getElementById("ticketDesc").value += $warning_desc;

}

function guilty() {
  document.getElementById("ticketDesc").value += $guilty_desc;

}

function innocent() {

  document.getElementById("ticketDesc").value += $inno_desc;
}

function calculateOneTime(start, finish) {
  start = start.match(/([0-9]+)([^a-zA-Z0-9])([0-9]+)/);
  finish = finish.match(/([0-9]+)([^a-zA-Z0-9])([0-9]+)/);
  var startDate = new Date(0, 0, 0, 0, start[1], start[3]);
  var finishDate = new Date(0, 0, 0, 0, finish[1], finish[3]);
  var diff = finishDate.getTime() - startDate.getTime();
  diff = diff / 1000; // get seconds
  let minutes = Math.floor(diff / 60);
  let seconds = diff - (minutes * 60);
  let time = [minutes, seconds];
  return time;
}

$("#calcButton").click(function () {
  //calc();
  calculateTotalTime();
});

$("#resetButton").click(function () {
  $(".calc-elem").val("");
  $('#pTest').text("")
});

$("#guiltyButton").click(function () {
  guilty();
});

$("#warningButton").click(function () {
  warning();
});
$("#innoButton").click(function () {
  innocent();
});
$(document).ready(function () {
  if (window.location.pathname.includes("ticket") && window.location.pathname.includes("user")) {
    $("a[class='rapp-chatlogLink']").attr("href", $("a[class='rapp-chatlogLink']").attr("href").replace("items=on&apm=on", "items=off&apm=off"))
    $("#ticketContent > div.row.top5 > div > div.portlet-body > div > div.col-lg-6.col-xs-6.col-sm-6 > table > thead > tr:nth-child(5) > td:nth-child(3) > a:nth-child(1)").attr(
      "href", $("#ticketContent > div.row.top5 > div > div.portlet-body > div > div.col-lg-6.col-xs-6.col-sm-6 > table > thead > tr:nth-child(5) > td:nth-child(3) > a:nth-child(1)").attr("href").replace("http", "https"));
  }

});