Hentai Heroes Helper (auto collect, button press and more)

Extension for Hentai Heroes game.

// ==UserScript==
// @name  Hentai Heroes Helper (auto collect, button press and more)
// @description Extension for Hentai Heroes game.
// @version     3.8.4
// @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==

var HeroData = window.Hero;
if (window.shared !== undefined) HeroData = window.shared.Hero;
// console.table(HeroData);
is_numeric = function (c) {
    return /^\d+$/.test(c);
};
toint_string = function (str) {
    if (typeof str == 'number') return 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 = 'erocollect_options',
    default_settings = {
        auto_collect_harem: false,
        timeout_collect_after: 3000,
        not_collect_full_graded: false,
        safe_work: false,
        pantheon_auto_enter: true,
        auto_press_btns: false,
        girls_data: false,
        girls_data_export: false,
        girls_data_full: false,
        random_waifu: false,
        change_waifu_interval: 30,
        last_id_troll: 1,
        last_bang_team_points: 0,
        last_bang_team_points_active: false,
        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_season: true,
        last_links: true,
        back_to_link: true,
        header_link_show: true,
        confirm_exceed: true,
        auto_start_activities: false,
        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_item: true,
        upgrade_girl_redirect: false,
        trigger_shop_arrows: 0,
        choosed_bg: '',
        invert_bg: false,
        cg_background: false,
        shards_state: {},
        carac_state: {},
        minimum_money_open_harem: 0,
        link_last_troll: true,
        // temp_girl_list: [],
        // temp_girl_list_index: 0,
    },
    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) {
    if (typeof setting.type == 'undefined') setting.type = 'checkbox';

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

// Story functions
girlLink = function (id, tab = 'affection') {
    tab = '?resource=' + tab;
    if (!tab) tab = '';
    return '/girl/' + id + tab;
};
questLink = function () {
    $('#canvas_quest_energy .energy_counter_bar .bar-wrapper .over').wrap(
        '<a href="' +
            HeroData.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', girlLink(id)).click(function () {
        change_settings('start_girl_story', true);
    });
};
retriveSalary = function () {
    return toint_element($('#collect_all span[rel="next_salary"]'));
};
// 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',
        orange: '#eeaa34',
        shadow_orange:
            'rgb(33 27 7 / 60%) 0px 3px 0px, rgb(240 117 33) 0px 3px 0px inset',
    },
    add_css = '',
    $body = false;
