// ==UserScript==
// @name Fotostrana Sports
// @namespace scriptomatika
// @author mouse-karaganda
// @description Интерфейс на страницах Surf Rider
// @version 1.23
// @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,
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(
'.surfScrollWrap .miniAward, .surfShopMinigame .miniAward, #volcano-prize .miniAward { position: absolute; border: 1px solid black; border-radius: 5px; background-position: -68px 0; width: 18px; height: 18px; z-index: 1; }',
'.surfScrollWrap .miniAward:hover, .surfShopMinigame .miniAward:hover, #volcano-prize .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; }',
'#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; }'
);
}
/**
* Быстрые настройки питомца
*/
, 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;
// Кнопка для мини-игр
button = $('<div class="daylyGamesPerson atlantis" />')
.appendTo('.surfScrollWrap.questsWrap .surfScroll')
.wrap('<div class="sQuestIco" />')
.attr({ title: 'Мини-игры' })
.tooltip()
.click(function(e) {
$('#surfFriendsWrap .dailyGames').trigger('mouseenter').trigger('click');
});
// Кнопка для задир
var button = $('<div class="daylyGamesPerson extreme" />')
.appendTo('.surfScrollWrap.questsWrap .surfScroll')
.wrap('<div class="sQuestIco" />')
.attr({ title: 'Экстремальные задиры' })
.tooltip()
.click(function(e) {
location.href = ('//fotostrana.ru/sports/extremeEvent/');
});
// Кнопка для битвы на равных
var button = $('<div class="daylyGamesPerson rascally" />')
.appendTo('.surfScrollWrap.questsWrap .surfScroll')
.wrap('<div class="sQuestIco" />')
.attr({ title: 'Битва на равных' })
.tooltip()
.click(function(e) {
location.href = ('//fotostrana.ru/sports/honestEvent/');
});
// Быстрые кнопки в открытом окне
$fotostrana.missingElement('#surfFriendsWrap .dailyGames', function(exists) {
if (!exists) return;
$(this).click(function(e) {
$fotostrana.missingElement('#surfPopup.surfMinigamesPopup', '.popupTitle', function(exists) {
if (!exists) return;
// Подготовим контейнер для дублей
$('<div class="minigameDoubleContainer" />')
.prependTo($(this).find('.surfScrollWrap'));
// Добавляем к каждой игре кнопку бонуса
$(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 = 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 prizeGame = new window.surf.Volcano.PrizeGameView();
prizeGame.showPrize();
});
}
/**
* Взять лучший комплект в сундуке
*/
, 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()) {
$fotostrana.missingElement('#surfCup .surfShopMinigame', $fotostrana.minigameWindowClick);
}
if (this.isVolcanoPage()) {
$fotostrana.missingElement('#volcano-prize .get-prize-block', $fotostrana.volcanoPrizeClick);
}
}
/**
* Ждём, пока отрисуется элемент, и выполняем действия
*/
, 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.leaveSportsRound();
}
});
unsafeWindow.$fotostrana.startSports();
})(paramWindow);