Greasy Fork

Fotostrana Sports

Интерфейс на страницах Surf Rider

目前为 2019-10-26 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.greasyfork.icu/scripts/389814/744162/Fotostrana%20Sports.js

// ==UserScript==
// @name           Fotostrana Sports
// @namespace      scriptomatika
// @author         mouse-karaganda
// @description    Интерфейс на страницах Surf Rider
// @version        1.36
// @grant          none
// ==/UserScript==


var paramWindow = (typeof unsafeWindow == 'object') ? unsafeWindow : window;

(function(unsafeWindow) {
    if (unsafeWindow.self != unsafeWindow.top)
        return;

    var console = unsafeWindow.console;
    var $$ = unsafeWindow.__krokodil;
    var $ = unsafeWindow.jQuery;

    console.log('💬  Фотострана пришла! sports');

    if (!unsafeWindow.$fotostrana) {
        unsafeWindow.$fotostrana = {};
    }

    // Всплывающая подсказка для допингов в Сёрфере
    var surfDetailsTemplate = $$.join([
        '<div class="surfItemDetails">',
            '<div class="surfTooltipTitle">{title}</div>',
            '<p class="surfItemSlotName">{slotName}</p>',
            '<div class="surfItemWrap">',
                '<div class="surfItemImg"><img src="{img}"></div>',
                '<div class="surfItemBonuses">{bonuses}</div>',
            '</div>',
        '</div>'
    ], '\r\n');

    var surfSimpleTemplate = (
        '<div class="surfTooltipTitle">{title}</div>{simple}'
    );

    var surfBonusTemplate = (
        '<p class="surfItemBonus"><span class="surfProfileIco {kind}"></span> {name}: <span class="value">{value}</span></p>'
    );

    var surfVolcanoRunTable = $$.join([
        '<div class="building__content_wrapper">',
            '<div class="building__content nclear">',
                '<table class="volcanoRunTable" style="width: auto; margin: 0 auto 20px;">',
                    '<tr><td>{before}</td></tr>',
                    '<tr><td>{message}</td></tr>',
                '</table>',
            '</div>',
        '</div>',
    ], '\r\n');

    $$.extend(unsafeWindow.$fotostrana, {
        /**
         * Период ожидания для скриптов (в секундах)
         */
        missingPeriod: 180,
        missingPause: 2000
        /**
         * Определим, что мы находимся на страничке питомца
         */
        , isPetPage: function() {
            return /\.ru\/pet/i.test(location.href);
        }
        /**
         * Определим, что мы находимся на страничке финансов
         */
        , isFinancePage: function() {
            return /\.ru\/finance/i.test(location.href);
        }
        /**
         * Определим, что мы находимся на страничке серфинга
         */
        , isSportsPage: function() {
            return /\.ru\/sports/i.test(location.href);
        }
        /**
         * Определим, что мы находимся на страничке заплыва по серфингу
         */
        , isSportsRunPage: function() {
            var result = /\.ru\/sports\/index\/run/i.test(location.href);
            return result || /\.ru\/sports\/fairMiniPets\/run/i.test(location.href);
        }
        /**
         * Определим, что мы находимся на страничке кубка по серфингу
         */
        , isCupPage: function() {
            return /\.ru\/sports\/index\/cup/i.test(location.href);
        }
        /**
         * Определим, что мы находимся на страничке школы серферов
         */
        , isSchoolPage: function() {
            var result = /\.ru\/sports\/school/i.test(location.href);
            return result && !/\.ru\/sports\/school\/\w+/i.test(location.href);
        }
        /**
         * Определим, что мы находимся на страничке вулкана
         */
        , isVolcanoPage: function() {
            return /\.ru\/sports\/volcano/i.test(location.href);
        }
        /**
         * Стили для новых объектов
         */
        , styleSurf: function() {
            $$.renderStyle(
                '.miniAward { position: absolute; border: 1px solid black; border-radius: 5px; background-position: -68px 0; width: 18px; height: 18px; z-index: 1; }',
                '.miniAward.top { background-position: -50px 0; }',
                '.miniAward:hover { border-color: red; }',
                '.surfScrollWrap .miniAward { left: auto !important; right: -20px; bottom: -7px !important; }',
                '.surfShopMinigame .miniAward { right: 148px; bottom: 27px; }',
                '#volcano-prize .miniAward { right: 36px; bottom: 21px; }',
                '#volcano-app .awards .content .miniAward { left: 20px; top: 10px; }',
                '#volcano-app .awards .content .miniAward.top { left: auto; top: auto; right: 20px; bottom: 10px; }',
                '#surfSchoolBonus .surfSchoolBonusItem { display: inline-block; color: #ffeaa3; font-size: 12px; font-weight: bold; line-height: 16px; margin: 0 5px; margin: 10px 40px; text-align: center; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.35); vertical-align: top; cursor: pointer; }',
                '#surfSchoolBonus .surfSchoolBonusItem:hover { color: white; font-weight: bold; }',
                '#surfSchoolBonus .surfSchoolBonusImageWrap { background: #5b2700; border-radius: 5px; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15) inset, 0 1px 0 rgba(235, 199, 76, 0.15); margin-bottom: 4px; padding: 2px; text-align: center; }',
                '#surfSchoolBonus .surfSchoolBonusImageWrap img { width: 100px; height: auto; vertical-align: middle; }',
                '.sFriend .surfProfileIco.autoDress { background-size: 224px 143px; }',
                '.sFriend:hover .surfProfileIco.autoDress { background-size: auto auto; }',
                '.sQuestIco { vertical-align: top; }',
                '.daylyGamesArrow { position: relative; width: 48px; height: 48px; margin: 9px auto 0; border-radius: 30px; cursor: pointer; background: no-repeat center center; background-image: url(//st.fotocdn.net/app/sports/newsurf/img/common/fastRoundIco.png); }',
                '.sQuestIco:hover .daylyGamesArrow { background-color: #ff2d05; }',
                '.daylyGamesPerson { position: absolute; width: 51px; height: 51px; left: 7px; bottom: 2px; border-radius: 30px; cursor: pointer; }',
                '.daylyGamesPerson:after { content: " "; display: block; position: absolute; width: 65px; left: -7px; bottom: -2px; background: no-repeat; background-size: contain; }',
                '.daylyGamesPerson.atlantis:after { transform: scaleX(-1); height: 73px; background-image: url(//st.fotocdn.net/app/sports/newsurf/img/persons/atlantis.png); }',
                '.daylyGamesPerson.extreme:after { height: 82px; background-image: url(//st.fotocdn.net/app/sports/newsurf/img/sunday/help_image.png); }',
                '.daylyGamesPerson.rascally:after { height: 76px; background-image: url(//st.fotocdn.net/app/sports/newsurf/img/rascally/hero.png); }',
                '.sQuestIco:hover .daylyGamesPerson { background-color: #c78720; }',
                '.surfPopup.surfMinigamesPopup .surfScrollWrap { margin-top: 0; }',
                '.minigameDoubleContainer { padding-bottom: 20px; }',
                '.minigameDoubleCell { position: relative; display: inline-block; width: 40px; height: 20px; margin-bottom: 10px; }',
                '.surfInvButtons .autoDressBtn { width: auto; }',
                '.surfInvButtons .sButton { padding-left: 10px; padding-right: 10px; margin-left: 10px; }',
                '.surfInvIco-removePack { width: 26px; height: 27px; background-position: -141px -129px; margin: -1px 0 -7px 0; transform: scaleY(-1); }',
                '.volcanoRunTable { width: auto; margin: 0 auto 20px; }',
                '.auto-buttons .b_grd-button { min-width: 0; }',
                '#volcano-app .auto-buttons .content { width: 200px; }'
            );
        }
        /**
         * Быстрые настройки питомца
         */
        , quickPetSettings: function() {
            $fotostrana.missingElement('#surfSchool .surfTabs', function(exists) {
                ////a1.s.fsimg.ru/app/fs2pet/img/icons-20.png
            });
        }
        /**
         * Взять ежедневный бонус в школе серферов
         */
        , schoolBonus: function() {
            if (!this.isSchoolPage())
                return;
            var self = this;
            $fotostrana.missingElement('#surfSchool .surfTabs', function(exists) {
                if (!exists) return;
                // Создадим новую вкладку со списком бонусов
                $('<div class="surfTab" />').appendTo(this)
                    .html('<span>Взять все бонусы</span>')
                    .attr({
                        'onclick': 'surf.tabs.tabClick(this, event);',
                        'data-tab-content': '#surfSchoolBonus'
                    });
                    var bonusTab = $('<div id="surfSchoolBonus" />')
                        .addClass('surfTabContent surfDarkBlock flatTop')
                        .append('<em class="blockBg"></em>')
                        .appendTo('#surfSchool .surfTabContentWrap');
                    // Список зданий
                    var base = ('//a1.s7.fsimg.ru/app/sports/newsurf/school/');
                    var tipBase = ('//st.fotocdn.net/z/images/sports/equip/');
                    var buildings = [{
                        id: 8, img: 'img/buildings/o_8_3.png', getBonus: true,
                        tooltip: {
                            title: 'Шоколадный массаж',
                            slotName: 'Допинг',
                            img: tipBase + '691_b.png',
                            value: '+6000',
                            kind: 'doping'
                        }
                    }, {
                        id: 1, img: 'img/buildings/o_1_3.png', getBonus: false, // false
                        tooltip: {
                            title: 'Магазин',
                            simple: 'Уникальное снаряжение школы'
                        }
                    }, {
                        id: 5, img: 'img/buildings/o_5_3.png', getBonus: true,
                        tooltip: {
                            title: 'Хороший тонус',
                            slotName: 'Воодушевление',
                            img: tipBase + '247_b.png',
                            value: '+15%',
                            kind: 'doping'
                        }
                    }, {
                        id: 4, img: 'img/buildings/o_4_3.png', getBonus: true,
                        tooltip: {
                            title: 'Школьный воск Deluxe',
                            slotName: 'Допинг',
                            img: tipBase + '619_b.png',
                            value: '+4200',
                            kind: 'doping'
                        }
                    }, {
                        id: 2, img: 'img/buildings/o_2_5.png', getBonus: true,
                        tooltip: {
                            title: 'Братство серферов',
                            slotName: 'Допинг',
                            img: tipBase + '122_b.png',
                            value: '+3000',
                            kind: 'doping'
                        }
                    }, {
                        id: 6, img: 'img/buildings/o_6_2.png', getBonus: true,
                        tooltip: {
                            title: 'Бонус',
                            simple: 'Элемент коллекции в подарок'
                        }
                    }, {
                        id: 7, img: 'img/buildings/o_7_1.png', getBonus: false, // false
                        tooltip: {
                            title: 'Тяжелая травма',
                            simple: 'Лечение тяжёлых травм'
                        }
                    }, {
                        id: 3, img: 'img/buildings/o_3_3.png', getBonus: true,
                        tooltip: {
                            title: 'Тайная злость',
                            slotName: 'Навык',
                            img: tipBase + '418_b.png',
                            value: '+15000',
                            kind: 'perk'
                        }
                    }];
                    // Просто открыть здание
                    var onlyOpen = function(e) {
                        e.preventDefault();
                        var buildingId = $(this).data('buildingId');
                        surf.school.openBuilding(buildingId);
                    };
                    // Стандартная функция для бонуса
                    var defaultBonus = function(e) {
                        e.preventDefault();
                        var buildingId = $(this).data('buildingId');
                        surf.school.openBuilding(buildingId);
                        var popup = ('#surfPopup.questPopup');
                        $fotostrana.missingElement(popup, function(exists) {
                            if (!exists) return;
                            // Забираем бонус
                            surf.school.getBuildingBonus(buildingId);
                            // Сразу закроем окно
                            $fotostrana.missingElement(popup + ' .popupClose', popup + ' .equipItem .tooltip', function(exists) {
                                if (!exists) return;
                                $(this).trigger('click');
                            });
                        });
                    };
                    // Бонусы братства
                    var brothershipBonus = function(e) {
                        e.preventDefault();
                        var buildingId = $(this).data('buildingId');
                        surf.school.openBuilding(buildingId);
                        $fotostrana.missingElement('#surfPopup.questPopup', function(exists) {
                            if (!exists) return;
                            // Забираем все бонусы
                            var bonusIndex = 0;
                            var bonusList = [ 2001, 2002, 2003, 2005 ];
                            var bonusTimer = setInterval(function() {
                                surf.school.getSchoolBonus(bonusList[bonusIndex]);
                                if (++bonusIndex >= bonusList.length) {
                                    clearInterval(bonusTimer);
                                }
                            }, self.missingPause / 2);
                            // Сразу закроем окно
                            setTimeout($$.createDelegate(function() {
                                $(this).find('.popupClose').trigger('click');
                            }, this), self.missingPause * 3);
                        });
                    };
                    // Подсказка для допингов и навыков
                    var profile = {
                        doping: {
                            slide: 'Скольжение',
                            turn: 'Поворот',
                            balance: 'Баланс'
                        },
                        perk: {
                            boost: 'Ускорение'
                        }
                    };
                    var dopingTooltip = function(value, type) {
                        var current = profile[type];
                        if (!current)
                            return '';
                        var ttip = [];
                        for (var kind in current) {
                            var row = {
                                kind: kind, value: value, name: current[kind]
                            };
                            ttip.push($$.template(surfBonusTemplate, row));
                        }
                        return ttip.join('\r\n')
                    };
                    // Создать всплывающую подсказку
                    var bonusTooltip = function(index, elem) {
                        var tooltip = buildings[index].tooltip;
                        if (!tooltip)
                            return;
                        var content = $$.template(surfSimpleTemplate, tooltip);
                        if (!tooltip.simple) {
                            tooltip.bonuses = dopingTooltip(tooltip.value, tooltip.kind);
                            content = $$.template(surfDetailsTemplate, tooltip);
                        }
                        elem.tooltip({
                            tooltipExt: false, extraClass: 'simpleTooltip', content: content
                        });
                    };
                    // Вкладываем дивы по порядку
                    var table = $('<div class="surfSchoolBonusList" />')
                        .appendTo(bonusTab);
                    for (var bIndex = 0, bLen = buildings.length; bIndex < bLen; bIndex++) {
                        var building = buildings[bIndex];
                        var item = $('<div class="surfSchoolBonusItem" />')
                            .attr({ href: '?building=' + building.id })
                            .data('buildingId', building.id)
                            .appendTo(table);
                        bonusTooltip(bIndex, item);
                        $('<div class="surfSchoolBonusImageWrap" />')
                            .append($$.format('<img src="{0}" />', base + building.img))
                            .appendTo(item);
                        var linkText = (building.getBonus) ? ('Взять бонус') : ('Открыть здание');
                        item.append(linkText);
                        // События
                        var handler = null;
                        if (building.getBonus && building.id != 2) {
                            // Стандартное взятие бонуса
                            handler = defaultBonus;
                        } else if (!building.getBonus) {
                            // Просто откроем
                            handler = onlyOpen;
                        } else if (building.id == 2) {
                            // Бонусы братства
                            handler = brothershipBonus;
                        }
                        item.unbind('click').click(handler);
                    }
            });
        }
        /**
         * Взять ежедневный бонус во всех играх по серфингу
         */
        , minigameBonus: function() {
            if (!this.isSportsPage())
                return;

            var self = this;

            // Кнопка для битвы на равных
            $('<div class="daylyGamesPerson rascally" />')
                .prependTo('.surfScrollWrap.questsWrap .surfScroll')
                .wrap('<div class="sQuestIco" />')
                .attr({ title: 'Битва на равных' })
                .tooltip()
                .click(function(e) {
                    location.href = ('//fotostrana.ru/sports/honestEvent/');
                });

            // Кнопка для задир
            $('<div class="daylyGamesPerson extreme" />')
                .prependTo('.surfScrollWrap.questsWrap .surfScroll')
                .wrap('<div class="sQuestIco" />')
                .attr({ title: 'Экстремальные задиры' })
                .tooltip()
                .click(function(e) {
                    location.href = ('//fotostrana.ru/sports/extremeEvent/');
                });

            // Кнопка для мини-игр
            $('<div class="daylyGamesPerson atlantis" />')
                .prependTo('.surfScrollWrap.questsWrap .surfScroll')
                .wrap('<div class="sQuestIco" />')
                .attr({ title: 'Мини-игры' })
                .tooltip()
                .click(function(e) {
                    $('#surfFriendsWrap .dailyGames').trigger('mouseenter').trigger('click');
                });

            setTimeout(function() {
                surf.scroll($('.surfScrollWrap.questsWrap'));
            }, self.missingPause);

            // Быстрые кнопки в открытом окне
            $fotostrana.missingElement('#surfFriendsWrap .dailyGames', function(exists) {
                if (!exists) return;
                $(this).click(function(e) {
                    var openMinigames = function() {
                        $fotostrana.missingElement('#surfPopup.surfMinigamesPopup', function(exists) {
                            if (!exists) return;
                            // Подготовим контейнер для дублей
                            $('<div class="minigameDoubleContainer" />')
                                .prependTo($(this).find('.surfScrollWrap'));
                            // Добавляем к каждой игре кнопку бонуса
                            $(this).find('.surfMinigame').each($fotostrana.minigameWindowClick);
                        });
                    };
                    // Задержка, потому что на момент клика старый #surfPopup ещё не уничтожен
                    setTimeout(openMinigames, self.missingPause);
                });
            });
        }
        /**
         * Покинуть заплыв автоматически
         */
        , leaveSportsRound: function() {
            if (!this.isSportsRunPage())
                return;
            $fotostrana.missingElement('#mainTracks', function(exists) {
                if (!exists) return;
                // Скроем flash-ролик
                $(this).softHide();
                $fotostrana.missingElement('#surfRound .surfTab.user5.active', function(exists) {
                    if (!exists) return;
                    console.info('Пятый пошёл! %o', this);
                    $('#mainTracks').hide();
                    // Сигналим
                    $(document).data({ roundState: false });
                    setInterval(function() {
                        var roundState = !$(document).data('roundState');
                        document.title = roundState ? ('+') : ('Спортсмены выходят на старт!');
                        $(document).data({ roundState: roundState });
                    }, 1000);
                    // Покинем заплыв через 10 секунд
                    setTimeout(function() {
                        var toLeave = ('/sports/index/leave/');
                        if (/fairMiniPets/.test(location.href)) {
                            toLeave = ('/sports/fairMiniPets/leave/');
                        }
                        location.href = toLeave;
                    }, 10000);
                });
            });
        }
        /**
         * Добавляем к отдельно взятой игре кнопку бонуса
         */
        , minigameWindowClick: function() {
            // Отыщем, есть ли ссылка на прохождение игры
            var findGameId = $(this).html().match(/gamePopup\((\d+)\)/);
            var gameId = -1;
            try {
                gameId = findGameId[1];
            } catch (ex) { }

            console.info('minigameWindowClick: id == %o', gameId);
            if (gameId < 0) return;

            var miniAward = function() {
                var button = $('<div class="miniAward surfArrow bottom" />')
                    .attr({ title: 'Взять без игры' })
                    .tooltip()
                    .data({ 'gameid': gameId })
                    .click(function(e) {
                        var gameId = $(this).data('gameid');
                        //console.log('click: gameId == %o', gameId);
                        surf.minigames.awardPopup(gameId);
                        // Закроем последующие окна
                        $fotostrana.missingElement('#surfPopup.surfMinigameAward .sButton', function(exists) {
                            if (!exists) return;
                            $(this).trigger('click');
                            $fotostrana.missingElement('#surfPopup.surfMinigameMarket .popupClose', function(exists) {
                                if (!exists) return;
                                $(this).trigger('click');
                            });
                        });
                    });
                return button;
            };
            miniAward()
                .attr({ title: 'Взять без игры' })
                .tooltip()
                .appendTo(this);
            // Если есть возможность, то дублируем кнопку
            var container = $('#surfPopup .minigameDoubleContainer');
            if (container.length > 0) {
                var cell = $('<div class="minigameDoubleCell" />').prependTo(container);
                miniAward()
                    .attr({ title: $(this).find('.surfMinigameTitle').html() })
                    .tooltip()
                    .appendTo(cell);
            }
        }
        /**
         * Добавляем кнопку бонуса в вулкане
         */
        , volcanoPrizeClick: function() {
            // Отыщем, есть ли ссылка на прохождение игры
            var findGame = $(this).find('.js_get-prize');
            if (findGame.length == 0) return;

            var button = $('<div class="miniAward surfArrow bottom" />')
                .attr({ title: 'Взять без игры' })
                .tooltip()
                .appendTo(this)
                .click(function(e) {
                    var app = window.surf.Volcano;
                    var prizeGame = new app.PrizeGameView();
                    prizeGame.showPrize();
                });
        }
        /**
         * Кнопки для перемещения навыков в вулкане
         */
        , volcanoImpMove: function() {
            var self = $fotostrana;

            $('<div class="miniAward surfArrow bottom" />')
                .attr({ title: 'Вниз' })
                .tooltip()
                .appendTo(this)
                .click(function(e) {
                    $('#impruvements-block .imp .img').unbind('mouseenter').click(function(e) {
                        var app = window.surf.Volcano;
                        var impruvementId = $(this).data('impruvementId');
                        var square = app.improvementsView.collection.get(impruvementId);
                        app.improvementsView.onDragStart(square);
                        var result = app.activeImprovementsView.onDrop(square);
                        app.improvementsView.onDragEnd(result, square);
                        setTimeout(function() {
                            location.replace(location.href);
                        }, self.missingPause);
                    });
                });

            $('<div class="miniAward surfArrow top" />')
                .attr({ title: 'Вверх' })
                .tooltip()
                .appendTo(this)
                .click(function(e) {
                    $('#active-impruvements-block .imp .img').unbind('mouseenter').click(function(e) {
                        var app = window.surf.Volcano;
                        var impruvementId = $(this).data('impruvementId');
                        var square = app.activeImprovementsView.collection.get(impruvementId);
                        app.activeImprovementsView.onDragStart(square);
                        var result = app.improvementsView.onDrop(square);
                        app.activeImprovementsView.onDragEnd(result, square);
                        setTimeout(function() {
                            location.replace(location.href);
                        }, self.missingPause);
                    });
                });
        }
        /**
         * Показать количество заплывов
         */
        , volcanoRunShow: function() {
            var self = this;
            console.log('volcanoRunShow');

            $fotostrana.missingElement('.auto-buttons button', function(exists) {
                console.log('auto-buttons', exists);
                if (!exists) return;

                var modeList = [ 'reliably', 'riskily' ];
                modeList.forEach(function(mode) {
                    var data = self.volcanoRunCount(mode);
                    var button = $('.auto-buttons .js_on-' + mode);
                    var color = button.attr('class').match(/b_grd-button--\w+/);
                    if (color) {
                        color = color[0];
                    }
                    button.click(function(e) {
                        var createVolcanoRun = function() {
                            self.volcanoRunShow();
                        };
                        setTimeout(createVolcanoRun, self.missingPause);
                    });
                    var opener = $('<button />')
                        .appendTo('.auto-buttons .content')
                        .addClass('b_grd-button ' + color)
                        .attr({ title: data.title })
                        .tooltip()
                        .text(data.step)
                        .data('popup', data)
                        .click(function(e) {
                            var data = $(this).data('popup');
                            surf.popup.show(data.html, data.css_class, data.title);
                        });
                });

                //surf.popup.show(data.html, data.css_class, data.title);
            });
        }
        /**
         * Посчитать количество заплывов
         */
        , volcanoRunCount: function(mode) {
            var app = window.surf.Volcano;
            var step = 0;
            var runCount = 0;
            var message = [];

            var countWithCase = function(value) {
                return $$.numberWithCase(value, 'навык', 'навыка', 'навыков').replace(' ', '</td><td>');
            };

            // points - рискованно, possibility - надежно
            var sortBy = (mode == 'riskily') ? 'points' : 'possibility';
            var titleBy = (mode == 'riskily') ? 'Рискованно' : 'Надежно';

            // Берем навыки и сортируем "рискованно"
            var prepareSkills = new app.SkillsCollection(app.skillsView.collection.toJSON());
            var beforeCount = countWithCase(prepareSkills.length);
            var before = ('На старте</td><td></td><td>—</td><td>' + beforeCount);

            while (prepareSkills.length >= 10) {
                var best = prepareSkills.getBestSkills(sortBy);
                // удаляем по одному лучшему навыку
                best.forEach(function(item, index) {
                    var prepareItem = prepareSkills.get(item.id);
                    var newCount = (prepareItem.attributes.count * 1 - 1);
                    //console.log('%o)  %s item [%o] from %o to %o  --  %o', (index + 1), mode, item.id * 1, prepareItem.attributes.count * 1, newCount, prepareItem.attributes.title);
                    if (newCount > 0) {
                        prepareItem.attributes.count = newCount;
                    } else {
                        prepareSkills.remove(item.id);
                    }
                });
                step++;
                //var info = [];
                //prepareSkills.models.forEach(function(elem) {
                //    info.push({ id: elem.attributes.id * 1, count: elem.attributes.count * 1, title: elem.attributes.title });
                //});
                //console.log('после заплыва [%o] %s = %o', step, mode, info);
                var row = {
                    step: step,
                    count: countWithCase(prepareSkills.length)
                };
                message.push($$.template('После заплыва</td><td>{step}</td><td>—</td><td>{count}', row));
            }
            //console.log(message);
            var html = { before: before, message: $$.join(message, '</td></tr><tr><td>') };
            var data = {
                html: $$.template(surfVolcanoRunTable, html),
                css_class: 'volcanoRunCount surfPopup surfPopup-dark questPopup surfPopup-blueTitle surfPopup-w600',
                title: ('Количество заплывов. ' + titleBy),
                step: step
            };
            return data;
        }
        /**
         * Взять лучший комплект в сундуке
         */
        , icoChest: ('.surfProfile .profExtras .surfProfileIco.chest')
        , chestInventory: function() {
            if (!this.isSportsPage())
                return;

            var self = this;

            // Кнопка, чтобы снять все
            var createRemoveButton = function() {
                console.log('createRemoveButton');
                $(self.icoChest).click(function(e) {
                    var removePack = function() {
                        $fotostrana.missingElement('#surfPopup.surfInventoryPopup #dressTopBtn', function(exists) {
                            if (!exists) return;
                            var newB = $('<div class="sButton big type3" />')
                                .insertAfter(this)
                                .text(' Снять все ')
                                .prepend('<div class="surfInvIco surfInvIco-removePack" />')
                                .click(function(e) {
                                    var inventories = [
                                        '.surfInvChestContent .surfInvClothes .surfInvItem.isOn',
                                        '.surfInvChestContent .surfInvArtefacts .surfInvItem.isOn',
                                        '.surfInvChestContent .surfInvAddons .surfInvItem.isOn'
                                    ];
                                    var nodes = $($$.join(inventories, ', '));
                                    var index = 0;
                                    var removeTimer = setInterval(function() {
                                        nodes.eq(index).trigger('click');
                                        if (++index >= nodes.length) {
                                            clearInterval(removeTimer);
                                            $('#surfPopup .popupClose').trigger('click');
                                        }
                                    }, self.missingPause / 8);
                                });
                        });
                    };
                    // Задержка, потому что на момент клика старый #surfPopup ещё не уничтожен
                    setTimeout(removePack, self.missingPause * 3 / 4);
                });
            };

            // При создании кнопки заново навесим обработчик
            surf.profile.updateInfoOLD = surf.profile.updateInfo;
            surf.profile.updateInfo = function() {
                this.updateInfoOLD.apply(this, arguments);
                setTimeout(createRemoveButton, self.missingPause);
            };

            createRemoveButton();

            // Кнопка лучшего комплекта
            var chestButton = $('<div class="sFriend">')
                .attr({ title: 'Лучший комплект' })
                .tooltip()
                .append('<em class="surfProfileIco chest image autoDress">')
                .prependTo('.surfFriendsBlock .surfScroll')
                .click(function(e) {
                    $fotostrana.missingElement(self.icoChest, function(exists) {
                        if (!exists) return;
                        $(this).trigger('click');
                        $fotostrana.missingElement('#surfPopup #dressTopBtn', '#surfPopup .popupTitle', function(exists) {
                            if (!exists) return;
                            //surf.inventory.popup.dressTopClick();
                            //surf.inventory.dressTopEquip(true);
                            $(this).trigger('click');
                            //$('#surfPopup .popupClose').trigger('click');
                        });
                    });
                });
            //$fotostrana.missingElement('#surfCup .surfShopMinigame', $fotostrana.minigameWindowClick);
        }
        /**
         * Взять ежедневный бонус в кубке по серфингу
         */
        , cupBonus: function() {
            if (!this.isCupPage())
                return;

            $fotostrana.missingElement('#surfCup .surfShopMinigame', $fotostrana.minigameWindowClick);
        }
        /**
         * Взять ежедневный бонус в вулкане
         */
        , volcanoBonus: function() {
            if (!this.isVolcanoPage())
                return;

            // Ежедневный бесплатный бонус
            $fotostrana.missingElement('#volcano-prize .get-prize-block', $fotostrana.volcanoPrizeClick);

            $fotostrana.missingElement('#volcano-app .awards .content', $fotostrana.volcanoImpMove);
        }
        /**
         * Ждём, пока отрисуется элемент, и выполняем действия
         */
        , missingElement: function(selector, mouseOver, callback) {
            // Аргумент mouseOver может отсутствовать, сразу callback
            var method;
            if ($$.isFunction(mouseOver)) {
                method = mouseOver;
            } else {
                var missingPause = this.missingPause;
                $(mouseOver).trigger('mouseenter');
                method = function(exists) {
                    setTimeout($$.createDelegate(function() {
                        $(mouseOver).trigger('mouseleave');
                        callback.call(this, exists);
                    }, this), missingPause);
                };
            }
            $$.missingElement(selector, method, this.missingPeriod);
        }
        /**
         * Запустим систему в работу
         */
        , startSports: function() {
            this.styleSurf();
            this.chestInventory();
            this.schoolBonus();
            this.minigameBonus();
            this.cupBonus();
            this.volcanoBonus();
            this.volcanoRunShow();
            this.leaveSportsRound();
        }
    });
    unsafeWindow.$fotostrana.startSports();
})(paramWindow);