Hentai Heroes Helper (auto collect and button press)

Add in the Hentai Heroes game.

Od 06.06.2022.. Pogledajte najnovija verzija.

// ==UserScript==
// @name  Hentai Heroes Helper (auto collect and button press)
// @description Add in the Hentai Heroes game.
// @version     2.17.5
// @match       https://*.hentaiheroes.com/*
// @exclude     https://test.hentaiheroes.com/*
// @match       https://*.haremheroes.com/*
// @match       https://*.gayharem.com/*
// @match       https://*.comixharem.com/*
// @match       https://*.hornyheroes.com/*
// @match       https://*.pornstarharem.com/*
// @run-at      document-end
// @grant       none
// @license     MIT
// @author      Morryx
// @namespace   https://greasyfork.org/users/807892
// ==/UserScript==

// reload btn harem and stop
// fix: after redirect upgrade trigger left arrow market

// fix: scroll to correct position zoom
// generateSetting of input numbers (min_collect_exp / timeout collect)
// add auto click troll (scegli fino a quanti ticket avere ancora)
// leagues check list di chi attaccare, star icon on right
// when 3/3 the selected click the first star not first in list
// color orange nel caso di % in più non solo rosso
// se il prox champion è già finito vai di nuovo al prox
// probabile fix dato dal setting sul journey_champion ?
// confirm collect if values exceed, in path of valor, season
// Auto off sfw if range of day/hour
// remember leagues datas x 1gg ?
// maybe setting of autostart a activity?

// Search best item
// "rarity":"legendary",
//    no rare o epic
//    "level":"337", > actual - 2
//    se almeno 3 verdi non nascondere
//    "subtype":"5",
//    values
//       "carac1_equip":"2279",
//       "carac2_equip":"2328",
//       "carac3_equip":"2204",
//       "chance_equip":"3151.82",
//       "endurance_equip":"2338",
// count how many point can get selling all items (50xItems), meanwhile

// arrow troll tier
// $(".tiers-selection .tier").on("click", function() {
//   var tierNum = $(".tiers-selection .tier.selected").attr("tier");
//   var params = {
//       class: "Troll",
//       action: "set_favorite_tier",
//       id_troll: trollInfo.id_troll,
//       tier: tierNum
//   };
//   hh_ajax(params, function(data) { ... })
// })

// fix: if in leagues hidden is selected or 3/3 select first line
// add random select avatar / remove new skin notification
// auto collect if stackable items
// retest do auto story mode (check if changed bg before click again)
// check if can go to correct page contest
// guida completa

// possibili:
// can convert to animated waifu
// next amount? maybe calculate in harem
// salva lista log (message top right)
// a quali girl dare exp quali son le più utili?
// create team in base al colore da fare (4 + forti più prime colorate)
// check https://github.com/Roukys/HHauto/wiki/English
// Utile HHPNMap? data storage

// console.table(Hero);
is_numeric = function (c) {
  return /^\d+$/.test(c);
};
toint_string = function (str) {
  var new_str = '';
  if (str == '' || str == null) return 0;
  for (i = 0; i < str.length; i++) {
    var char = str.charAt(i);
    if (is_numeric(char)) new_str += char;
  }
  return +new_str;
};
toint_element = function ($el) {
  return toint_string($el.text().replace(/^\D+/g, ''));
};
addCss = function (code, append) {
  if (code !== '') add_css += '' + code;

  if (typeof append != 'undefined' && append) appendCss();
};
appendCss = function () {
  $('#customStyle').remove();
  if (add_css !== '')
    $body.append($('<style id="customStyle">' + add_css + '</style>'));
};
toCsv = function (objArray, separator = ',', eol = '\r\n') {
  var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
  var str = '';

  for (var i = 0; i < array.length; i++) {
    var line = '';
    for (var index in array[i]) {
      if (line !== '') line += separator;
      line += array[i][index];
    }
    str += line + eol;
  }

  return str;
};
random = function (max = 1, min = 0) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};
stopClick = function (e) {
  e.preventDefault();
  e.stopPropagation();
  return false;
};

// Settings
var storage_key = 'AutoCollect_Settings',
  default_settings = {
    auto_collect_harem: true,
    timeout_collect: 25,
    not_collect_full_graded: false,
    redirect_shop_not_full_graded: true,
    safe_work: false,
    pantheon_auto_enter: true,
    auto_press_btns: true,
    girls_data: false,
    girls_data_print: false,
    random_waifu: false,
    change_waifu_interval: 30,
    last_id_troll: 1,
    //last_bang_team: 1,
    last_side_quest: false,
    min_collect_exp: 10000,
    journey_champion_active: true,
    journey_champion: false,
    last_link_activity: false,
    last_link_shop: false,
    last_link_champion: false,
    colored_leagues: true,
    colored_season: true,
    //last_bang_team_active: false,
    last_links: true,
    back_to_link: true,
    header_link_show: true,
    confirm_exceed: true,
    leagues_scan_after: 5000,
    leagues_scan_after_long: 120000,
    max_days_club: 60,
    auto_assign_pop: true,
    exit_after_pop_assign: false,
    start_girl_story: false,
    retrive_home_timer: false,
    redirect_to_home: false,
    selected_mythic_book: true,
    leagues_data: [],
    always_first_leagues: false,
  },
  links = {
    'troll': '/troll-pre-battle.html?id_opponent=',
    'activity': '/activities.html?tab=',
    'shop': '/shop.html?type=',
  },
  NOT_FOUND = 'NOT_FOUND',
  unsafe_click = false;
save_settings = function (settings) {
  window.localStorage.setItem(storage_key, JSON.stringify(settings));
};
clear_settings = function () {
  window.localStorage.removeItem(storage_key);
};
get_settings = function () {
  var settings = window.localStorage.getItem(storage_key),
    default_settings_length = Object.keys(default_settings).length,
    last_added_settings = Object.keys(default_settings)[default_settings_length - 1],
    key = false;

  if (settings === null) settings = {};
  else settings = JSON.parse(settings);

  if (!settings.hasOwnProperty(last_added_settings) || default_settings_length != Object.keys(settings).length) {
    for (key in default_settings) {
      if (!settings.hasOwnProperty(key)) settings[key] = default_settings[key];
    }
  }

  for (key in settings) {
    if (!default_settings.hasOwnProperty(key)) delete settings[key];
  }

  save_settings(settings);
  return settings;
};
change_settings = function (key, value) {
  settings[key] = value;
  save_settings(settings);
};
generateSetting = function (setting, $el) {
  $setting = $('<label class="switchSetting">' +
    '  <input type="checkbox" setting="' + setting.name + '"' + (settings[setting.name] === true ? ' checked="checked"' : '') + '/>' +
    '  <span class="sliderSetting"></span>' +
    '</label>' +
    setting.text + '<br />');
  $setting
    .appendTo($el)
    .find('input').change(function () {
      var value = $(this).is(':checked');
      if (typeof setting.onchange != 'undefined') {
        setting.onchange(value);
        if (typeof setting.stopafterchange != 'undefined' && setting.stopafterchange)
          return;
      }
      change_settings($(this).attr('setting'), value);
    });
};

