// ==UserScript==
// @name Fotostrana Sports
// @namespace scriptomatika
// @author mouse-karaganda
// @description Интерфейс на страницах Surf Rider
// @require https://greasyfork.org/scripts/379902-include-tools/code/Include%20Tools.js
// @version 1.4
// @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 = (
'<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>'
);
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>'
);
$$.extend(unsafeWindow.$fotostrana, {
/**
* Период ожидания для скриптов (в секундах)
*/
missingPeriod: 180
/**
* Определим, что мы находимся на страничке питомца
*/
, 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() {
return /\.ru\/sports\/school/i.test(location.href);
}
/**
* Стили для новых объектов
*/
, styleSurf: function() {
$$.renderStyle(
'.surfScrollWrap .miniAward, .surfShopMinigame .miniAward { position: absolute; border: 1px solid black; border-radius: 5px; background-position: -68px 0; width: 18px; height: 18px; }',
'.surfScrollWrap .miniAward:hover, .surfShopMinigame .miniAward:hover { border-color: red; }',
'.surfScrollWrap .miniAward { left: auto !important; right: -15px; bottom: -7px !important; }',
'.surfShopMinigame .miniAward { right: 165px; 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; }'
);
}
/**
* Быстрые настройки питомца
*/
, quickPetSettings: function() {
$fotostrana.missingElement('#surfSchool .surfTabs', function(exists) {
////a1.s.fsimg.ru/app/fs2pet/img/icons-20.png
});
}
/**
* Взять ежедневный бонус в школе серферов
*/
, schoolBonus: function() {
if (!this.isSchoolPage())
return;
$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);
$fotostrana.missingElement('#surfPopup.questPopup', function(exists) {
if (!exists) return;
// Забираем бонус
surf.school.getBuildingBonus(buildingId);
// Сразу закроем окно
var _this = this;
setTimeout(function() {
$(_this).find('.popupClose').trigger('click');
}, 2000);
});
};
// Бонусы братства
var brothershipBonus = function(e) {
e.preventDefault();
var buildingId = $(this).data('buildingId');
surf.school.openBuilding(buildingId);
$fotostrana.missingElement('#surfPopup.questPopup', function(exists) {
if (!exists) return;
// Забираем все бонусы
surf.school.getSchoolBonus(2001);
surf.school.getSchoolBonus(2002);
surf.school.getSchoolBonus(2003);
surf.school.getSchoolBonus(2005);
// Сразу закроем окно
var _this = this;
setTimeout(function() {
$(_this).find('.popupClose').trigger('click');
}, 2000);
});
};
// Подсказка для допингов и навыков
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;
$fotostrana.missingElement('#surfFriendsWrap .dailyGames', function(exists) {
if (!exists) return;
$(this).click(function(e) {
$fotostrana.missingElement('#surfPopup.surfMinigamesPopup', function(exists) {
if (!exists) return;
// Добавляем к каждой игре кнопку бонуса
$(this).find('.surfMinigame').each($fotostrana.minigameWindowClick);
});
});
});
}
/**
* Покинуть заплыв автоматически
*/
, 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 = $('<div class="miniAward" />')
.addClass('surfArrow bottom')
.attr({ title: 'Взять без игры' })
.tooltip()
.data({ 'gameid': gameId })
.appendTo(this)
.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');
});
});
});
}
/**
* Взять лучший комплект в сундуке
*/
, chestInventory: function() {
if (!this.isSportsPage())
return;
// Создаем новую кнопку
var chestButton = $('<div class="sFriend">')
.attr({ title: 'Лучший комплект' })
.tooltip()
.append('<em class="surfProfileIco chest image autoDress">')
.prependTo('.surfFriendsBlock .surfScroll')
.click(function(e) {
$fotostrana.missingElement('.surfProfile .profExtras .surfProfileIco.chest', function(exists) {
if (!exists) return;
$(this).trigger('click');
$fotostrana.missingElement('#surfPopup #dressTopBtn', function(exists) {
if (!exists) return;
var _this = this;
var close = function() {
$(_this).trigger('click');
};
setTimeout(close, 2000);
//$('#surfPopup.surfInventoryPopup .popupClose').trigger('click');
});
});
});
//$fotostrana.missingElement('#surfCup .surfShopMinigame', $fotostrana.minigameWindowClick);
}
/**
* Взять ежедневный бонус в кубке по серфингу
*/
, cupBonus: function() {
if (!this.isCupPage())
return;
$fotostrana.missingElement('#surfCup .surfShopMinigame', $fotostrana.minigameWindowClick);
}
/**
* Ждём, пока отрисуется элемент, и выполняем действия
*/
, missingElement: function(selector, callback) {
$$.missingElement(selector, callback, this.missingPeriod);
}
/**
* Запустим систему в работу
*/
, startSports: function() {
this.styleSurf();
this.chestInventory();
this.schoolBonus();
this.minigameBonus();
this.cupBonus();
this.leaveSportsRound();
}
});
unsafeWindow.$fotostrana.startSports();
})(paramWindow);