$(function () {
    $body = $('body[page]');
    var page = $body.attr('page'),
        page_interact = false;
    // console.log(page);
    $('#contains_all').click(function (e) {
        if (
            page_interact ||
            (page == 'shop' &&
                e.target.parentNode.parentNode.classList.contains(
                    'inventory_slots'
                ))
        )
            return;
        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 ||
                    window.pachinkoDef[3].content.games[0].button_type == 1)
            )
                return;

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

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

    if (page == 'harem') {
        if (settings.girls_data_export) addExportDataLink();

        var shards_state_list = ['owned', 'inprogress', 'notowned'];
        for (var i = 0; i < shards_state_list.length; i++) {
            var shard_name = shards_state_list[i];
            if (settings.shards_state[shard_name])
                $('.shards-state.' + shard_name).trigger('click');
        }
        $('.shards-state').click(function () {
            var btn = $(this)
                .attr('class')
                .replace('check-btn shards-state ', '');
            settings.shards_state[btn] =
                $(this).attr('shardsstate') == 'active';
            change_settings('shards_state', settings.shards_state);
        });

        for (var carac = 1; carac <= 3; carac++) {
            if (settings.carac_state['c' + carac])
                $('.carac-state[carac="' + carac + '"]').trigger('click');
        }
        $('.carac-state').click(function () {
            settings.carac_state['c' + $(this).attr('carac')] =
                $(this).attr('caracstate') == 'active';
            change_settings('carac_state', settings.carac_state);
        });

        var girls = null,
            interval_collect = false,
            can_collect = true,
            $girl_list = $('.girls_list'),
            start_from = 0,
            girls_data = [],
            stop_collect = false,
            $btnStopCollect,
            $btnRestartCollect,
            money_not_collected = 0;

        checkPopupError = function () {
            // The server didn't answer properly. Please try again.
            // Unauthorized Access, perhaps a session loss, reloading page...
            var $text_popup = $(
                    '#popup_message:not(.popup-not-supported-browser)'
                ),
                founds = $text_popup
                    .text()
                    .match(/(Please try again|Unauthorized Access)/g);
            if (founds === null || !founds.length) return false;

            $btnStopCollect.trigger('click');
            return true;
        };
        $('#popups').bind('DOMNodeInserted', checkPopupError);

        restart_collect = function () {
            $btnStopCollect.show();
            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 || stop_collect || checkPopupError()) 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'),
                grade: $stars.length,
            });

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

            if (settings.not_collect_full_graded) {
                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;

                money_not_collected += toint_element(
                    $girl.find('.collect_money .s_value')
                );
                if (money_not_collected == retriveSalary())
                    $btnStopCollect.trigger('click');
            }

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

            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 {
                    change_settings('girls_data_full', true);
                    change_settings('girls_data', girls_data);
                    // maybe better do not click last girl, expecially for next run
                    // $girl.trigger('click');
                    $btnStopCollect.hide();
                    if (retriveSalary()) $btnRestartCollect.trigger('click');
                }
                if (!settings.girls_data_full)
                    change_settings('girls_data', girls_data);
            } else start_from = i;
            if (!after && i % 50 === 0) collect_girl(i + 1);
            else
                setTimeout(function () {
                    collect_girl(i + 1);
                }, after);
        };
        is_cheat_click = function (e) {
            return false;
        };

        $haremLeft = $('#harem_left');
        $btnStopCollect = $('<div id="btnStopCollect" class="stop"></div>');
        $btnStopCollect.click(function () {
            clearInterval(interval_collect);
            stop_collect = !stop_collect;
            var icon = '';
            if (stop_collect) icon = '▶';
            else restart_collect();
            $(this).html(icon).toggleClass('stop');
        });
        $btnStopCollect.appendTo($haremLeft);
        $btnRestartCollect = $('<div id="btnRestartCollect">⟲</div>');
        $btnRestartCollect.click(function () {
            if (!stop_collect) $btnStopCollect.trigger('click');
            $btnStopCollect.trigger('click');
        });
        $btnRestartCollect.appendTo($haremLeft);

        var total_salary = retriveSalary();
        if (
            settings.auto_collect_harem &&
            !settings.upgrade_girl_redirect &&
            !settings.start_girl_story &&
            !(!total_salary && settings.girls_data.length)
        ) {
            collect();
            $('select').change(function () {
                $girl_list.scrollTop(0);
                restart_collect();
            });
        } else $btnStopCollect.trigger('click').hide();
        if (settings.upgrade_girl_redirect)
            change_settings('upgrade_girl_redirect', false);

        // 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, .missing_girl, .girl-display')
                        .addClass('safe-work');
            },
            last_dom_id_girl = 0;
        $(harem_right)
            .append($btnSafeWork)
            .bind('DOMNodeInserted', function () {
                addSafeWork();
                var $avatar = $('.avatar'),
                    avatar_src = $avatar.attr('src');
                if (avatar_src)
                    $avatar.attr('src', avatar_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);
                    });

                var id_girl = $('[girl].opened').attr('girl');
                if (last_dom_id_girl == id_girl) return;
                last_dom_id_girl = id_girl;

                setTimeout(function () {
                    var awakening_costs =
                            window.girlsDataList[id_girl].awakening_costs,
                        $gems = $('#gems-amount'),
                        actual_gems = toint_element($gems);
                    $gems.text(awakening_costs + '/' + actual_gems);
                    if (awakening_costs > actual_gems)
                        $gems.css('color', '#c30009');
                }, 100);
            });
        $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);
                });
        });

        // Move fast in girl page (removed ocd)
        // $('.girl_line .hudPlus_mix_icn').hover(function () {
        //     var temp_girl_list = [],
        //         temp_girl_list_index = i = 0;
        //     $('.girls_list [girl]').each(function () {
        //         temp_girl_list.push($(this).attr('girl'));
        //         if ($(this).hasClass('opened')) temp_girl_list_index = i;
        //         i++;
        //         // Temp storing
        //         if (i % 15 === 0) {
        //             change_settings('temp_girl_list_index', temp_girl_list_index);
        //             change_settings('temp_girl_list', temp_girl_list);
        //         }
        //     });
        //     change_settings('temp_girl_list_index', temp_girl_list_index);
        //     change_settings('temp_girl_list', temp_girl_list);
        // });

        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}' +
                '#btnStopCollect{' +
                '    position: absolute;' +
                '    bottom: 0;' +
                '    right: 10px;' +
                '    font-size: 25px;' +
                '    cursor: pointer;' +
                '    height: 35px;' +
                '    z-index: 100;' +
                '}' +
                '#btnStopCollect.stop{height: 25px;}' +
                '#btnStopCollect.stop::after {' +
                '    content: "";' +
                '    box-sizing: border-box;' +
                '    position: relative;' +
                '    display: block;' +
                '    width: 20px;' +
                '    height: 20px;' +
                '    background: currentColor' +
                '}' +
                '#btnRestartCollect{' +
                '    position: absolute;' +
                '    bottom: 0;' +
                '    right: 35px;' +
                '    font-size: 25px;' +
                '    cursor: pointer;' +
                '    height: 35px;' +
                '    z-index: 100;' +
                '}'
        );
    } else if (page == 'labyrinth-battle') {
        if (settings.safe_work) {
            setInterval(function () {
                $('.pvp-container').addClass('safe-work');
            }, 150);
        }
    } else if (page == 'girl') {
        if (settings.safe_work) {
            $('.girl-avatar').addClass('safe-work');
            setTimeout(function () {
                $('.quicknav').addClass('safe-work');
            }, 1500);
        }

        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 journey (removed ocd)
        // if (settings.temp_girl_list.length) {
        //     var max_index = settings.temp_girl_list.length - 1,
        //         temp_index = settings.temp_girl_list_index,
        //         $btns_container = $('<div class="btns_container"></div>');

        //     $btns_container.appendTo($('.inventory-section'));

        //     previous_temp_index = temp_index - 1;
        //     if (previous_temp_index < 0) previous_temp_index = max_index;
        //     $(
        //         '<button class="finished round_blue_button">' +
        //         '	<img src="https://hh.hh-content.com/design/ic_arrow-left-ffffff.svg">' +
        //         '</button>'
        //     )
        //         .click(function () {
        //             change_settings('temp_girl_list_index', previous_temp_index);
        //             location.href = girlLink(settings.temp_girl_list[previous_temp_index], false);
        //         })
        //         .appendTo($btns_container);

        //     next_temp_index = temp_index + 1;
        //     if (next_temp_index > max_index) next_temp_index = 0;
        //     $(
        //         '<button class="finished round_blue_button">' +
        //         '	<img class="continue" src="https://hh.hh-content.com/design/ic_arrow-right-ffffff.svg">' +
        //         '</button>'
        //     )
        //         .click(function () {
        //             change_settings('temp_girl_list_index', next_temp_index);
        //             location.href = girlLink(settings.temp_girl_list[next_temp_index], false);
        //         })
        //         .appendTo($btns_container);
        // }

        // Select book or gift
        var selector_book = ':not(.mythic)';
        if (settings.selected_mythic_item) selector_book = '';
        selectGirlSlot = function () {
            $(
                '.inventory:visible .inventory-slot:not(.empty-slot) .slot' +
                    selector_book
            )
                .last()
                .parent()
                .trigger('click');
        };
        setTimeout(selectGirlSlot, 1500);
        $('.tabs-switcher .switch-tab').click(selectGirlSlot);

        addCss(
            '#girl_max_out_popup{margin-top:-5em}' +
                '.btns_container{' +
                '  display: flex;' +
                '  position: absolute;' +
                '  top: 40px;' +
                '  right: 5px;' +
                '}' +
                '.btns_container .round_blue_button img{height: 75%}'
        );
    } else if (page == 'quest') {
        if (settings.safe_work) {
            var scene_selector = '#scene #background, .quest_v2';
            $(scene_selector).addClass('safe-work');
            $('#temp-background')
                // .remove();
                .dblclick(function () {
                    $(scene_selector).trigger('dblclick');
                }); // Not working
            $('#scene .eye').click(function () {
                toggleSafeWork(scene_selector);
            });
        }

        // if (settings.not_collect_full_graded)
        //     $('button.grade-complete-button').click(function () {
        //         change_settings('upgrade_girl_redirect', true);
        //     });

        if (settings.cg_background)
            $('#scene').contextmenu(function (e) {
                change_settings(
                    'choosed_bg',
                    $(this).find('#background').attr('src')
                );
                return stopClick(e);
            });

        $('#breadcrumbs>span:nth-child(7)')
            .css('cursor', 'pointer')
            .click(function () {
                location.reload();
            });

        // Girl page
        var $girlBack = $('#breadcrumbs > a:nth-child(5)'),
            linkGirlBack = $girlBack.attr('href');
        if (linkGirlBack.startsWith('/harem/'))
            $girlBack.attr('href', linkGirlBack.replace('harem', 'girl'));
    } else if (page == 'season_arena') {
        if (settings.colored_season) {
            var css_hero = '#season-arena .battle_hero',
                hero_power = toint_element(
                    $(css_hero + ' #player_attack_stat #stats-damage')
                ),
                hero_crown = toint_element(
                    $(css_hero + ' #player_ego_stat #stats-ego')
                ),
                opponent_index = 0;
            $('.opponents_arena .season_arena_opponent_container').each(
                function () {
                    var $opponent_power = $(this).find(
                            '#player_attack_stat #stats-damage'
                        ),
                        opponent_power = toint_element($opponent_power),
                        $opponent_crown = $(this).find(
                            '#player_ego_stat #stats-ego'
                        ),
                        opponent_crown = toint_element($opponent_crown),
                        result_power = hero_power >= opponent_power,
                        result_crown = hero_crown >= opponent_crown;
                    power_percent = (opponent_power * 5) / 100;
                    // anche arancione se nel 2.2%/5% 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
                    );

                    var colors = false;
                    if (!result_power && !result_crown)
                        colors = {
                            background: theme_colors.gray,
                            'box-shadow': theme_colors.shadow_gray,
                            '-webkit-box-shadow': theme_colors.shadow_gray,
                        };
                    else if (!result_power || !result_crown)
                        colors = {
                            background: theme_colors.orange,
                            'box-shadow': theme_colors.shadow_orange,
                            '-webkit-box-shadow': theme_colors.shadow_orange,
                        };
                    if (colors)
                        $('.opponents_arena .opponent_perform_button_container')
                            .eq(opponent_index)
                            .find('button')
                            .css(colors);
                    opponent_index++;
                }
            );
            // Se neanche uno scegli migliore in giallo
            // Se almeno uno tutti i gialli grigi
        }

        questLink();
    } else if (page == 'shop') {
        if (settings.safe_work) $('.market-girl').addClass('safe-work');

        // Awake girl info
        // 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_item) 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;
        // };
        $('.market-menu-switch-tab').click(function (e) {
            change_settings('last_link_shop', $(this).attr('type'));
            // setTimeout(selectFirstToBuy, 1000);
            // return stopClick(e);
        });
        // setTimeout(function () {
        //     if (page_interact) return;
        //     selectFirstToBuy();
        // }, 1000);

        // Left arrow after upgrade
        // var temp_trigger = settings.trigger_shop_arrows,
        //     selector_right_arrow =
        //         '#shops #girls_list .g1 span[nav][nav=right]',
        //     selector_left_arrow = '#shops #girls_list .g1 span[nav][nav=left]';
        // change_settings('trigger_shop_arrows', 0);
        // $(selector_left_arrow).click(function () {
        //     change_settings(
        //         'trigger_shop_arrows',
        //         settings.trigger_shop_arrows + 1
        //     );
        // });
        // $(selector_right_arrow).click(function () {
        //     change_settings(
        //         'trigger_shop_arrows',
        //         settings.trigger_shop_arrows - 1
        //     );
        // });
        // if (settings.upgrade_girl_redirect) {
        //     var selector_arrow = selector_left_arrow;
        //     if (temp_trigger < 1) {
        //         selector_arrow = selector_right_arrow;
        //         temp_trigger = Math.abs(temp_trigger);
        //     }
        //     for (var trigger = 0; trigger < temp_trigger; trigger++)
        //         $(selector_arrow).trigger('click');
        //     change_settings('upgrade_girl_redirect', false);
        // }

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

        // Clear filter
        // var appendBtnClearFilter = function () {
        //     var $arena = $('#arena_filter_box');
        //     if (!$arena.length) {
        //         setTimeout(appendBtnClearFilter, 300);
        //         return;
        //     }

        //     var $btnClearFilter = $(
        //         '<input type="button" class="blue_button_L" value="Clear filter" style="width:100%;height:36px;padding-top:5px;">'
        //     );
        //     $arena.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');
        //     });
        // };
        // appendBtnClearFilter();

        // Breadcrumb shop link
        // $('#breadcrumbs>span:nth-child(3)')
        //     .css('cursor', 'pointer')
        //     .click(function () {
        //         location.href = links.shop + settings.last_link_shop;
        //     });

        // Count sell items
        $('.right-side-title').dblclick(function () {
            var items = null,
                $items_list = $(this).parent().find('.menu-content'),
                start_from = 0,
                nb_track = 0,
                items_data = [],
                total_slot = 0,
                total_price = 0;

            $items_list.bind('DOMNodeInserted', function () {
                if (nb_track > 5) return;

                nb_track++;
                track();
            });
            track = function () {
                items = $items_list.find('.slot');
                track_item(start_from);
            };
            track_item = function (i) {
                if (i >= items.length) return;

                var $item = $(items[i]),
                    nbr_stack = 1,
                    $stack = $item.find('.stack_num');
                if ($stack.length) nbr_stack = toint_element($stack);
                total_slot += nbr_stack;
                // json = JSON.parse($item.attr('data-d'));
                // if (typeof json != 'undefined')
                // total_price += json['price_sell'];

                // items_data.push({
                // });
                if (i === items.length - 1) {
                    $items_list.scrollTop($items_list.prop('scrollHeight'));
                    var end = $item.parent().hasClass('empty');
                    if (nb_track > 5 || end) {
                        if (!end) console.log('more');
                        console.log('Total points: ' + total_slot * 50);
                        // console.log('Total money: ' + total_price);
                        return;
                    }
                } else {
                    start_from = i;
                    track_item(i + 1);
                }
            };
            track();
        });

        addCss(
            '#player-inventory{width:21rem!important}' +
                '#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 == '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 =
                    HeroData.energies.fight.amount + values.troll,
                max_troll_fight = HeroData.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 (HeroData.infos.Xp.left <= values.xp) {
                if (exceed != '') exceed += ' and ';
                exceed +=
                    'experience (' +
                    values.xp +
                    '/' +
                    HeroData.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-switcher .switch-tab.underline-tab').attr(
                'data-tab'
            );
            change_settings('last_link_activity', tab);
            switch (tab) {
                case '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);
                        }
                        if ($btnExit.length)
                            $('[rel="pop_auto_assign"]').click(function () {
                                if ($('[rel="pop_action"]').is(':disabled'))
                                    change_settings('auto_assign_pop', false);
                            });

                        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' +
                            '}' +
                            '.nicescroll-rails{display:none!important}',
                        true
                    );
                    break;
                case '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;
                        });
                    break;
                case '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;
                            }
                        );

                    if (!$('.nicescroll-cursors').length) {
                        $('.daily-goals-objectives-container').addClass(
                            'can_scroll'
                        );
                        addCss(
                            '.daily-goals-objectives-container.can_scroll{overflow-y:auto!important}',
                            true
                        );
                    }
                    break;
                default:
                    if (settings.auto_press_btns) {
                        // :not([data-d*=\'"remaining_time":null\'])
                        $('.mission_object').each(function () {
                            $btn = $(this).find(
                                'button.purple_button_L:visible'
                            );
                            if (!$btn.length) return;

                            if (
                                HeroData.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.auto_start_activities) {
                        $('.mission_button .blue_button_L').trigger('click');
                        page_interact = false;
                    }
                    break;
            }
        };

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

        change_tab();
        $('.tabs-switcher .switch-tab').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 #carousel, .sm-static-girl'
            ).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], .gradient_mask>img'
                    );
                    if ($girl.length) {
                        $girl.addClass('safe-work');
                        clearInterval(interval);
                    }
                }, 5);
            fixDiamondImg();
        });

        var tempGirlAnimation = null;
        $('body').on('keydown', function (e) {
            if (e.keyCode !== 37 && e.keyCode !== 39) return;

            var selector = '.nc-event-list-reward-container',
                $actualGirl = $(selector + '.selected');
            $girl =
                e.keyCode === 37 // Left
                    ? $actualGirl.prev(selector)
                    : e.keyCode === 39 // Right
                    ? $actualGirl.next(selector)
                    : false;

            if ($girl.length) {
                // Original code
                var selectedGirlId = $girl
                    .find('.nc-event-list-reward')
                    .data('selectGirlId');
                var girlHasAnimation = false;
                eventGirls.forEach(function (eventGirl) {
                    if (
                        eventGirl.id_girl == selectedGirlId &&
                        eventGirl.hasOwnProperty('animated_grades') &&
                        eventGirl.animated_grades.includes('0')
                    ) {
                        girlHasAnimation = true;
                    }
                });
                $('.nc-event-list-reward-container').removeClass('selected');
                $('.nc-event-reward-container').removeClass('selected');
                $(
                    '.nc-event-reward-container[data-reward-girl-id=' +
                        selectedGirlId +
                        ']'
                ).addClass('selected');
                $girl.addClass('selected');

                if (tempGirlAnimation !== null) {
                    tempGirlAnimation.removeCurrentAnimation();
                    $('.nc-event-reward-container .nc-event-reward-preview')
                        .find('canvas')
                        .remove();
                    $(
                        '.nc-event-reward-container[data-reward-girl-id=' +
                            selectedGirlId +
                            '] .nc-event-reward-preview'
                    )
                        .find('canvas')
                        .remove();
                }
                if (girlHasAnimation && !HeroData.infos.no_pachinko_anim) {
                    $(
                        '.nc-event-reward-container[data-reward-girl-id=' +
                            selectedGirlId +
                            '] .nc-event-reward-preview'
                    )
                        .find('img')
                        .remove();
                    $(
                        '.nc-event-reward-container[data-reward-girl-id=' +
                            selectedGirlId +
                            '] .nc-event-reward-preview'
                    ).append(
                        '<canvas class="animated-girl-display" id="id_' +
                            selectedGirlId +
                            '_grade_0_animated"></canvas>'
                    );
                    tempGirlAnimation = new GirlAnimation();
                    tempGirlAnimation.initAnimation(
                        selectedGirlId,
                        0,
                        '/images/pictures/girls/',
                        0.3
                    );
                }
            }
            return stopClick(e);
        });

        // Boss bang
        if ($('#boss_bang').length) {
            var bang_selector = '.boss-bang-team-slot',
                bang_selected = bang_selector + '.selected-boss-bang-team';
            $('#start-bang-button').click(function () {
                change_settings('last_bang_team_points_active', true);
            });
            if (settings.last_bang_team_points_active) {
                change_settings('last_bang_team_points_active', false);
                var $el_bang = $(bang_selected).find(
                        '.boss-bang-team-ego span:first-child'
                    ),
                    new_point =
                        (toint_element($el_bang) -
                            settings.last_bang_team_points) /
                        10,
                    $score = 'green">+ ';
                if (new_point < 0) $score = '#e98100">';
                $el_bang.after(
                    ' <span style="color:' + $score + new_point + '%</span>'
                );
            }
            $(bang_selector).click(function () {
                change_settings(
                    'last_bang_team_points',
                    toint_element(
                        $(this).find('.boss-bang-team-ego span:first-child')
                    )
                );
            });
            $(bang_selected).trigger('click');
        }

        addCss(
            '#dp-content .left-container .tiers-container .player-progression-container{height:125%}'
        );
    } 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 &&
            !$('.free-text:visible').length &&
            toint_string($('#collect_all .sum').attr('amount')) >=
                settings.minimum_money_open_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"]',
                    notif: $('body').attr('id') != 'hh_star',
                },
                {
                    link: links.shop + 'potion',
                    selector: 'a[rel="shop"] span[rel="expires"]',
                    check: 'a[rel="shop"]',
                    notif: false,
                },
                {
                    link: links.activity + 'missions',
                    selector: '#missionsTimer1:visible',
                    check: 'a[rel="activities"]',
                    notif: false,
                },
                {
                    link: settings.last_link_champion,
                    selector: '#scriptChampionsTimer:visible',
                    check: 'a[rel="sex-god-path"]',
                    notif: false,
                },
                {
                    link: '/club-champion.html',
                    selector: 'a[rel="clubs"] span[rel="expires"]',
                    check: 'a[rel="clubs"]',
                    notif: false,
                },
                {
                    link: '/season.html',
                    selector: '#scriptSeasonTime',
                    check: '#kisses_data>a',
                    notif: false,
                },
                {
                    link: '/path-of-valor.html',
                    selector: '#scriptPovTime',
                    check: 'a[rel="path-of-valor"]',
                    notif: false,
                },
                {
                    link: '/path-of-glory.html',
                    selector: '#scriptPogTime',
                    check: 'a[rel="path-of-glory"]',
                    notif: false,
                },
                {
                    link: links.activity + 'pop',
                    selector: '#scriptPoPTimer span:visible',
                    check: '#pop_data>a',
                    notif: false,
                },
            ];
            var redirectPage = function (route) {
                change_settings('redirect_to_home', true);
                location.href = route.link;
            };
            setInterval(function () {
                for (var i = 0; i < routes.length; i++) {
                    var route = routes[i];
                    if (
                        route.notif &&
                        $(route.check).find(
                            '.button-notification-icon:not(.button-notification-doubleshards)'
                        ).length
                    )
                        redirectPage(route);

                    if ($(route.selector).text() == '0s') {
                        if (
                            !settings.auto_assign_pop &&
                            route.link == links.activity + 'pop'
                        )
                            continue;
                        if (
                            route.check != '' &&
                            $(route.check).attr('href') == '#'
                        )
                            continue;
                        redirectPage(route);
                    }
                    if (settings.redirect_to_home) break;
                }
            }, 2500);
        }

        setInterval(function () {
            // Colored timer event
            var timersList = [
                '#scriptPogTime',
                '#scriptPovTime',
                '#scriptSeasonTime',
                '[rel="seasonal-event"] [rel="expires"]',
                '[rel="event"] [rel="expires"]',
                '[rel="mythic_event"] [rel="expires"]',
                '[rel="sm_event"] [rel="expires"]',
                '[rel="cumback_contest"] [rel="expires"]',
                '[rel="boss_bang_event"] [rel="expires"]',
                '[rel="path_event"] [rel="expires"]',
                '[rel="dp_event"] [rel="expires"]',
                '[rel="kinky_event"] [rel="expires"]',
                '[rel="legendary_contest"] [rel="expires"]',
                '[rel="double_pachinko_event"] [rel="expires"]',
            ];
            for (var i = 0; i < timersList.length; i++) {
                var $timer = $(timersList[i]),
                    timers = $timer.text().trim().split(' ');
                if (
                    timers.length &&
                    !$timer.parent().attr('data-seconds-until-start')
                ) {
                    timer = timers[0];
                    var color = '';
                    if (
                        timer == '3g' ||
                        timer == '4g' ||
                        timer == '5g' ||
                        timer == '3d' ||
                        timer == '4d' ||
                        timer == '5d'
                    )
                        color = '#fffa71';
                    if (
                        timer == '1g' ||
                        timer == '2g' ||
                        timer == '1d' ||
                        timer == '2d'
                    )
                        color = '#ff8d00';
                    if (
                        timer == '0g' ||
                        timer == '0d' ||
                        (timer.slice(-1) != 'g' && timer.slice(-1) != 'd')
                    )
                        // || timers.length == 2
                        color = '#d61350';
                    $timer.css({
                        color: color,
                        'text-shadow': '0 0 1px #fff',
                    });
                }
            }
        }, 1000);

        // 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
        setTimeout(function () {
            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
            }
        }, 200);

        // 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: 'timeout_collect_after',
                text: 'Timeout collect girl in harem<br>in millisecond - default: 3s - es. 3 seconds => 3000ms',
                type: 'number',
                min: 25,
                step: 100,
            },
            {
                name: 'not_collect_full_graded',
                text: 'Collect only full graded girl (recommended)',
            },
            {
                name: 'minimum_money_open_harem',
                text: 'Minimum amount to open harem clicking right collect all button<br>default: 0',
                type: 'number',
                min: 0,
                step: 1000,
            },
            { 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: 'change_waifu_interval',
                text: 'Change waifu interval<br>in seconds - default: 30s',
                type: 'number',
                min: 5,
            },
            { 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_links',
                text: 'Override menu link with last visited page',
            },
            { name: 'link_last_troll', text: 'Go to last troll battle' },
            {
                name: 'selected_mythic_item',
                text: 'Select mythic item instead of legendary (girl page)',
            },
            {
                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: 'auto_start_activities',
                text: 'Auto start the daily activities',
            },
            { name: 'back_to_link', text: 'Back to previous page when miss' },
            {
                name: 'header_link_show',
                text: 'Clickable header link after battle',
            },
            {
                name: 'cg_background',
                text: 'Change background with selected story/messenger image',
            },
            { name: 'invert_bg', text: 'Flip horizontally background' },
            {
                name: 'girls_data_export',
                text: 'Export girls data button in the market',
            },
            {
                name: 'min_collect_exp',
                text: 'Do not collect if xp lower than<br>default: 10.000',
                type: 'number',
                min: 1,
                step: 100,
            },
            {
                name: 'max_days_club',
                text: 'Flag club member as inactive after days<br>default: 60 days',
                type: 'number',
                min: 1,
            },
        ];
        for (var index = 0; index < settings_to_generate.length; index++) {
            var setting = settings_to_generate[index];
            generateSetting(setting, $settingsArea);
        }
        $settingsArea.append(
            $(
                '<p style="text-align:center; margin-bottom:0">All docs at <a href="https://sleazyfork.org/en/scripts/436188-hentai-heroes-helper-auto-collect-button-press-and-more" target="_blank" style="color:white" title="Docs">sleazyfork.org</a></p>'
            )
        );

        $(
            '<div class="setting-text-nav"><div class="setting-text-button setting-text-up">+</div><div class="setting-text-button setting-text-down">-</div></div>'
        ).insertAfter('.setting-text input');
        $('.setting-text').each(function () {
            var spinner = $(this),
                input = spinner.find('input[type="number"]'),
                btnUp = spinner.find('.setting-text-up'),
                btnDown = spinner.find('.setting-text-down'),
                min = input.attr('min'),
                max = input.attr('max'),
                step = input.attr('step');

            if (typeof step != 'undefined') step = parseFloat(step);
            else step = 1;
            if (step <= 0) step = 1;

            btnUp.click(function () {
                var oldValue = parseFloat(input.val()),
                    newVal = oldValue;
                if (oldValue + step >= max) {
                    newVal = max;
                } else {
                    newVal = oldValue + step;
                }
                spinner.find('input').val(newVal);
                spinner.find('input').trigger('change');
            });

            btnDown.click(function () {
                var oldValue = parseFloat(input.val()),
                    newVal = oldValue;
                if (oldValue - step <= min) {
                    newVal = min;
                } else {
                    newVal = oldValue - step;
                }
                spinner.find('input').val(newVal);
                spinner.find('input').trigger('change');
            });
        });
        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;' +
                '  max-height: 49vh;' +
                '  overflow-y: auto;' +
                '  display: none;' +
                '}' +
                '#settingsArea.active{display: block}' +
                '#btnSettings{' +
                '  z-index: 52;' +
                '  height: 35px;' +
                '  position: absolute;' +
                '  top: 135px;' +
                '  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%;' +
                '}' +
                '.setting-text {' +
                '  position: relative' +
                '}' +
                'input[type=number]::-webkit-inner-spin-button,' +
                'input[type=number]::-webkit-outer-spin-button' +
                '{' +
                '  -webkit-appearance: none!important;' +
                '  margin: 0!important;' +
                '}' +
                'input[type=number]' +
                '{' +
                '  -moz-appearance: textfield!important;' +
                '}' +
                '.setting-text input {' +
                '  width: 100px;' +
                '  float: left;' +
                '  display: block;' +
                '  padding: 2px;' +
                '  margin: 0;' +
                '  border: 1px solid rgb(241, 31, 100);' +
                '  border-radius: 4px;' +
                '}' +
                '.setting-text input:focus {' +
                '  outline: 0!important;' +
                '}' +
                '.setting-text-nav {' +
                '  float: left;' +
                '  position: relative;' +
                '  height: 20px!important;' +
                '}' +
                '.setting-text-button {' +
                '  position: relative;' +
                '  cursor: pointer;' +
                '  border-left: 1px solid rgb(241, 31, 100);' +
                '  width: 15px;' +
                '  text-align: center;' +
                '  color: #333;' +
                '  font-size: 15px;' +
                '  line-height: 12px;' +
                '  -webkit-transform: translateX(-100%);' +
                '  transform: translateX(-100%);' +
                '  -webkit-user-select: none;' +
                '  -moz-user-select: none;' +
                '  -ms-user-select: none;' +
                '  -o-user-select: none;' +
                '  user-select: none;' +
                '}' +
                '.setting-text-button.setting-text-up {' +
                '  position: absolute;' +
                '  height: 70%;' +
                '  top: 0;' +
                '  border-bottom: 1px solid rgb(241, 31, 100);' +
                '}' +
                '.setting-text-button.setting-text-down {' +
                '  position: absolute;' +
                '  bottom: -3px;' +
                '  height: 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 == 'seasonal') {
        addCss(
            '.seasonal-event-panel .seasonal-event-container .tabs-section #home_tab_container .middle-container .girls-reward-container canvas.animated-girl-display{z-index:0!important}'
        );
        if (settings.safe_work)
            $('.girls-reward-container').addClass('safe-work');
    } else if (page == 'path-of-valor' || page == 'path-of-glory') {
        if (settings.safe_work) {
            $('.girl-preview>img').addClass('safe-work');
            addCss(
                '.potions-paths-background-panel .potions-paths-second-row .animation-container{z-index:0!important}' +
                    '.potions-paths-background-panel .potions-paths-second-row .potions-paths-central-section{z-index:9}'
            );
        }

        $('.girl-preview').each(function () {
            var $a = $(
                '<a class="waifuStory" href="/girl/' +
                    $(this).attr('girl-id') +
                    '?resource=affection"><img src="https://hh.hh-content.com/design_v2/affstar.png"></a>'
            );
            $a.click(function () {
                change_settings('start_girl_story', true);
            });
            $(this).find('.girl-info-container').append($a);
        });
    } 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' ||
        page == 'edit-labyrinth-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));
        if (
            $('.rewards_list>.girls_reward:not(.items_reward) .slot').length > 1
        )
            addCss(
                '.girls_reward.girl_ico .animate > div{' +
                    '  animation-duration: 2s!important' +
                    '}'
            );
    } else if (page == 'pantheon-pre-battle') {
        questLink();
        addBackToLink('/sex-god-path.html');

        $('#pre-battle .battle-buttons-row > a').insertAfter(
            $('#pre-battle .battle-buttons-row > button')
        );
    } else if (page == 'leagues-pre-battle') {
        if (settings.safe_work) {
            $('.girl-block').addClass('safe-work');
        }
    } else if (
        page == 'battle' /* probably deprecated */ ||
        page == 'league-battle' ||
        page == 'pantheon-battle' ||
        page == 'season-battle' ||
        page == 'troll-battle' ||
        page == 'troll-pre-battle' ||
        page == 'boss-bang-battle'
    ) {
        if (settings.safe_work) $('.new-battle-image').addClass('safe-work');

        addCss(
            '#popups #rewards_popup .flex-container .rewards{margin:30px 0px!important}' +
                '#popups #rewards_popup .flex-container .rewards:has(.shards){margin:145px 0px!important}' +
                '#rewards_popup .popup_buttons{transform:translateY(-40px)}'
        );
    } else if (page == 'waifu') {
        if (settings.safe_work) {
            setTimeout(waifuSafeWork, 500);
            $('.harem-girl-container').click(waifuSafeWork);
        }
    } else if (page == 'clubs') {
        $('#members .body-row .active_light').each(function () {
            var days = toint_string($(this).attr('afk-tooltip')) / 60 / 60 / 24;
            if (days >= settings.max_days_club) {
                $(this).parent().find('p').css('color', '#96141a');
            } else $(this).removeClass('offline');
        });
        addCss('.active_light.offline{background-color: #96141a!important}');
    } else if (page == 'messenger') {
        setInterval(function () {
            if (settings.cg_background)
                $('.girl-album-image>img, .message-image')
                    .off('contextmenu.choose_bg')
                    .on('contextmenu.choose_bg', function (e) {
                        change_settings(
                            'choosed_bg',
                            $(this).attr('src').replace('800x', '1600x')
                        );
                        return stopClick(e);
                    });

            if (settings.safe_work)
                $('.girl-album-image, .message-image').addClass('safe-work');
        }, 300);
    }

    // Global
    if (settings.auto_press_btns) {
        var to_press = true;
        setInterval(function () {
            $btns = $(
                '.popup_buttons .blue_button_L, button[rel="pop_claim"]:not(:disabled), #heal_girl_labyrinth_popup .blue_button_L'
            );
            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, .gradient_mask>img, .member-progression-bg .page-girl>img'
            ).addClass('safe-work');
        }, 10);
        $('#no_HC').bind('DOMNodeInserted', function () {
            $(
                '.season_pass #left_girl_sp, .season_pass #right_girl_sp, .payments .product-background, .product-offer-background-container, .monthly_card .rewards-container, .bundle-offer-container.treasure-bg, .season_pass #left_girl, .season_pass #right_girl'
            ).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();

    if (settings.link_last_troll)
        $('.energy_counter[type="fight"] .energy_counter_amount').wrap(
            '<a href="' +
                links.troll +
                settings.last_id_troll +
                '" class="link_last_troll"></a>'
        );
    $('.energy_counter[type="fight"] .energy_counter_bar').contextmenu(
        function (e) {
            location.href =
                links.troll + (window.HeroData.infos.questing.id_world - 1);
            return stopClick(e);
        }
    );

    // Girl preview images
    var current_girlpreview = 0,
        discover_previewgirls = false,
        list_previewgirls = [],
        list_previewgirls_info = {},
        selector_previewgirls =
            'canvas, img:not(.excluded, .icon, .user-avatar, .background_images, [src*="/pictures/design/"], [src*="/pictures/misc/"], [src*="/pictures/hero/"], [src*="/payments/"], [src*="/logo_picture/"], [src*="ic_"], [src*="/seasonal_event/"])',
        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>' +
                (list_previewgirls_info[id_img].owned
                    ? '<span style="color:#6ed902;font-weight:bold">✔</span> '
                    : '') +
                '        <span class="position">' +
                position_preview() +
                '</span></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_info = {};
            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_info[id_img].type
                    ) +
                    '">'
            )
                .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))/g;
                    search = 'src';
                }
                var search = $(this).attr(search);
                if (search) founds_preview = search.match(regex);
                else {
                    founds_preview = [];
                    $girlId = $('[girl-id]');
                    if ($girlId.length) {
                        $girlId.each(function () {
                            founds_preview.push($(this).attr('girl-id'));
                        });
                    } else if (page == 'season') {
                        for (var i = 0; i < seasons_images.length; i++)
                            founds_preview.push(seasons_images[i].id_girl);
                    } else if (page == 'seasonal') {
                        for (var i = 0; i < seasonal_girls.length; i++)
                            founds_preview.push(seasonal_girls[i].id);
                    } else if (typeof current_event != 'undefined') {
                        for (var i = 0; i < current_event.girls.length; i++)
                            founds_preview.push(current_event.girls[i].id_girl);
                    }
                }
                if (founds_preview === null || !founds_preview.length) return;

                for (var j = 0; j < founds_preview.length; j++) {
                    id_img = toint_string(founds_preview[j]);
                    if (!id_img) continue;
                    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 && search.includes(types[i])) {
                                type = types[i];
                                break;
                            }
                        }

                        var owned =
                            $(this).parent().hasClass('already-owned') ||
                            $(this).next().find('.shards>p>span').text() ===
                                '100/100';
                        list_previewgirls_info[id_img] = {
                            type: type,
                            owned: owned,
                        };
                    }
                }

                if (discover_previewgirls) return;
                id_img = list_previewgirls[0];

                current_src = search;
                if ($(this).is('canvas')) {
                    $img = $(
                        'div[data-select-girl-id="' +
                            id_img +
                            '"]>img[girl-ico-src]'
                    );
                    temp_src = $img.attr('src');
                    if (temp_src) current_src = temp_src;
                }

                preview_girl(id_img);

                // Discover other images
                discover_previewgirls = true;
                $(selector_previewgirls.replace('canvas, ', '')).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);
            });

        $(
            '.notifs:not(#awakening_popup):not(#confirm_BB_team_creation):not(#girl_max_out_popup)'
        )
            .off('click')
            .on('click', function () {
                $(this).remove();
            });
    }, 500);

    if (settings.last_side_quest)
        $('.energy_counter[type="quest"] .energy_counter_bar').contextmenu(
            function (e) {
                location.href = settings.last_side_quest;
                return stopClick(e);
            }
        );

    if (
        !settings.safe_work &&
        settings.choosed_bg != '' &&
        settings.cg_background
    ) {
        var $bg = $(
            'body:not([page="map"]):not([page="world"]):not([page="troll-battle"]) #bg_all>.fixed_scaled>img'
        );
        $bg.attr('src', settings.choosed_bg);
        if (settings.invert_bg) $bg.addClass('invert');
    }

    $('#popups').bind('DOMNodeInserted', function () {
        var text_popup = $('#popup_message').text(),
            founds = text_popup.match(
                /(Club room|Clubraum|chat server|sala del club|Club depuis|チャットサーバー)/g
            );

        if (text_popup.match(/(non supported)/g)?.length) {
            $('#popup_message').hide();
            location.reload();
        }

        if (founds === null || !founds.length) return;
        $('#popup_message').remove();
    });

    fixDiamondImg();

    addCss(
        '#popups #heal_girl_labyrinth_popup .flex-container, #popups #labyrinth_reward_popup .flex-container, #popups #level_up .flex-container, #popups #rewards_popup .flex-container, #sliding-popups #heal_girl_labyrinth_popup .flex-container, #sliding-popups #labyrinth_reward_popup .flex-container, #sliding-popups #level_up .flex-container, #sliding-popups #rewards_popup .flex-container{height:530px!important}' +
            '#popups #no_HC .payments-wrapper{transform:translateY(-60px)}' +
            '#pass_reminder_popup,#hero_resources_popup,#no_energy_quest{top:0!important}' +
            '#bg_all>.fixed_scaled>img{object-fit:cover}' +
            '#bg_all>.fixed_scaled>img.invert{transform:scaleX(-1)}' +
            '.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,' +
            '.girl-info-container  .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;' +
            '}' +
            '#popups #rewards_popup .flex-container .info_container a p{font-size:14px}' +
            '#popups #rewards_popup .flex-container .info_container img{width:60%}' +
            '#popups #rewards_popup .flex-container>h1{font-size:55px}' +
            '#popups #labyrinth_reward_popup .flex-container > h1, #popups #heal_girl_labyrinth_popup .flex-container > h1{font-size:35px}' +
            '#popups #level_up .flex-container button, #sliding-popups #level_up .flex-container button, #popups #rewards_popup .flex-container button, #sliding-popups #rewards_popup .flex-container button, #popups #heal_girl_labyrinth_popup .flex-container button, #sliding-popups #heal_girl_labyrinth_popup .flex-container button, #popups #labyrinth_reward_popup .flex-container button, #sliding-popups #labyrinth_reward_popup .flex-container button{margin-top:-4rem}'
    );
    // 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();
});