// Story functions
questLink = function () {
  $('#canvas_quest_energy .energy_counter_bar .bar-wrapper .over').wrap('<a href="' + Hero.infos.questing.current_url + '" style="width:100%;text-decoration:none;z-index:2"></a>');
  $('.energy_counter_amount, span[rel="count_txt"]').css('z-index', '1');
};
addBackToLink = function (link, to_selector = '#pre-battle') {
  if (settings.back_to_link)
    $('<a href="' + link + '" class="back-to">&lt;- BACK</a>').appendTo($(to_selector));
};
toggleSafeWork = function (selector) {
  change_settings('safe_work', !settings.safe_work);
  $(selector).toggleClass('safe-work');
};
unsafeWork = function () {
  $('.safe-work')
    .off('dblclick.unsafe')
    .on('dblclick.unsafe', function (e) {
      unsafe_click = true;
      $(this)
        .toggleClass('safe-work')
        .toggleClass('unsafe-work');
      return stopClick(e);
    });
};
safeWorkBackground = function (selector) {
  $(selector).css({
    'background-color': '#7c7c7c',
    'background-blend-mode': 'exclusion',
  });
};
getLastLink = function ($el, type) {
  var link = $el.attr('href');
  if (typeof link == 'undefined')
    link = $el.attr('data-href');
  if (typeof link != 'undefined' && link.includes(links[type]))
    return link.split(links[type])[1];
  return NOT_FOUND;
};
changeLastTroll = function () {
  var result = getLastLink($(this), 'troll');
  if (result == NOT_FOUND) return;
  change_settings('last_id_troll', toint_string(result));
};
trollMenuLink = function () {
  var $trollMenu = $('.TrollsMenu');
  if (!$trollMenu.length) {
    setTimeout(trollMenuLink, 200);
    return;
  }
  $trollMenu.find('a[href^="' + links.troll + '"]').click(changeLastTroll);
};
changeLastActivityLink = function () {
  var result = getLastLink($(this), 'activity');
  if (result == NOT_FOUND) return;
  change_settings('last_link_activity', result);
};
changeLastShopLink = function () {
  var result = getLastLink($(this), 'shop');
  if (result == NOT_FOUND)
    result = false;
  change_settings('last_link_shop', result);
};
shopMenuLink = function () {
  var $shopMenuLinks = $('a[rel="shop"] .market_menu');
  if (!$shopMenuLinks.length) {
    setTimeout(shopMenuLink, 200);
    return;
  }
  $shopMenuLinks.click(changeLastShopLink);
};
changeLastChampionLink = function () {
  change_settings('last_link_champion', $(this).attr('href'));
};
championMenuLink = function () {
  var $championMenuLinks = $('a[rel="sex-god-path"] .champions_menu');
  if (!$championMenuLinks.length) {
    setTimeout(championMenuLink, 200);
    return;
  }
  $championMenuLinks.click(changeLastChampionLink);
};
goToChampion = function (id_champion) {
  location.href = "/champions/" + id_champion;
};
journeyChampion = function (id_champion) {
  if (settings.journey_champion) {
    goToChampion(settings.journey_champion);
    change_settings('journey_champion', false);
  }
};
waifuSafeWork = function () {
  $('.waifu-girl-container img').addClass('safe-work');
  $('.diamond-bar .diamond').click(function () {
    setTimeout(waifuSafeWork, 200);
  });
};
generateImg = function (id, grade, src, type = 'girls') {
  if (typeof src != 'undefined')
    domain = src.split('hh-content.com')[0];
  else domain = 'https://hh.';
  filename = 'ava' + grade;
  if (type == 'trolls' && grade > 1)
    filename = 'ava1_t' + grade;
  return domain + 'hh-content.com/pictures/' + type + '/' + id + '/' + filename + '.png';
};
appendStory = function (selector, id) {
  var $waifuStory = $(selector + ' .waifuStory');
  if (!$waifuStory.length) {
    $waifuStory = $('<a class="waifuStory"><img src="https://hh.hh-content.com/design_v2/affstar.png"></a>');
    $waifuStory.appendTo($(selector));
  }
  $waifuStory
    .attr('href', '/harem/' + id)
    .click(function () {
      change_settings('start_girl_story', true);
    });
};
// Other plugins
fixDiamondImg = function () {
  setTimeout(function () {
    $('.diamond-bar .diamond:first-child').trigger('mouseenter');
  }, 500);
};

var settings = get_settings(),
  theme_colors = {
    green: '#53af00',
    red: '#b14',
    gray: '#6a6a6a',
    shadow_gray: '0 3px 0 rgb(23 33 7 / 60%), inset 0 3px 0 #3c3c3c',
  },
  add_css = '',
  $body = false;