function addExportDataLink() {
    function grade_ratio(grade) {
        switch (grade) {
            case 0:
                return 1;
            case 1:
                return 1.3;
            case 2:
                return 1.6;
            case 3:
                return 1.9;
            case 4:
                return 2.2;
            case 5:
                return 2.5;
            default:
                return 0;
        }
    }

    function exportData() {
        alert(
            'Check to view the last girl that you want to export. Scroll down'
        );

        var girls_data = [];
        // Compute girls data
        $('.girls_list>div[id_girl]').each(function (index) {
            var girl_id = $(this).find('div[girl]').attr('girl');
            var girl_data = window.girlsDataList[girl_id];

            // Compute
            var cur_level = parseInt(girl_data.level);
            var cur_grade = parseInt(girl_data.graded);
            var cur_hardcore = parseInt(girl_data.caracs.carac1);
            var cur_charm = parseInt(girl_data.caracs.carac2);
            var cur_know_how = parseInt(girl_data.caracs.carac3);
            var base_hardcore =
                Math.round(
                    (cur_hardcore / cur_level / grade_ratio(cur_grade)) * 10
                ) / 10;
            var base_charm =
                Math.round(
                    (cur_charm / cur_level / grade_ratio(cur_grade)) * 10
                ) / 10;
            var base_know_how =
                Math.round(
                    (cur_know_how / cur_level / grade_ratio(cur_grade)) * 10
                ) / 10;

            // Set
            girls_data.push({
                name: girl_data.name,
                id: girl_data.id_girl,
                rarity: girl_data.rarity,
                element: girl_data.element_data.flavor,
                grade: cur_grade,
                nb_grades: girl_data.nb_grades,
                level: cur_level,
                level_cap: girl_data.level_cap,
                awakening_costs: girl_data.awakening_costs,
                hardcore: cur_hardcore,
                charm: cur_charm,
                know_how: cur_know_how,
                base_hardcore: base_hardcore,
                base_charm: base_charm,
                base_know_how: base_know_how,
                blessed: girl_data.blessed_attributes != null,
                own: girl_data.own,
            });
        });

        return girls_data;
    }

    $btnExportData = $(
        '<div id="btnExportData" style="cursor:grab; display: flex; position: absolute; font-size:30px; z-index: 30; left:3.5rem">⇲</div>'
    );
    $('.general_girls_console').children(':eq(0)').after($btnExportData);

    $btnExportData.click(function () {
        var girls_data_csv = toCsv([
            {
                name: 'Name',
                id: 'Id',
                rarity: 'Rarity',
                element: 'Element',
                grade: 'Grade',
                nb_grades: 'Max grade',
                level: 'Level',
                level_cap: 'Max level',
                awakening_costs: 'Limit raise cost',
                hardcore: 'Hardcore',
                charm: 'Charm',
                know_how: 'Know how',
                base_hardcore: 'Base hardcore',
                base_charm: 'Base charm',
                base_know_how: 'Base know how',
                blessed: 'Blessed',
                own: 'Owned',
            },
            ...exportData(),
        ]);

        // Create a temporary link for triggering the download
        var link = document.createElement('a');
        link.setAttribute(
            'href',
            'data:text/plain;charset=utf-8,' +
                encodeURIComponent(girls_data_csv)
        );
        link.setAttribute('download', 'girls_data.csv');
        link.style.display = 'none';

        document.body.appendChild(link);
        link.click();

        // For Firefox, to be tested
        setTimeout(function () {
            URL.revokeObjectURL(link.href);
            link.parentNode.removeChild(link);
        }, 0);
    });
}