$(function () {
  $body = $('body[page]');
  var page = $body.attr('page');
  // console.log(page);
  var page_interact = false;
  $('#contains_all').click(function (e) { page_interact = true; });

  if (settings.redirect_to_home) {
    change_settings('redirect_to_home', false);
    setTimeout(function () {
      if ((page_interact && page != 'pachinko') || page == 'club_champion') return;

      if (page == 'pachinko' && $('.blue_button_L[free="1"]').length)
        return;

      if (page == 'activities' && (
        $('.blue_button_L:not([disabled]):visible').length ||
        $('.purple_button_L:visible').length
      ))
        return;

      location.href = '/home.html';
    }, 2000);
  }

  if (page == 'harem') {
    var girls = null,
      interval_collect = false,
      can_collect = true,
      $girl_list = $('.girls_list'),
      start_from = 0,
      girls_data = [];

    restart_collect = function () {
      can_collect = true;
      start_from = 0;
      collect();
    };
    collect = function () {
      clearInterval(interval_collect);
      interval_collect = setInterval(restart_collect, 120000);
      $girl_list.bind('DOMNodeInserted', function () {
        if (!can_collect) return;

        can_collect = false;
        collect();
      });
      girls = $('div.girls_list>div[id_girl]>div[girl]:not(.not_owned)');
      collect_girl(start_from);
    };
    collect_girl = function (i) {
      if (i >= girls.length) return;

      var $girl = $(girls[i]),
        after = 0,
        skip_girl = false,
        $stars = $girl.find('.graded g');

      girls_data.push({
        'name': $girl.find('h4').text(),
        'id': +$girl.attr("girl"),
        'rarity': $girl.find('.left').attr("rarity"),
        'domination': $girl.find('.domination-toggle').attr("generic-tooltip"),
        'level': toint_element($girl.find('.lvl span:nth-child(2)')),
        'grade': $stars.length
      });

      $girl.click(function () {
        setTimeout(function () {
          $('.diamond-bar .diamond.selected').trigger('mouseenter');
        }, 500);
      });

      if (settings.not_collect_full_graded) {
        // if ($girl.find('h4').text() == 'Donatella')
        //   console.log('debug girl name');
        var class_attr = $stars.last().attr('class');
        class_count = 0;
        if (typeof class_attr != 'undefined')
          class_count = class_attr.split(/\s+/).length;
        skip_girl = (
          class_count > 0 ||
          $girl.find('.can_upgrade').length
        );
      }

      if (!$girl.find('.salary.loads').length && !skip_girl) {
        $girl.trigger('click');
        after = settings.timeout_collect;
      }

      // Commented to let work girls_data / add again if girls data is valid in same day or option not set
      // var total_salary = toint_element(
      //   $('#collect_all span[rel="next_salary"]')
      // );
      if (i === girls.length - 1) {
        $girl_list.scrollTop($girl_list.prop('scrollHeight') - 300);
        if (!$girl.parent().next().find('div[girl]').hasClass('not_owned'))
          can_collect = true;
        else {
          console.clear();
          console.table(girls_data);
          change_settings('girls_data', girls_data);
          if (settings.girls_data_print)
            console.log(toCsv([{
              'name': 'Name',
              'id': 'Id',
              'rarity': 'Rarity',
              'domination': 'Domination',
              'level': 'Level',
              'grade': 'Grade'
            },
            ...girls_data
            ]));
          // maybe better do not click last girl, expecially for next run
          // $girl.trigger('click');
        }
      } else
        setTimeout(function () {
          start_from = i;
          collect_girl(i + 1);
        }, after);
    };
    is_cheat_click = function (e) {
      return false;
    };

    var total_salary = toint_element(
      $('#collect_all span[rel="next_salary"]')
    );
    if (settings.auto_collect_harem && !settings.start_girl_story &&
      !(!total_salary && settings.girls_data.length)) {
      collect();
      $('select').change(restart_collect);
    }

    // SFW
    retrive_img = function () {
      return (
        'https://hh.hh-content.com/' +
        (settings.safe_work ?
          'design/menu/ic_eyeopen.svg' :
          'quest/ic_eyeclosed.svg')
      );
    };
    var harem_right = '#harem_whole #harem_right',
      $btnSafeWork = $('<img class="view" src="' + retrive_img() + '">'),
      addSafeWork = function () {
        if (settings.safe_work)
          $(harem_right).find('.avatar-box').addClass('safe-work');
      };
    $(harem_right).append($btnSafeWork).bind('DOMNodeInserted', function () {
      addSafeWork();
      var $avatar = $('.avatar');
      $avatar.attr('src', $avatar.attr('src').replace('avb', 'ava'));

      $('.big_border .g_infos')
        .off('contextmenu.girlpreview')
        .on('contextmenu.girlpreview', function (e) {
          $(this).parent().find('img').trigger('contextmenu');
          return stopClick(e);
        });
    });
    $btnSafeWork.click(function () {
      toggleSafeWork(harem_right + ' .avatar-box');
      $(this).attr('src', retrive_img());
    });
    addSafeWork();

    if (settings.start_girl_story) {
      change_settings('start_girl_story', false);
      $a = $('.girl_quests').first().find('a');
      if ($a.length)
        location.href = $a.attr('href');
    }

    $girl_list.bind('DOMNodeInserted', function () {
      $('#harem_left div.girls_list.grid_view div[girl]>.right')
        .off('contextmenu.girlpreview')
        .on('contextmenu.girlpreview', function (e) {
          $(this).parent().find('.left img').trigger('contextmenu');
          return stopClick(e);
        });
    });

    addCss(
      harem_right +
      '{position: relative}' +
      harem_right +
      ' img.view{' +
      '  width: 25px;' +
      '  position: absolute;' +
      '  bottom: 20px;' +
      '  left: -10px;' +
      '  cursor: pointer;' +
      '  z-index: 9;' +
      '}' +
      '.variation_block>.big_border>.variation_girl>.g_infos{z-index: 999}'
    );
  } else if (page == 'quest') {
    if (settings.safe_work) {
      var scene_selector = '#scene #background';
      $(scene_selector).addClass('safe-work');
      $('#temp-background').dblclick(function () {
        $(scene_selector).trigger('dblclick');
      });
      $('#scene .eye').click(function () {
        toggleSafeWork(scene_selector);
      });
    }

    if (settings.not_collect_full_graded)
      $('button[rel="next"]').click(function () {
        setTimeout(function () {
          var to = '/harem.html';
          if (settings.redirect_shop_not_full_graded)
            to = '/shop.html?type=gift';
          location.href = to;
        }, 1000);
      });
  } else if (page == 'season_arena') {
    if (settings.colored_season) {
      var css_hero = '#season-arena .battle_hero .hero_stats_row',
        hero_power = toint_element($(css_hero + ':first-child>div:first-child')),
        hero_crown = toint_element($(css_hero + ':nth-child(2)>div:first-child')),
        opponent_index = 0;
      $('.opponents_arena .season_arena_opponent_container').each(function () {
        var $opponent_power = $(this).find(
          '.hero_stats_row:first-child>div:first-child'
        ),
          opponent_power = toint_element($opponent_power),
          $opponent_crown = $(this).find(
            '.hero_stats_row:nth-child(2)>div:first-child'
          ),
          opponent_crown = toint_element($opponent_crown),
          result_power = hero_power >= opponent_power,
          result_crown = hero_crown >= opponent_crown;
        // anche arancione se nel 2.2% circa
        $opponent_power.css(
          'color',
          result_power ? theme_colors.green : theme_colors.red
        );
        $opponent_crown.css(
          'color',
          result_crown ? theme_colors.green : theme_colors.red
        );
        if (!result_power || !result_crown)
          $('.opponents_arena .opponent_perform_button_container')
            .eq(opponent_index)
            .find('button')
            .css({
              background: theme_colors.gray,
              'box-shadow': theme_colors.shadow_gray,
              '-webkit-box-shadow': theme_colors.shadow_gray,
            });
        opponent_index++;
      });
    }

    questLink();
  } else if (page == 'shop') {
    var $girl_title = $('#girls_list h3'),
      last_girl_name = '',
      interval_try = false;
    awakening_view = function () {
      var girl_name = $girl_title.clone().children().remove().end().text();
      if (last_girl_name == girl_name) return;

      last_girl_name = girl_name;
      clearInterval(interval_try);
      interval_try = setInterval(function () {
        var girl_awakening = $('#girls_list img.icon').attr('hh_title'),
          $btn_awakening = $('#inventory .blue_text_button');
        if (girl_awakening != undefined) {
          var selector_book = ':not(.mythic)';
          if (settings.selected_mythic_book)
            selector_book = '';
          $('#inventory .selected .inventory_slots .slot:not(.empty)' + selector_book).last().trigger('click');
          var split_awakening = girl_awakening.split(':'),
            split_awakening_values = split_awakening[1].split('/'),
            total_awakening = toint_string(split_awakening_values[1]),
            required_awakening = toint_string(split_awakening_values[0]),
            color = 'inherit',
            cant_awake = required_awakening < total_awakening,
            full_exp_bar = $btn_awakening
              .find('span[rel="girl"] span span')
              .hasClass('hudAwaken_mix_icn');
          $btn_awakening.attr('disabled', cant_awake && full_exp_bar);
          if (cant_awake) color = theme_colors.red;
          $girl_title.html(
            girl_name +
            '<span style="color:' +
            color +
            '">' +
            girl_awakening +
            '</span>'
          );
          clearInterval(interval_try);
        }
      }, 200);
    };

    $girl_title.bind('DOMNodeInserted', awakening_view);
    awakening_view();

    setInterval(function () {
      $('.CustomStats').text('');
    }, 25);

    // First item to buy
    selectFirstToBuy = function () {
      $('#shop .selected .slot:not(.mythic):not(.empty)').first().trigger('click');
      page_interact = false;
    };
    $('#type_item>div').click(function (e) {
      change_settings('last_link_shop', $(this).attr('type'));
      setTimeout(selectFirstToBuy, 1000);
      return stopClick(e);
    });
    setTimeout(selectFirstToBuy, 1000);

    // Next girl when full xp
    var timeoutXp = false;
    $('.blue_text_button.inventory-tab').click(function () {
      clearTimeout(timeoutXp);
      timeoutXp = setTimeout(function () {
        if ($('.hudAwaken_mix_icn').length)
          $('#shops #girls_list .g1 span[nav][nav=right]').trigger('click');
      }, 1000);
    });

    // Clear filter
    var $btnClearFilter = $('<input type="button" class="blue_button_L" value="Clear filter" style="width:100%;height:36px;padding-top:5px;">');
    $('#arena_filter_box').append($btnClearFilter);
    $btnClearFilter.click(function () {
      $('#arena_filter_box .form-control').each(function () {
        $(this).find('input').val('');
        $(this).find('select').val('all');
      });
      $('#arena_filter_box .form-control input').first().trigger('input');
    });

    addCss(
      '#girls_list h3{' +
      '  display: flex;' +
      '  justify-content: center;' +
      '  flex-wrap: wrap;' +
      '  line-height: 20px;' +
      '}' +
      '#girls_list h3 span{' +
      '  width: 100%;' +
      '  font-size: 12px;' +
      '}' +
      '#type_item .text{' +
      '  font-size: 10px;' +
      '}' +
      '#hideText{text-shadow: 0 0 3px #057}' +
      '#hideSellButton{left: 39px!important}' +
      '#arena_filter_box{width: 218px!important}'
    );
  } else if (page == 'leaderboard') {
    var opponents_list = '.lead_table table tbody tr:not(.personal_highlight):not(.cached):visible',
      $opponents_list = false,
      stop_simulation = false,
      simulationTimeout = false,
      nextTimeout = false,
      leagues_data = settings.leagues_data;

    simulation = function () {
      if (stop_simulation) return;

      $opponents_list = $(opponents_list);
      $(opponents_list).click(function () {
        if (stop_simulation) {
          $('.matchRating').remove();
          wait_simulate($(this), -1);
        }
      });

      stop_simulation = false;
      $('.btnStopSimulation').show();
      $('.lead_table_view').scrollTop(0);
      $('.matchRating').remove();
      simulate(0);
    };
    simulate = function (i) {
      if (i >= $opponents_list.length || stop_simulation) {
        $btnStopSimulation.click();
        return;
      }

      var $opponent = $($opponents_list[i]),
        opponent_full = $opponent.find('td:nth-child(4)').text();

      if (
        $('.lead_table table tbody tr:last-child').attr('sorting_id') ==
        $opponent.attr('sorting_id')
      )
        stop_simulation = true;

      // fix se -/-/-
      if (opponent_full == '3/3') simulate(i + 1);
      else {
        // $('.matchRating').remove();
        $opponent.trigger('click');
        wait_simulate($opponent, i);
      }
    };
    wait_simulate = function ($opponent, position) {
      var $rating = $('.matchRating'),
        next = false;
      if (!$rating.length)
        next = function () {
          wait_simulate($opponent, position);
        };
      else {
        var color = $rating.css('color');
        $opponent.find('td').css('color', color);
        leagues_data.push({
          name: $opponent.find('.nickname').text(),
          color: color
        });
        change_settings('leagues_data', leagues_data);
        if (position != -1) {
          $rating.remove();
          next = function () {
            simulate(position + 1);
          };
        }
      }
      nextTimeout = setTimeout(next, 25);
    };

    if (settings.colored_leagues) {
      var $leaguesTable = $('.leagues_table');

      write_cache = function () {
        if (leagues_data.length) {
          for (var i = 0; i < leagues_data.length; i++) {
            var opponent_data = leagues_data[i];
            $leaguesTable.find('.nickname:contains(' + opponent_data.name + ')').parent().parent()
              .addClass('cached')
              .find('td').css('color', opponent_data.color);
          }
        }
      };
      write_cache();
      $leaguesTable.find('th').click(write_cache);

      if (!$(opponents_list).length) {
        $btnClearCache = $(
          '<a class="blue_button_L btnLeagues">Clear</a>'
        );
        $btnClearCache.click(function () {
          change_settings('leagues_data', []);
          location.href = "/tower-of-fame.html";
        });
        $leaguesTable.append($btnClearCache);
      } else {
        var after = settings.leagues_scan_after;
        if (toint_element($('.challenge_points .over span[energy]')) < 1) after = settings.leagues_scan_after_long;
        setTimeout(simulation, after);

        $btnStopSimulation = $(
          '<a class="blue_button_L btnLeagues">Stop</a>'
        );
        $btnStopSimulation.click(function () {
          clearTimeout(simulationTimeout);
          clearTimeout(nextTimeout);
          stop_simulation = true;
          $(this).hide();
        });
        $leaguesTable.append($btnStopSimulation);

        $leaguesTable.find('th').click(function () {
          if (!$(this).find('span').length) return;

          $btnStopSimulation.click();
          stop_simulation = false;
          simulationTimeout = setTimeout(simulation, 1000);
        });
      }
    }

    if (!$('.challenge .blue_button_L').length || settings.always_first_leagues)
      $(opponents_list.replace(':not(.cached)', '')).first().trigger('click');

    addCss(
      '.leagues_table{position: relative}' +
      '.btnLeagues{' +
      '  position: absolute;' +
      '  top: 0;' +
      '  left: 0;' +
      '  z-index: 99;' +
      '}'
    );
  } else if (page == 'activities') {
    confirm_exceed = function (e, values = {}) {
      var exceed = '';

      if (!values.hasOwnProperty('xp')) values.xp = 0;
      if (!values.hasOwnProperty('troll')) values.troll = 0;

      var new_total_troll_fight = Hero.energies.fight.amount + values.troll,
        max_troll_fight = Hero.energies.fight.max_amount;
      if (values.troll > 0) new_total_troll_fight++; // Add for next hour
      if (new_total_troll_fight >= max_troll_fight)
        exceed += 'troll fights (in next hour ' + new_total_troll_fight + '/' + max_troll_fight + ')';

      if (Hero.infos.Xp.left <= values.xp) {
        if (exceed != '')
          exceed += ' and ';
        exceed += 'experience (' + values.xp + '/' + Hero.infos.Xp.left + ' left)';
      }
      if (exceed != '') {
        if (!confirm('Are you sure? you\'ll exceed ' + exceed))
          return stopClick(e);
        $(e.target).trigger('click');
      }
    };
    find_rewards = function (rewards) {
      var results = {};
      for (var i = 0; i < rewards.length; i++) {
        var reward = rewards[i];
        if (reward.type == 'xp')
          results.xp = toint_string(reward.value);
        if (reward.type == 'energy_fight')
          results.troll = toint_string(reward.value);
      }
      return results;
    };

    change_tab = function () {
      var $tab = $('.tabs h4.selected');
      change_settings('last_link_activity', $tab.attr('rel'));
      if ($tab.hasClass('pop')) {
        if (settings.auto_press_btns && settings.auto_assign_pop) {
          var $btnExit = $('.pop_right_part .back_button:not([id]):visible');
          if (settings.exit_after_pop_assign && $btnExit.length) {
            change_settings('exit_after_pop_assign', false);
            setTimeout(function () { $btnExit.trigger('click'); }, 2000);
          }

          var $btnPurple = $('.purple_button_L:visible').first();
          $btnPurple.trigger('click');
          if (!$btnPurple.length)
            $('.pop_thumb_container').each(function () {
              if (!$(this).find('.pop_thumb_progress_bar:visible').length) {
                change_settings('exit_after_pop_assign', true);
                $(this).find('button[rel="pop_thumb_info"]:visible').trigger('click');
              }
            });
        }

        if (settings.safe_work)
          $('.pop_thumb_container img, img[girl-ava-src]').addClass(
            'safe-work'
          );

        addCss(
          '#pop .pop_list .pop_list_scrolling_area .pop_thumb_container {' +
          '  margin: 0px 2px 10px;' +
          '  width: 100px;' +
          '}' +
          '#pop .pop_list .pop_list_scrolling_area .pop_thumb>.pop_thumb_progress_bar,' +
          '#pop .pop_list .pop_list_scrolling_area .pop_thumb_expanded .pop_thumb_title,' +
          '#pop .pop_list .pop_list_scrolling_area .pop_thumb>.pop_thumb_title{' +
          '  width: 95px;' +
          '}' +
          '#pop .pop_list .pop_list_scrolling_area .pop_thumb>button{' +
          '  width: 93px;' +
          '}' +
          '#pop .pop_list .pop_list_scrolling_area .pop_thumb>.pop_thumb_progress_bar .pop_thumb_remaining,' +
          '#pop .pop_list .pop_list_scrolling_area .pop_thumb>.pop_thumb_title span{' +
          '  font-size:10px' +
          '}' +
          '#pop .pop_list .pop_list_scrolling_area .pop_thumb>.pop_thumb_progress_bar .hh_bar>.backbar{' +
          '  width: 90px!important' +
          '}' +
          '#pop .pop_list .pop_list_scrolling_area{' +
          '  margin-top: 40px' +
          '}' +
          '.nicescroll-rails{display:none!important}',
          true
        );
      } else if ($tab.hasClass('contests')) {
        if (settings.safe_work) {
          $('.right_part>img').addClass('safe-work');
          safeWorkBackground('.contest_header');
        }

        if (settings.confirm_exceed)
          $('.contest .personal_rewards button[rel="claim"]:visible').mousedown(function (e) {
            var rewards_string = $(e.target).parent().find('.reward_wrap').attr('data-reward-display'),
              rewards = JSON.parse(rewards_string).rewards;

            if (confirm_exceed(e, find_rewards(rewards)))
              return;
          });
      } else if ($tab.hasClass('daily_goals')) {
        if (settings.safe_work)
          $('.daily-goals-right-part>img').addClass('safe-work');

        if (settings.confirm_exceed)
          $('.progress-bar-rewards-container').mousedown(function (e) {
            var rewards_string = $(e.target).parent().find('.progress-bar-reward-chest').attr('data-rewards'),
              rewards = JSON.parse(rewards_string).rewards;

            if (confirm_exceed(e, find_rewards(rewards)))
              return;
          });
      } else {
        if (settings.auto_press_btns) {
          $('.mission_object:not([data-d*=\'"remaining_time":null\'])').each(function () {
            $btn = $(this).find('button.purple_button_L:visible');
            if (!$btn.length) return;

            if (Hero.infos.Xp.left <= settings.min_collect_exp &&
              $(this).find('.mission_reward .slot_xp').length)
              return;

            $btn.trigger('click');
          });
          if ($('.end_gift:visible').length)
            $('.end_gift button').trigger('click');
        }

        if (settings.confirm_exceed)
          $('button.purple_button_L:visible').mousedown(function (e) {
            var rewards_string = $(e.target).parent().parent().find('.mission_reward .reward_wrap').attr('data-reward-display'),
              rewards = JSON.parse(rewards_string).rewards;

            if (confirm_exceed(e, find_rewards(rewards)))
              return;
          });
      }
    };

    if (settings.safe_work) $('.mission_image, .timer-girl-container').addClass('safe-work');

    change_tab();
    $('.tabs h4').click(change_tab);
  } else if (page == 'pantheon') {
    if (settings.safe_work)
      $('.team-girl-container, #rewards-girl-container img').addClass(
        'safe-work'
      );

    if (settings.pantheon_auto_enter) {
      auto_enter = function () {
        var $btnPantheon = $('.pantheon-pre-battle-btn');
        if (
          $btnPantheon.length &&
          $('#tabs_switcher #pantheon_tab').hasClass('underline-tab') &&
          !page_interact &&
          $('#scriptPantheonAttempts').text() != '0'
        )
          location.href = $btnPantheon.attr('href');
      };
      setTimeout(auto_enter, 3000);
      $('#tabs_switcher .switch-tab').click(auto_enter);
    }
  } else if (page == 'champions' || page == 'club_champion') {
    if (settings.safe_work) {
      $(
        '.new-battle-image, .champions-over__girl-image, .champions-over__champion-image'
      ).addClass('safe-work');
      var interval = setInterval(function () {
        $girl = $('.section__preview-characters>div');
        if ($girl.length) {
          $girl.addClass('safe-work');
          clearInterval(interval);
        }
      }, 5);
      $('.champions-over__champion-tier-link').click(function () {
        setTimeout(function () {
          safeWorkBackground('#scene_popup');
        }, 100);
      });
    }
    addCss('.champions-bottom__rest{font-size: 15px}' +
      '.champions-over__girl-image{z-index:999}' +
      '.champions-over__champion-wrapper{pointer-events:auto!important}');

    if (page == 'champions') {
      var max_champions = 6,
        champion_id = toint_string(championData.champion.id),
        $btns_container = $('<div class="btns_container"></div>');

      $btns_container.appendTo($('.champions-bottom__wrapper'));

      previous_champion_id = champion_id - 1;
      if (previous_champion_id < 1)
        previous_champion_id = max_champions;
      $('<button class="finished round_blue_button">' +
        '	<img src="https://hh.hh-content.com/design/ic_arrow-left-ffffff.svg">' +
        '</button>')
        .click(function () { goToChampion(previous_champion_id); })
        .appendTo($btns_container);

      next_champion_id = champion_id + 1;
      if (next_champion_id > max_champions)
        next_champion_id = 1;
      $('<button class="finished round_blue_button">' +
        '	<img class="continue" src="https://hh.hh-content.com/design/ic_arrow-right-ffffff.svg">' +
        '</button>')
        .click(function () { goToChampion(next_champion_id); })
        .appendTo($btns_container);

      addCss(
        '.btns_container{' +
        '  display: flex;' +
        '  position: absolute;' +
        '  top: 5px;' +
        '  right: 149px;' +
        '}' +
        '.btns_container .round_blue_button img{height: 75%}'
      );

      if (settings.journey_champion_active) {
        journeyChampion();
        $('button[rel="perform"]').click(function () {
          change_settings('journey_champion', next_champion_id);
        });
      }
    }
  } else if (page == 'champions_map') {
    if (settings.journey_champion_active)
      journeyChampion();
    $('.champion-lair').click(changeLastChampionLink);
  } else if (page == 'event') {
    if (settings.safe_work)
      $('.girl-avatar, .nc-event-reward-preview>img').addClass('safe-work');
    $('.nc-event-list-reward-container').click(function () {
      if (settings.safe_work)
        var interval = setInterval(function () {
          $girl = $('.animated-girl-display, img[girl-ava-src]');
          if ($girl.length) {
            $girl.addClass('safe-work');
            clearInterval(interval);
          }
        }, 5);
      fixDiamondImg();
    });
    // Boss bang (fixed)
    // if (settings.last_bang_team_active && $('#boss_bang').length) {
    //   var bang_selector = '.boss-bang-team-slot';
    //   if (settings.last_bang_team > 1)
    //     $(bang_selector + '[data-slot-index="' + settings.last_bang_team + '"]').trigger('click');
    //   $(bang_selector).click(function () {
    //     change_settings('last_bang_team', $(this).attr('data-slot-index'));
    //   });
    // }
  } else if (page == 'side-quests') {
    if (settings.safe_work) $('.side-quest-image').addClass('safe-work');
    $('.side-quest-button').click(function () {
      change_settings('last_side_quest', $(this).attr('href'));
    });
  } else if (page == 'pachinko') {
    if (settings.safe_work) {
      setInterval(function () {
        $('.pachinko_img').addClass('safe-work');
      }, 100);
      $('canvas, .pachinko_img, .game-simple-block>img').addClass('safe-work');
    }
    questLink();
  } else if (page == 'teams') {
    if (settings.safe_work) $('.girl-image-container').addClass('safe-work');
  } else if (page == 'home') {
    if (settings.safe_work) {
      $('.news_wrapper').bind('DOMNodeInserted', function () {
        $('.news_thumb_pic, .news_page_pic').addClass('safe-work');
      });
      $('.waifu-container').addClass('safe-work');
    }
    $('#collect_all .collect-infos .sum').after($('<br>'));
    if (settings.auto_collect_harem)
      $('#collect_all_container').click(function () {
        location.href = "/harem.html";
      });

    if (settings.retrive_home_timer) {
      var routes = [
        { link: '/pachinko.html', selector: '#scriptPachinkoTimer', check: 'a[rel="pachinko"]' },
        { link: '/shop.html?type=potion', selector: '#scriptMarketTimer', check: 'a[rel="shop"]' },
        { link: '/activities.html?tab=missions', selector: '#missionsTimer1', check: 'a[rel="activities"]' },
        { link: '/club-champion.html', selector: '#scriptClubChampionTimer', check: 'a[rel="clubs"]' },
        { link: '/season.html', selector: '#scriptSeasonTime', check: '#kisses_data>a' },
        { link: '/path-of-valor.html', selector: '#scriptPoVTimer', check: 'a[rel="path-of-valor"]' },
        { link: '/path-of-glory.html', selector: '#scriptPoGTimer', check: 'a[rel="path-of-glory"]' },
        { link: '/activities.html?tab=pop', selector: '#scriptPoPTimer span', check: '#pop_data>a' },
      ];
      setInterval(function () {
        for (var i = 0; i < routes.length; i++) {
          var route = routes[i];
          if ($(route.selector).text() == '0s') {
            if (route.check != '' && $(route.check).attr('href') == '#')
              continue;
            change_settings('redirect_to_home', true);
            location.href = route.link;
          }
          if (settings.redirect_to_home) break;
        }
      }, 2500);
    }

    // Random waifu
    init_change_waifu = function () {
      if (settings.random_waifu && settings.girls_data) {
        var $waifu_container = $('.waifu-container>img'),
          src = $waifu_container.attr('src');
        change_waifu = function () {
          var random_waifu = random(settings.girls_data.length - 1),
            selected_waifu = settings.girls_data[random_waifu],
            random_grade = random(selected_waifu.grade),
            image = generateImg(selected_waifu.id, random_grade, src);

          $waifu_container
            .attr('src', image)
            .attr('title', selected_waifu.name + ' : ' + random_grade);

          appendStory('.waifu-and-right-side-container', selected_waifu.id);
        };
        change_waifu();
        setInterval(change_waifu, settings.change_waifu_interval * 1000);
        var timeoutWaifu = false;
        $waifu_container.click(function () {
          clearTimeout(timeoutWaifu);
          timeoutWaifu = setTimeout(function () {
            if (!unsafe_click)
              change_waifu();
            unsafe_click = false;
          }, 300);
        })
          .css('cursor', 'pointer');
      }
    };
    init_change_waifu();
    $('.waifu-buttons-container .eye').click(init_change_waifu);

    // Last links
    if (settings.last_links) {
      if (settings.last_side_quest)
        $('.continue_side_quest_home, .side_quests').attr('href', settings.last_side_quest);
      var $activitiesLink = $('a[rel="activities"]');
      $activitiesLink.find('a[href^="' + links.activity + '"]').click(changeLastActivityLink);
      if (settings.last_link_activity)
        $activitiesLink.attr('href', links.activity + settings.last_link_activity);
      shopMenuLink();
      if (settings.last_link_shop)
        $('a[rel="shop"]').attr('href', links.shop + settings.last_link_shop);
      championMenuLink();
      if (settings.last_link_champion)
        $('.champions_map').attr('href', settings.last_link_champion);
      // $('a[rel="sex-god-path"]') removed cause no other links are present anymore
    }

    // Settings
    $containerSettings = $('#contains_all');
    $toggleSettings = $('<img src="https://hh.hh-content.com/design/menu/panel.svg" id="btnSettings"></img>');
    $toggleSettings
      .appendTo($containerSettings)
      .click(function () {
        $settingsArea.toggleClass('active');
      });
    $settingsArea = $('<div id="settingsArea"></div>');
    $settingsArea.appendTo($containerSettings);
    var settings_to_generate = [
      { name: 'auto_press_btns', text: 'Auto press buttons' },
      { name: 'auto_collect_harem', text: 'Auto collect when enter in harem' },
      { name: 'not_collect_full_graded', text: 'Collect only full graded girl (recommended)' },
      { name: 'redirect_shop_not_full_graded', text: 'Redirect to shop gift if not_collect_full_graded' },
      { name: 'auto_assign_pop', text: 'Auto assign in place of power' },
      {
        name: 'safe_work',
        text: 'Safe for work filter',
        onchange: function (value) {
          toggleSafeWork('.waifu-container');
        },
        stopafterchange: true
      },
      { name: 'random_waifu', text: 'Random waifu image' },
      { name: 'colored_leagues', text: 'Colored leagues list' },
      { name: 'colored_season', text: 'Colored season opponent' },
      { name: 'pantheon_auto_enter', text: 'Auto enter in pantheon (5s)' },
      { name: 'journey_champion_active', text: 'Champion journey' },
      //{ name: 'last_bang_team_active', text: 'Select the last team in bang event' },
      { name: 'last_links', text: 'Override menu link with last visited page' },
      { name: 'selected_mythic_book', text: 'Select mythic book instead of legendary (market xp)' },
      { name: 'retrive_home_timer', text: 'Retrive automatically home timer (pachinko, pop, market and other)' }, /*  */
      { name: 'confirm_exceed', text: 'Ask for confirmation if rewards exceed' },
      { name: 'back_to_link', text: 'Back to previous page when miss' },
      { name: 'header_link_show', text: 'Clickable header link after battle' },
      { name: 'always_first_leagues', text: 'Always select first opponent in leagues' },
      { name: 'girls_data_print', text: 'Print in console girls_data (to improve)' },
    ];
    for (var index = 0; index < settings_to_generate.length; index++) {
      var setting = settings_to_generate[index];
      generateSetting(setting, $settingsArea);
    }

    addCss(
      '#homepage .waifuStory{' +
      '  position: absolute;' +
      '  bottom: 20px;' +
      '  left: 49%;' +
      '  z-index: 9;' +
      '}' +
      'span.pay-in{display: initial!important}' +
      '#collect_all{cursor: pointer}' +
      '#homepage .main-container .middle-container .waifu-and-right-side-container .right-side-container .event-container .collect-button #collect_all_container #collect_all .collect-infos .cost-text span[cur=hard_currency]::before {' +
      '  width: 13px;' +
      '  height: 15px;' +
      '}' +
      '#homepage .main-container .middle-container .waifu-and-right-side-container .right-side-container .event-container .season-pov-container .pov-button > a > .button-notification-icon, #homepage .main-container .middle-container .waifu-and-right-side-container .right-side-container .event-container .season-pov-container .season-button > a > .button-notification-icon{margin-top: 0}' +
      '#homepage .main-container .left-side-container .quest-container>a>.button-notification-icon, #homepage .main-container .left-side-container>a>.button-notification-icon{z-index: 999}' +
      '#homepage .main-container .middle-container .waifu-and-right-side-container .right-side-container .event-container .collect-button #collect_all_container #collect_all .collect-infos .cost-text{margin-top: 0}' +
      '#homepage .main-container .middle-container .waifu-and-right-side-container .right-side-container .event-container .season-pov-container .pov-button, #homepage .main-container .middle-container .waifu-and-right-side-container .right-side-container .event-container .season-pov-container .season-button{z-index: 1}' +
      '#home_pov_bar .text{width: 100%}' +
      '#settingsArea{' +
      '  font-size: 12px;' +
      '  text-align: left;' +
      '  z-index: 99;' +
      '  padding: 3px 5px;' +
      '  border: 2px solid rgb(144, 83, 18);' +
      '  border-radius: 6px;' +
      '  background-color: rgba(32, 3, 7, 0.9);' +
      '  position: absolute;' +
      '  right: 55px;' +
      '  top: 47px;' +
      '  display: none;' +
      '}' +
      '#settingsArea.active{display: block}' +
      '#btnSettings{' +
      '  z-index: 100;' +
      '  height: 35px;' +
      '  position: absolute;' +
      '  top: 122px;' +
      '  right: 15px;' +
      '  filter: drop-shadow(#000 0px 0px 5px);' +
      '  cursor: pointer;' +
      '}' +
      '.switchSetting {' +
      '  position: relative;' +
      '  display: inline-block;' +
      '  width: 34px;' +
      '  height: 17px;' +
      '}' +
      'input:checked + .sliderSetting{background-color: rgb(241, 31, 100)}' +
      '.sliderSetting {' +
      '  position: absolute;' +
      '  cursor: pointer;' +
      '  inset: 0px;' +
      '  background-color: rgb(204, 204, 204);' +
      '  transition: all 0.4s ease 0s;' +
      '  border-radius: 17px;' +
      '  margin-right: 4px;' +
      '}' +
      'input:checked + .sliderSetting::before {transform: translateX(13px)}' +
      '.sliderSetting::before {' +
      '  position: absolute;' +
      '  content: "";' +
      '  height: 13px;' +
      '  width: 13px;' +
      '  left: 2px;' +
      '  bottom: 2px;' +
      '  background-color: white;' +
      '  transition: all 0.4s ease 0s;' +
      '  border-radius: 50%;' +
      '}', true);
  } else if (page == 'world') {
    if (settings.safe_work) {
      $('div.girl_world, div.troll_world').addClass('safe-work');
      addCss('#worldmap div.troll_world{pointer-events:auto!important}');
    }
  } else if (page == 'path-of-valor' || page == 'path-of-glory') {
    if (settings.safe_work) $('.girl-preview>img').addClass('safe-work');
  } else if (page == 'sex-god-path') {
    if (settings.safe_work) $('.feature-categories img').addClass('safe-work');
  } else if (page == 'hero_pages') {
    if (settings.safe_work) $('img[girl-ava-src]').addClass('safe-work');
  } else if (page == 'edit-team' || page == 'add-boss-bang-team') {
    if (settings.safe_work) $('.girl-display img[girl-ava-src]').addClass('safe-work');
  } else if (page == 'troll-pre-battle') {
    questLink();
    addBackToLink('/world/' + (settings.last_id_troll + 1));
    addCss(
      '#opponent-panel .girls_reward.girl_ico .animate > div{' +
      '  animation: 2s linear 0s infinite normal none running vertical_slots0!important' +
      '}'
    );
  } else if (page == 'pantheon-pre-battle') {
    questLink();
    addBackToLink('/sex-god-path.html');
  } else if (page == 'battle' /* probably deprecated */ ||
    page == 'league-battle' ||
    page == 'pantheon-battle' ||
    page == 'season-battle' ||
    page == 'troll-battle' ||
    page == 'boss-bang-battle') {
    if (settings.safe_work) $('.new-battle-image').addClass('safe-work');
  } else if (page == 'waifu') {
    if (settings.safe_work) {
      setTimeout(waifuSafeWork, 500);
      $('.harem-girl-container').click(waifuSafeWork);
    }
  } else if (page == 'clubs') {
    $('#members tr .active_light').each(function () {
      var days = toint_string($(this).attr('afk')) / 60 / 60 / 24;
      if (days >= settings.max_days_club) {
        $(this)
          .addClass('offline')
          .parent().next().find('.member_name').css('color', '#96141a');
      }
    });
    addCss('.active_light.offline{background-color: #96141a!important}');
  }
  else if (page == 'messenger') {
    if (settings.safe_work) {
      safeWorkCamera = function () {
        setTimeout(function () {
          $('.girl-album-image, .message-image').addClass('safe-work');
        }, 500);
      };
      safeWorkCamera();
      $('.girl-conversation').click(safeWorkCamera);
    }
  }

  // Global
  if (settings.auto_press_btns) {
    var to_press = true;
    setInterval(function () {
      $btns = $(
        '.popup_buttons .blue_button_L, button[rel="pop_claim"]:not(:disabled)'
      );
      if ($btns.length && $btns.is(':visible') && to_press) {
        to_press = false;
        setTimeout(function () {
          $btns.trigger('click');
          to_press = true;
        }, 1000);
      }
    }, 300);

    var to_press_fast = true;
    setInterval(function () {
      $btnsFast = $(
        '#new-battle-skip-btn, .skip-button, .not-supported-browser .blue_button_L,' +
        'button[rel="pop_auto_assign"]:not(:disabled), button[rel="pop_action"]:not(:disabled)'
      );
      if ($btnsFast.length && to_press_fast) {
        // to_press_fast = false;
        $btnsFast.trigger('click');
        // to_press_fast = true;
      }
    }, 50);
  }
  if (settings.journey_champion)
    change_settings('journey_champion', false);

  if (settings.safe_work) {
    var to_check = true;
    setInterval(function () {
      $heroPage = $('#hero_pages');
      if ($heroPage.length && to_check) {
        to_check = false;
        $heroPage.find('.girls, .img_wrapper').addClass('safe-work');
        to_check = true;
      }
      $(
        '#girls_holder #left_girl, #girls_holder #right_girl, .animated-girl-display, .payments-left-girl, .payments-right-girl, #no_energy_worship>img, #no_energy_fight>img, #no_energy_kiss>img, #no_energy_challenge>img, #awakening_popup .awakening-avatar, #no_energy_quest>img'
      ).addClass('safe-work');
    }, 10);
    $('#no_HC').bind('DOMNodeInserted', function () {
      $('.season_pass #left_girl_sp, .season_pass #right_girl_sp, .payments .product-background').addClass('safe-work');
    });

    setInterval(unsafeWork, 1000);
  }

  $(document).on('keypress', function (e) {
    if ($(e.target).is('.club-chat-input')) return;
    if (e.which == 13) $('.blue_button_L:visible').first().trigger('click');
  });

  $('a[href^="' + links.troll + '"]').click(changeLastTroll);
  $('button[data-href^="' + links.troll + '"]').click(changeLastTroll);
  trollMenuLink();

  $('.energy_counter[type="fight"] .energy_counter_amount').wrap('<a href="' + links.troll + settings.last_id_troll + '" class="link_last_troll"></a>');

  // Girl preview images
  var current_girlpreview = 0,
    discover_previewgirls = false,
    list_previewgirls = [],
    list_previewgirls_types = {},
    selector_previewgirls = 'canvas, img:not(.excluded)',
    current_src;
  position_preview = function () {
    return (current_girlpreview + 1) + '/' + list_previewgirls.length;
  };
  preview_girl = function (id_img) {
    $('.nc-panel-preview-girl').remove();
    var $panelImg = $(
      '<div class="nc-panel-preview-girl">' +
      '  <div class="nc-panel">' +
      '    <div class="nc-panel-header">' +
      '      <a href="#" class="close_cross potions-paths-panel-button">' +
      '        <img class="excluded" src="https://hh.hh-content.com/clubs/ic_xCross.png">' +
      '      </a>' +
      '    </div>' +
      '    <div class="nc-panel-body"><p style="text-align:center;font-size:2em;color:#fff">LOADING..</p></div>' +
      '    <div class="nc-panel-footer">' +
      '      <p class="prev">&lt;</p>' +
      '      <div class="current"' + (list_previewgirls.length > 1 ? '' : ' style="visibility:hidden"') + '>' +
      '        <p class="position">' + position_preview() + '</p>' +
      '      </div>' +
      '      <p class="next">&gt;</p>' +
      '    </div>' +
      '  </div>' +
      '</div>');
    $('#contains_all').append($panelImg);
    $panelImg.find('.close_cross').click(function () {
      $panelImg.remove();
      list_previewgirls = [];
      list_previewgirls_types = {};
      current_girlpreview = 0;
    });
    $panelImg.find('.prev').click(function () {
      current_girlpreview--;
      if (current_girlpreview < 0) current_girlpreview = list_previewgirls.length - 1;
      preview_girl(list_previewgirls[current_girlpreview]);
    });
    $panelImg.find('.next').click(function () {
      current_girlpreview++;
      if (current_girlpreview >= list_previewgirls.length) current_girlpreview = 0;
      preview_girl(list_previewgirls[current_girlpreview]);
    });
    $panelImg.find('.current .position').click(function () {
      current_girlpreview = window.prompt('Type a number [0 to ' + (list_previewgirls.length - 1) + '] or string "random":', 'random');
      if (current_girlpreview == 'random')
        current_girlpreview = random(list_previewgirls.length);
      else current_girlpreview = toint_string(current_girlpreview);
      if (current_girlpreview >= list_previewgirls.length) current_girlpreview = 0;
      if (current_girlpreview < 0) current_girlpreview = list_previewgirls.length - 1;
      preview_girl(list_previewgirls[current_girlpreview]);
    });

    appendStory('.nc-panel-preview-girl .current', id_img);

    var $panelBody = $panelImg.find('.nc-panel-body'),
      total_images = 0;
    for (var grade = 0; grade < 7; grade++)
      $('<img class="excluded" src="' + generateImg(id_img, grade, current_src, list_previewgirls_types[id_img]) + '">')
        .appendTo($panelBody)
        .on('error', function () {
          $(this).remove();
          total_images++;
        })
        .on('load', function () {
          total_images++;
        });
    var intResizeGirl = setInterval(function () {
      if (total_images == 7) {
        clearInterval(intResizeGirl);
        $panelBody.find('p').remove();
        $imgs = $panelBody.find('img');
        $imgs.css({
          'width': (100 / $imgs.length) + '%',
          'height': $panelBody.height(),
        }).click(function () {
          $(this).toggleClass('zoom');
          $panelBody.scrollTop($(this).position().top);
        });
      }
    }, 500);
  };
  setInterval(function () {
    $(selector_previewgirls)
      .off('contextmenu.girlpreview')
      .on('contextmenu.girlpreview', function (e) {
        if ($(this).is('canvas')) {
          regex = /id_[0-9]+_grade/g;
          search = 'id';
        } else {
          regex = /(\/[0-9]+\/(ava|ico)|ciao)/g;
          search = 'src';
        }
        var search = $(this).attr(search),
          founds = search.match(regex);
        if (founds === null || !founds.length) return;

        id_img = toint_string(founds[0]);
        if (!list_previewgirls.includes(id_img)) {
          list_previewgirls.push(id_img);
          var type = 'girls',
            types = [
              'troll',
              'club_champions',
              'champions'
            ];
          for (var i = 0; i < types.length; i++)
            if (search.includes(types[i])) {
              type = types[i];
              break;
            }
          list_previewgirls_types[id_img] = type;
        }
        if (discover_previewgirls) return;

        current_src = search;
        preview_girl(id_img);

        // Discover other images
        discover_previewgirls = true;
        $(selector_previewgirls).trigger('contextmenu');
        setTimeout(function () {
          discover_previewgirls = false;
          var $panel = $('.nc-panel-preview-girl');
          $panel.find('.current')
            .css('visibility', '');
          $panel.find('.current .position')
            .html(position_preview());
          if (list_previewgirls.length <= 1) {
            $panel.find('.prev, .next').hide();
            $panel.find('.nc-panel-footer').css('justify-content', 'center');
            $panel.find('.current .position').off('click');
          }
        }, 1500);

        return stopClick(e);
      });
  }, 500);

  fixDiamondImg();

  addCss(
    '.nc-panel-preview-girl{' +
    '  position: absolute!important;' +
    '  z-index: 999999;' +
    '  top: 12%;' +
    '  left: 0;' +
    '  right: 0;' +
    '  display: flex;' +
    '  flex-direction: column;' +
    '  justify-content: center;' +
    '  align-items: center;' +
    '}' +
    '.nc-panel-preview-girl .nc-panel{' +
    '  width: 1025px;' +
    '  height: 520px;' +
    '  background: linear-gradient(to top,#572332 0,#572332 1%,#2c1e1c 100%);' +
    '  border-radius: 7px;' +
    '  padding: 18px;' +
    '  display: flex;' +
    '  flex-direction: column;' +
    '  border: 2px solid #ffa23e;' +
    '}' +
    '.nc-panel-preview-girl .nc-panel-header{' +
    '  display: flex;' +
    '  justify-content: space-between;' +
    '  z-index: 1;' +
    '}' +
    '.nc-panel-preview-girl .nc-panel-header .close_cross{' +
    '  margin-top: 4px;' +
    '  width: 44px;' +
    '  height: 44px;' +
    '}' +
    '.nc-panel-preview-girl .nc-panel-body{' +
    '  display: flex;' +
    '  justify-content: center;' +
    '  align-items: center;' +
    '  flex: 1;' +
    '  flex-wrap: wrap;' +
    '  overflow-y: auto;' +
    '}' +
    '.nc-panel-preview-girl .nc-panel-body>img{' +
    '  width: 0;' +
    '  object-fit: contain;' +
    '  cursor: pointer;' +
    '}' +
    '.nc-panel-preview-girl .nc-panel-body>img.zoom{' +
    '  width: 100%!important;' +
    '  height: auto!important;' +
    '  backdrop-filter: brightness(0.8);' +
    '  border-radius: 3em;' +
    '}' +
    '.nc-panel-preview-girl .nc-panel-footer{' +
    '  display: flex;' +
    '  justify-content: space-between;' +
    '}' +
    '.nc-panel-preview-girl .nc-panel-footer p{' +
    '  font-size: 1.5em;' +
    '  margin: 0;' +
    '  line-height: 1em;' +
    '  cursor: pointer;' +
    '}' +
    '.nc-panel-preview-girl .current{' +
    '  display: flex;' +
    '  align-items: center;' +
    '  gap: 5px;' +
    '}' +
    '.waifuStory img{' +
    '  width: 55px!important;' +
    '  height: auto!important;' +
    '}' +
    '.nc-panel-preview-girl .waifuStory img{width:30px!important}' +
    '#popups>#confirm_HC>label, img.classGirl{display: none}' +
    '#leagues_middle .lead_table .nicescroll-rails, #leagues_middle .use-lead-table .nicescroll-rails{top: 0!important}' +
    '.safe-work:not(.unsafe-work){' +
    '  opacity: 0.05!important;' +
    '  transition: none;' +
    '  filter: grayscale(1);' +
    '}' +
    '.link_last_troll{' +
    '  color: #fff;' +
    '  text-decoration: none;' +
    '}'
  );
  // They fix it
  // '#collect_all_container #collect_all{' +
  // '  -webkit-box-shadow: 0 2px 0 rgb(13 22 25 / 35%), inset 0 3px 0 #f9b12e;' +
  // '  -moz-box-shadow: 0 2px 0 rgba(13,22,25,.35),inset 0 3px 0 #f9b12e;' +
  // '  box-shadow: 0 2px 0 rgb(13 22 25 / 35%), inset 0 3px 0 #f9b12e;' +
  // '}'
  if (settings.header_link_show)
    addCss('#popups.fixed_scaled, #sliding-popups.fixed_scaled, #black_screen{top: 10%}', true);
  if (settings.back_to_link)
    addCss(
      '.back-to {' +
      '  position: absolute;' +
      '  top: 0;' +
      '  left: 50%;' +
      '  transform: translateX(-50%);' +
      '  color: white;' +
      '  text-decoration: none;' +
      '  text-shadow: 0 0px 2px black;' +
      '}',
      true);

  appendCss();
});