FCup Script

This script aims to improve the game appearance and increase your gaming experience by adding new features. Under the MIT license the script is reproduced and further distributed. Copyright: Criyessei | mot33

目前为 2022-03-13 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name FCup Script
  3.  
  4. // @description This script aims to improve the game appearance and increase your gaming experience by adding new features. Under the MIT license the script is reproduced and further distributed. Copyright: Criyessei | mot33
  5.  
  6. // @version 3.7.1.4
  7. // @icon https://i.ibb.co/tJC5RX3/HFWRRt6.png
  8.  
  9. // @namespace https://greasyfork.org/users/83290
  10. // @author Criyessei | mot33
  11.  
  12. // @homepage https://www.fcup-tools.de/tool
  13. // @supportURL https://forum.fussballcup.de/showthread.php?t=417372
  14.  
  15. // @include /^https?:\/\/(futbolcup.net|fussballcup.(de|at)|futbolcup.pl|footcup.fr|footballcup.nl).+/
  16.  
  17. // @require https://code.jquery.com/jquery-3.3.1.min.js
  18. // @require https://code.jquery.com/ui/1.12.1/jquery-ui.min.js
  19. // @require https://greasyfork.org/scripts/441421-t%C5%82umaczenia/code/T%C5%82umaczenia.js?version=1027588
  20.  
  21. // @compatible chrome
  22. // @compatible firefox
  23. // @compatible opera
  24.  
  25. // @connect greasyfork.org
  26.  
  27. // @grant GM_getValue
  28. // @grant GM_setValue
  29. // @grant GM_deleteValue
  30. // @grant GM_listValues
  31. // @grant GM_addStyle
  32. // @grant GM_xmlhttpRequest
  33. // @grant unsafeWindow
  34.  
  35. // @license MIT
  36.  
  37. // @run-at document-body
  38. // @noframes
  39. // ==/UserScript==
  40.  
  41. /* eslint no-eval: 0, no-implicit-globals: 0, no-native-reassign: 0, curly: 0, no-proto: 0 */
  42.  
  43. /* global $, currentLive, worldId, toolTipObj, plObj, SelectBox, closeFocus, toolPipe*/ //jquery script and Game veriables
  44.  
  45. /* other dependencies game functions: (these functions will be modified)
  46. 1. showServerTime: Necessary to take the server's time. [Temporary Modify]
  47. 2. updateLayout: Necessary to understand that the page has changed and to detect that goals have been scored in other matches on the live match page. [Permanent Modify]
  48. 3. Live: Neccessary to get old or new match events and to detect when the match is end on the live match page. [Permanent Modify]
  49. 4. openCard: Necessary to display captain image. [Permanent Modify]
  50. */
  51.  
  52. /* global Translate */ //Translation.js
  53.  
  54. "use strict";
  55.  
  56. if(location.protocol!='https:'){ //Routing to secure protocol
  57. let pageHref = location.href;
  58. location.href = 'https'+pageHref.substring(pageHref.indexOf(':'));
  59. return;
  60. }
  61. else if(location.search.indexOf('action=logout')!=-1){
  62. location.href = location.origin; //Go main page
  63. return;
  64. }
  65.  
  66. let serversDatas = {
  67. "tr":{
  68. "flag" : "TUR",
  69. "language" : "Turkish",
  70. "footballerPositions" : ["KL", "DD", "DI", "OD", "OL", "OR", "OH", "FO"],
  71. "leagues" : [
  72. "2. Amatör Lig",
  73. "1. Amatör Lig",
  74. "Süper Amatör Lig",
  75. "Bölgesel Amatör Lig",
  76. "TFF 3.Lig",
  77. "TFF 2.Lig",
  78. "Spor Toto 1.Lig",
  79. "Spor Toto Süper Lig"
  80. ],
  81. "replaceClubName" : "'den Profil",
  82. "ScriptAuthorClubId" : "670524",
  83. "ClubExchange" : "Kulüp Değiştirme",
  84. "bidTexts" : {
  85. 'accept': 'kabul edildi',
  86. 'reject': 'reddedildi',
  87. 'read' : 'okundu',
  88. 'new' : 'yeni'
  89. },
  90. 'news' : {
  91. "youngPlayer": {"title":'Genç Oyuncu',"beforeName":"yetiyor.","afterName":"Detaylı incele"},
  92. "increaseBid": {"title":"Transfer Pazarı","control":"tarafından geçildi.","beforeName":"Transfer Pazarı","afterName":"için transfer teklifin"},
  93. "sellPlayer" : {"title":"Assistent: Transfer Pazarı","control":"yıllık kontrat imzaladı","beforeName":"</h2>","afterName":", <div"}
  94. },
  95. "ageDates" : [26483328, 26527104, 26570880, 26614656, 26658432, 26702208, 26746104, 26789880, 26833656, 26877432, 26921208, 26964984, 27008760, 27052536, 27096312, 27140088, 27183864, 27227640, 27271416, 27315192, 27358968, 27402744, 27446520, 27490296, 27534072, 27577848, 27621624, 27665400, 27709176, 27752952, 27796728, 27840504, 27884280, 27928056, 27971832, 28015608, 28059384, 28103160, 28146936, 28190712, 28234488, 28278264, 28322040, 28365816, 28409592, 28453368, 28497144, 28540920, 28584696, 28628472, 28672248],
  96. },
  97. "de":{
  98. "flag" : "DEU",
  99. "language" : "German", /*The game language*/
  100. "footballerPositions" : ["TW", "AV", "IV", "DM", "LM", "RM", "OM", "ST"],
  101. "leagues" : [
  102. "Kreisliga",
  103. "Landesliga",
  104. "Verbandsliga",
  105. "Oberliga",
  106. "Regionalliga",
  107. "3. Liga",
  108. "2. Bundesliga",
  109. "1. Bundesliga"
  110. ],
  111. "replaceClubName" : "Profil von",
  112. "ScriptAuthorClubId" : "1286060",
  113. "ClubExchange" : "Vereinswechsel",
  114. "bidTexts" : {
  115. 'accept': 'akzeptiert',
  116. 'reject': 'abgelehnt',
  117. 'read' : 'gelesen',
  118. 'new' : 'neu'
  119. },
  120. 'news' : {
  121. "youngPlayer": {"title":'Jugendspieler',"beforeName":"diesen ","afterName":" mal"},
  122. "increaseBid": {"title":"Transfermarkt","control":"überboten","beforeName":"für ","afterName":" wurde"},
  123. "sellPlayer" : {"title":"Assistent: Transfermarkt","control":"ausgehandelt","beforeName":"Spieler ","afterName":" hat"}
  124. },
  125. "ageDates" : [26402796, 26446632, 26490408, 26534184, 26579400, 26621736, 26665512, 26709288, 26753004, 26796780,26840676,26884452,26928228,26972004,27015780,27059556,27103332,27147108,27190884,27234660,27278436,27322212, 27365988, 27409764, 27453540, 27497316, 27541092, 27584868, 27628644, 27672420, 27716196, 27759972, 27803748, 27847524, 27891300, 27935076, 27978852, 28022628, 28066404, 28110180, 28153956, 28197732, 28241508, 28285284, 28329060, 28372836, 28416612, 28460388, 28504164, 28547940, 28591716, 28635492, 28679268, 28723044, 28766820, 28810596, 28854372, 28898148, 28941924, 28985700, 29029476, 29073252],
  126. },
  127. "at":{
  128. "flag" : "AUT",
  129. "language" : "German",
  130. "footballerPositions" : ["TW", "AV", "IV", "DM", "LM", "RM", "OM", "ST"],
  131. "leagues" : [
  132. "2. Klasse",
  133. "1. Klasse",
  134. "Gebietsliga",
  135. "2. Landesliga",
  136. "Landesliga",
  137. "Regionalliga",
  138. "Erste Liga",
  139. "Österreichische Bundesliga"
  140. ],
  141. "replaceClubName" : "Profil von",
  142. "ScriptAuthorClubId" : "1510674",
  143. "ClubExchange" : "Vereinswechsel",
  144. "bidTexts" : {
  145. 'accept': 'akzeptiert',
  146. 'reject': 'abgelehnt',
  147. 'read' : 'gelesen',
  148. 'new' : 'neu'
  149. },
  150. 'news' : {
  151. "youngPlayer": {"title":'Jugendspieler',"beforeName":"diesen ","afterName":" mal"},
  152. "increaseBid": {"title":"Transfermarkt","control":"überboten","beforeName":"für ","afterName":" wurde"},
  153. "sellPlayer" : {"title":"Assistent: Transfermarkt","control":"ausgehandelt","beforeName":"Spieler ","afterName":" hat"}
  154. },
  155. "ageDates" : [26542884,26588100,26630436,26674212,26717988,26761764,26805540, 26849316, 26893092, 26936868, 26980644, 27024420, 27068196, 27111972, 27155748, 27199524, 27243300, 27287076, 27330852, 27374628, 27418404, 27462180, 27505956, 27549732, 27593508, 27637284, 27681060, 27724836, 27768612, 27812388, 27856164, 27899940, 27943716, 27987492, 28031268, 28075044, 28118820, 28162596, 28206372, 28250148, 28293924, 28337700, 28381476, 28425252, 28469028, 28512804, 28556580],
  156. },
  157. "pl":{
  158. "flag" : "POL",
  159. "language" : "Polish",
  160. "footballerPositions" : ["BR", "OZ", "OŚ", "DP", "LP", "PP", "OP","N"],
  161. "leagues" : [
  162. "Klasa B",
  163. "Klasa A",
  164. "Liga okręgowa",
  165. "4 Liga",
  166. "3 Liga",
  167. "2 Liga",
  168. "1 Liga",
  169. "Ekstraklasa"
  170. ],
  171. "replaceClubName" : "Profil",
  172. "ScriptAuthorClubId" : "2074",
  173. "ClubExchange" : "Zmienia klub",
  174. "bidTexts" : {
  175. 'accept': 'Zaakceptowane',
  176. 'reject': 'Odrzucone',
  177. 'read' : 'przeczytana',
  178. 'new' : 'nowy'
  179. },
  180. 'news' : {
  181. "youngPlayer": {"title":'Junior',"beforeName":"dokładniej","afterName":"i zaproś"},
  182. "increaseBid": {"title":"Rynek transferowy","control":"została przebita przez","beforeName":"spłaty za","afterName":"została"},
  183. "sellPlayer" : {"title":"Assistent: Rynek transferowy","control":"periodzie rynku transferowego","beforeName":"</h2>","afterName":"wynegocjował"}
  184. },
  185. "ageDates" : [26196708, 26240484, 26284260, 26328036, 26371812, 26415588, 26459364, 26503140, 26546916, 26590692, 26634468, 26678244, 26722020, 26765796, 26809572, 26853348, 26897124, 26940900, 26984676, 27028452, 27072228, 27116004, 27159780, 27203556, 27247332, 27291108, 27334884, 27378660, 27422436, 27466212, 27509988, 27553764, 27597540, 27641316, 27685092, 27728868, 27772644, 27816420, 27860196, 27903972, 27947748, 27991524, 28035300, 28079076, 28122852, 28166628, 28210404, 28254180, 28297956, 28341732, 28385508, 28429284, 28473060, 28516836, 28560612, 28604388, 28648164, 28691940, 28735716, 28779492, 28823268, 28867044, 28910820, 28954596, 28998372, 29042148, 29085924, 29129700, 29173476, 29217252, 29261028, 29304804, 29348580, 29392356, 29436132, 29479908, 29523684, 29567460, 29611236, 29655012, 29698788, 29742564, 29786340, 29830116, 29873892],
  186.  
  187. },
  188. "fr":{
  189. "flag" : "FRA",
  190. "language" : "French",
  191. "footballerPositions" : ["GB", "DL", "DC", "Mdf", "MG", "MD", "MO", "BT"],
  192. "leagues" : [
  193. "PH",
  194. "DHR",
  195. "DH",
  196. "CFA 2",
  197. "CFA",
  198. "National",
  199. "Ligue 2",
  200. "Ligue 1"
  201. ],
  202. "replaceClubName" : "Profil de",
  203. "ScriptAuthorClubId" : "169948",
  204. "ClubExchange" : "Clubs Changer",
  205. "bidTexts" : {
  206. 'accept': 'approuvé',
  207. 'reject': 'rejeté',
  208. 'read' : 'lu',
  209. 'new' : 'nouveau'
  210. },
  211. 'news' : {
  212. "youngPlayer": {"title":'Jeune joueur',"beforeName":"d'œil sur ce","afterName":"..."},
  213. "increaseBid": undefined,
  214. "sellPlayer" : undefined
  215. },
  216. "ageDates" : [25733556, 25778772, 25821109, 25864884, 25908660, 25952436, 25996212, 26039988, 26083764, 26127540, 26171316, 26215092, 26258868, 26302644, 26346420, 26390196, 26433972, 26477748, 26521524, 26565300, 26609076, 26652852, 26696628, 26740404, 26784180, 26827956, 26871732, 26915508, 26959284, 27003060, 27046836, 27090612, 27134388, 27178164, 27221940, 27265716, 27309492, 27353268, 27397044, 27440820, 27484596, 27528372, 27572148, 27615924, 27659700, 27703476, 27747252, 27791028, 27834804, 27878580, 27922356],
  217. },
  218. "nl":{
  219. "flag" : "NLD",
  220. "language" : "Dutch",
  221. "footballerPositions" : ["GK", "VV", "CV", "DM", "LM", "RM", "AM", "AV"],
  222. "leagues" : [
  223. "4e Klasse",
  224. "3e Klasse",
  225. "2e Klasse",
  226. "1e Klasse",
  227. "Hoofdklasse",
  228. "Topklasse",
  229. "1e Divisie",
  230. "Eredivisie"
  231. ],
  232. "replaceClubName" : "Profiel van",
  233. "ScriptAuthorClubId" : "108310",
  234. //Aşağıdaki kısım düzeltilmeli!
  235. "ClubExchange" : "Kulüp Değiştirme",
  236. "bidTexts" : {
  237. 'accept': 'Geaccepteerd',
  238. 'reject': 'Afgewezen',
  239. 'read' : 'Gelezen',
  240. 'new' : 'Nieuw'
  241. },
  242. 'news' : {
  243. "youngPlayer": {"title":'Jeugdspeler',"beforeName":"De speler","afterName":"zou zeker"},
  244. "increaseBid": {"title":"Transfer markt","control":"overboden","beforeName":"transferbod op","afterName":"werd door"},
  245. "sellPlayer" : undefined,
  246. },
  247. "ageDates" : undefined
  248. }
  249. };
  250. let GetText = (key, opt={tag:1})=>Translate.getText(key, opt);
  251.  
  252. class Page{
  253. constructor(name, page_selector,run=null,sub_pages=null,parent_page=null){
  254. this.name = name;
  255. if(parent_page!==null) this.parent_page = parent_page;
  256. this.page_selector = page_selector;
  257. if(run!=null) this.run = run;
  258. this.features = [];
  259. this.features.getByName = function(n){
  260. return this.find(f=>f.name==n);
  261. };
  262. if(Array.isArray(sub_pages) && sub_pages.length) this.sub_pages = sub_pages;
  263.  
  264. }
  265. addFeature(feature){
  266. this.features.push(feature);
  267. }
  268. getActiveFeatures(){
  269. return this.features.filter(f=>f.active);
  270. }
  271. parentsByName(name){
  272. let temp = this.parent_page;
  273. while(temp instanceof Page && temp.name!=name) temp = temp.parent_page;
  274. return temp;
  275. }
  276. findPath(){
  277. let temp = this.parent_page,
  278. path = this.name;
  279. while(temp instanceof Page){
  280. path=temp.name+"->"+path;
  281. temp=temp.parent_page;
  282. }
  283. return path;
  284. }
  285. }
  286.  
  287. let Game = new (class{
  288. constructor(){
  289. this.currentPage = null;
  290. this.pages = [];
  291. this.pages.getByName = function(name){
  292. let names = name.split('->');
  293. if(names.length==1) return this.find(p=>p.name==names[0]);
  294. try{
  295. return eval("this.getByName('"+names.join("').sub_pages.getByName('")+"')");
  296. }
  297. catch(err){
  298. return undefined;
  299. }
  300. };
  301. this.pages.add = function(name, page_selector, run=null, sub_pages=null, parent_page=null){
  302. let page = (parent_page instanceof Page?parent_page.sub_pages:this).getByName(name);
  303. if(page instanceof Page) throw new Error(`A page with this name(${name}) was previously created in ${parent_page===null?'game page as top page':'sub pages of '+parent_page.name + ' page'}`);
  304.  
  305. page = new Page(name, page_selector, run, sub_pages, parent_page);
  306. if(Array.isArray(sub_pages)){
  307. if(!Array.isArray(sub_pages[0])) sub_pages=[sub_pages];
  308. page.sub_pages = sub_pages;
  309. page.sub_pages.getByName = Game.pages.getByName;
  310. page.sub_pages.forEach((sub_page,i)=>{
  311. page.sub_pages[i] = Game.pages.add(
  312. sub_page[0], //name
  313. sub_page[1], //page_selectort
  314. sub_page.length>2?sub_page[2]:null, //page run function
  315. sub_page.length>3?sub_page[3]:null, //page sub pages
  316. page
  317. )
  318. });
  319. }
  320. if(parent_page!==null) return page; //this page is sub page
  321. this.push(page);
  322. };
  323. this.link = new (function(){
  324. this.pr = {};
  325. this.on = function(a){
  326. if(!Array.isArray(a)) a = [a];
  327. for(let i=0,len=a.length;i<len;i++){
  328. for(let p in a[i]){
  329. let v=a[i][p];
  330. if(!Array.isArray(v)) v = [v];
  331. if(!(this.pr.hasOwnProperty(p) && v.includes(this.pr[p]))) return 0;
  332. }
  333. }
  334. return 1;
  335. }
  336. })();
  337. }
  338.  
  339. pageLoad(){// USE in async function: await PageLoad();
  340. return new Promise(function(res,rej){
  341. setTimeout(function(){
  342. if(!$('#body').hasClass('loading')) res(10);
  343. else{
  344. let counter=0,
  345. a = setInterval(function(){
  346. ++counter;
  347. if(!$('#body').hasClass('loading')){
  348. clearInterval(a);
  349. res(counter*50);
  350. }
  351. },50);
  352. }
  353. },10);
  354. });
  355. }
  356.  
  357. async initialConfigure(){
  358. delete this.__proto__.initialConfigure;
  359.  
  360. this.timeDifference = (
  361. await this.getInitialServerTime()
  362. + Math.round(Math.abs(window.performance.timing.responseEnd-window.performance.timing.requestStart)/2)
  363. + new Date().getTime()-window.performance.timing.responseEnd
  364. ) - new Date().getTime(); //Difference between server and pc
  365.  
  366. /*printServerTime();
  367. setInterval(printServerTime,1000);
  368. function printServerTime(){
  369. console.clear();
  370. console.log(
  371. 'Server Time: '+$('#server-time').text()+
  372. '\nTool Time : '+new Date(Game.getTime()).toLocaleTimeString()+
  373. '\nPC Time : '+new Date().toLocaleTimeString()
  374. );
  375. }*/
  376.  
  377. let z_index = parseInt($('#chatToggleBtn').css('z-index'));
  378. if(!isNaN(z_index)){
  379. let z_index_ = parseInt($('#feedback').css('z-index'))||0;
  380. if(z_index_<=z_index) $('#feedback').css('z-index',z_index+1);
  381. }
  382. }
  383.  
  384. giveNotification(NotificationType,Text){
  385. $('#feedback').prepend(
  386. `<p class="${NotificationType?'notice':'error'}" style="left: 0px;${NotificationType?'background:#1ba0de;border: 1px solid #000000;':''}">`+
  387. ` <span class="icon"></span>`+Text+
  388. `</p>`
  389. );
  390. $('#feedback p:not(.minified)').each(function(a,e){
  391. $(e).css('left',($(document).width() - $(e).outerWidth()) / 2);
  392. setTimeout(()=>{
  393. $(e).addClass('minified').css({left : 0});
  394. },4000);
  395. });
  396. $('#feedback p').each(function(key){
  397. if(key>19) {
  398. $(this).slideUp(function(){
  399. $(this).remove();
  400. });
  401. }
  402. });
  403. }
  404.  
  405. getInitialServerTime(){
  406. delete this.__proto__.getInitialServerTime;
  407. return new Promise(function(res,rej){
  408. $('<button id="TimeTrigger">').hide().appendTo('body').click(function(){
  409. $(this).off().remove();
  410. let server_time = JSON.parse($(this).attr('server_time'));
  411. Tool.modifyGameFunction('showServerTime',function(content){
  412. return content.substring(content.indexOf('/*{end}*/')+9);
  413. });
  414. res(server_time);
  415. });
  416. Tool.modifyGameFunction('showServerTime',function(content){
  417. return `$('#TimeTrigger').attr('server_time',
  418. (function getServerTime(args){
  419. args[1] = parseInt(args[1])-1; // month [0-11]
  420. return new Date(...args).getTime();
  421. })([...arguments])
  422. ).click();/*{end}*/` + content;
  423. });
  424. });
  425. }
  426. getTime(){
  427. return this.timeDifference+new Date().getTime();
  428. }
  429.  
  430. async detectPage(clear=true){
  431. if(clear) console.clear();
  432. console.log('Game Time: ' + new Date(this.getTime()).toLocaleString());
  433. await Game.pageLoad();
  434.  
  435. this.link.pr = location.hash.substring(location.hash.indexOf('?')+1).split('&').reduce((acc, i)=>{
  436. let parts = i.split('=');
  437. acc[parts[0]] = parts[1];
  438. return acc;
  439. }, {});
  440.  
  441. //Problem : https://forum.fussballcup.de/showpost.php?p=7513019&postcount=1
  442. $('#content table:has(.open-card)').each(function(){
  443. if($(this).width()>942){
  444. $(this).css({'display':'block','overflow-x':'auto'});
  445. }
  446. });
  447.  
  448. function find_page(pages){ //BFS Search
  449. if(!Array.isArray(pages) || !pages.length) return undefined;
  450. let page = pages.find(page=>{
  451. return Game.link.on(page.page_selector);
  452. });
  453. if(page!==undefined) return page;
  454. let pages_ = [];
  455. pages.filter(page=>{
  456. return page.sub_pages && Array.isArray(page.sub_pages) && page.sub_pages.length;
  457. }).forEach(page=>{
  458. pages_.push(...page.sub_pages);
  459. });
  460. return find_page(pages_);
  461. }
  462.  
  463. let prev_page = this.currentPage;
  464. this.currentPage = find_page(this.pages);
  465. console.log('Current Page : ' + (this.currentPage||{}).name+ (prev_page==null?"":"\nPrevious Page: " + prev_page.name));
  466.  
  467. if(prev_page instanceof Page){
  468. if(prev_page.name=="tournament"){
  469. if(this.currentPage.name!="tournament" && Tool.hasOwnProperty('tournaments_data')) delete Tool.tournaments_data;
  470. }
  471. else if(prev_page.findPath()=='live->match'){
  472. if(typeof unsafeWindow.timeout_1 != 'undefined') clearTimeout(unsafeWindow.timeout_1);
  473. }
  474.  
  475. //Özelliklerin olduğu tablo temizleniyor. Çünkü sayfa değiştirildi ve bu sayfada başka özellikler olabilir.
  476. Tool.featuresList.clear();
  477.  
  478. //Önceki sayfalardan kalan sayaçlar sıfırlanıyor.
  479. Tool.intervals.clear();
  480. }
  481.  
  482. if(this.currentPage == undefined){
  483. $('#featureList').after(
  484. `<p class="not-detected-info" style="color:red; font-weight:bold; text-align:center; border:1px dotted gray; border-radius:7px; margin:10px 0"${GetText('notdetected')}"</p>`
  485. );
  486. }
  487. else{
  488. $('#ScriptMenu .not-detected-info').remove();
  489.  
  490. if(typeof this.currentPage.run == 'function') this.currentPage.run();
  491.  
  492. this.currentPage.getActiveFeatures().forEach(f=>{
  493. f.work = false !== f.run();
  494. });
  495.  
  496. //Sayfalarda çalışan özelliklerin olduğu tablo gösteriliyor
  497. Tool.featuresList.show(this.currentPage.features);
  498. }
  499.  
  500. //Bir sonraki yaş atlamaya kalan süre sayaç şeklinde en alt menüye ekleniyor.
  501. (()=>{
  502. let sTime = Game.getTime(),
  503. ageDates = Tool.ageDates;
  504. if(!Array.isArray(ageDates) //Yaş atlama tarihleri mevcut değilse
  505. || $('#FutureAge').length //Geri sayım sayacı bulunuyorsa
  506. || ageDates[ageDates.length-1]*60000<sTime //Server zamanı, yaş atlama tarihlerinin sonuncusundan büyükse
  507. ) return;
  508. let nextAgeDate = ageDates.find(date=>date*60000>sTime);
  509. if(nextAgeDate === undefined){
  510. return;
  511. }
  512. nextAgeDate*=60000;
  513.  
  514. let remainingTime = parseInt((nextAgeDate-sTime)/1000);//Yaş atlamaya kalan saniye hesaplanıyor.
  515. $('#footer > div').css('width','300px');
  516. $('#footer > .server-infos').prepend(
  517. `<li style="padding: 4px 5px;font-size:12px;" title="${new Date(nextAgeDate).toLocaleString()}">`+
  518. ` ${GetText('NewAge')} : <label id="FutureAge">${SecToTime(remainingTime--)}</label>`+
  519. `</li>`
  520. );
  521. Tool.intervals.create(function(){ //eslint-disable-line no-loop-func
  522. $('#FutureAge').html(SecToTime(remainingTime--));
  523. if(remainingTime<1){
  524. $('#FutureAge').html('Yaş Atladı');
  525. this.delete();
  526. }
  527. },1000);
  528. })();
  529.  
  530. //Sayfanın düzeltildiği ana başlığa bildiriliyor.
  531. $('#content').find('h2').first().attr('Fixed',this.getTime());
  532. }
  533. startDetectingPageChanging(){
  534. delete this.__proto__.startDetectingPageChanging;
  535.  
  536. Tool.modifyGameFunction(//The function named updateLayout are needed update for the FCUP Script. Because when the page change, fcup script should work then.
  537. 'updateLayout',
  538. function(content){
  539. content = `\ntry{\nconsole.log("run updateLayout");`+ content + `\n}\ncatch(e){\nconsole.error('updateLayout: %o',e);}\n$('#ChangeContent').click();`;
  540. let idx = content.indexOf('scores.php?world');
  541. if(idx==-1) return content;
  542. let idx2 = content.substring(idx).search(/function\s*\(\s*transport/);
  543. if(idx2==-1) return content;
  544. idx = content.indexOf('{',idx+idx2);
  545. if(idx==-1) return content;
  546. ++idx;
  547. if(!Tool.hasOwnProperty('goalTrigger')) Tool.goalTrigger = 0;
  548. Tool.goalTrigger+=2;
  549. return content.substring(0,idx)+
  550. GetFuncContent(()=>{
  551. if($('#NewGoalCatcher').length){/*This codes were written by FCUP Script.*/
  552. try{
  553. var datas = JSON.parse(transport); /*eslint-disable-line no-undef*/
  554. for(let matchId in datas){
  555. let data = datas[matchId], score = $('#'+matchId+' > .score');
  556. if($('#MatchEndCatcher').length && data.status=="ended") $('#MatchEndCatcher').trigger('click', [matchId]);
  557. if(
  558. [data.home_goals, data.away_goals].find(v=>[null, undefined].includes(v))!==undefined ||
  559. data.home_goals==parseInt(score.find('.score-home').text()) &&
  560. data.away_goals==parseInt(score.find('.score-away').text())
  561. ){
  562. delete datas[matchId];
  563. continue;
  564. }
  565. }
  566. if(Object.keys(datas).length) $('#NewGoalCatcher').trigger('click', [datas]);
  567. }catch(err){ console.error(err);}
  568. }
  569. }) + content.substring(idx);
  570. }
  571. );
  572. }
  573.  
  574. getPage(url,querySelector=null,callBack=null,fail=0,layoutData=null){
  575. //let argNames = ['url','querySelector','callBack','fail','layoutData'];
  576. //console.log(`[getPage] ${url}, arguments: %o`, Array.from(arguments).slice(1).reduce((acc,i,idx)=>{acc[argNames[idx+1]]=i;return acc;},{}));
  577. return new Promise((res,rej)=>{
  578. $.get(url, function(response){
  579. let layout = url.indexOf('&layout=none')!=-1,
  580. page = $('<html>').html(layout?response.content:response);
  581.  
  582. let newSecureId = page.find('input[name="secureId"][type="hidden"]');
  583. if(newSecureId.length) $('body').find('input[name="secureId"][type="hidden"]').val(newSecureId.first().val());
  584.  
  585. if(layout && layoutData!=null){
  586. if(!Array.isArray(layoutData)){
  587. if(typeof layoutData != "string") throw new Error("layoutData must be array or string");
  588. layoutData = [layoutData];
  589. }
  590. let data = Object.entries(response).filter(i=>layoutData.includes(i[0])), r;
  591. if(querySelector != null && (r = data.find(i=>i[0]=='content'))!==undefined) r[1]=page.find(querySelector);
  592. res(Object.fromEntries(data));
  593. return;
  594. }
  595.  
  596. if(typeof querySelector!='string' || (querySelector=querySelector.trim())==""){
  597. res(page);
  598. return;
  599. }
  600. let e = page.find(querySelector);
  601. if(e.length!=0){
  602. if(typeof callBack=='function') callBack(e);
  603. res(e);
  604. return;
  605. }
  606. rej(new Error("Game->getPage->html->find->querySelector->length==0"));
  607. }).fail(function(){
  608. if(++fail<3){
  609. setTimeout(()=>{Game.getPage(url,querySelector,callBack,fail);},250);
  610. }
  611. else rej(new Error("Game->getPage->fail 3 times"));
  612. }).always(function(){
  613. });
  614. });
  615. }
  616. })();
  617.  
  618. //CATEGORY: TEAM
  619. Game.pages.add('squad',{
  620. 'module':'team','action':'squad'
  621. },function(){
  622. let comingPlayersCount = $('#players-table-changes > tbody').find('.open-card').length;
  623. if(comingPlayersCount.length) $('#players-table-changes').prev('h3').append(`<span style="float:right;">${comingPlayersCount} ${comingPlayersCount>1?GetText('Players'):GetText('Player')}</span>`);
  624. });
  625. Game.pages.add('formation',{
  626. 'module':'formation','action':'index'
  627. },function(){
  628. if($('#squad span.field-player').length>1 || $('#bank span.field-player').length>1 ){
  629. if($('#squad').find('span.field-player').length>1){
  630. Create('squad');
  631. $('#squad').css('height','auto');
  632. }
  633. if($('#bank').find('span.field-player').length>1) Create('bank',27);
  634. function Create(divId,addHeight=0){
  635. $('#'+divId).css('min-height',parseInt($('#'+divId).css('height'))+addHeight).find('>h3:first').after(
  636. '<p class="sorting_players">'+
  637. ' <label>'+
  638. ' <input type="radio" name="sorting_preference_'+divId+'" value="Position">'+GetText('Position')+
  639. ' </label>'+
  640. ' <label>'+
  641. ' <input type="radio" name="sorting_preference_'+divId+'" value="Strength">'+GetText('Strength')+
  642. ' </label>'+
  643. '</p>'+
  644. '<p class="filterByPositions"></p>'
  645. );
  646. let positions = [...new Set($('#'+divId).find('span.field-player').toArray().map(e=>$('>div >div.position',e).text()))],
  647. POSITIONS = Tool.footballerPositions;
  648. positions.sort((a,b)=> POSITIONS.findIndex(x=>x==a)-POSITIONS.findIndex(x=>x==b));
  649.  
  650. let filterByPositions = $('#'+divId+' > p.filterByPositions'),
  651. b_colors = ['green','#72ed72','#72ed72','#3f8a83','yellow','yellow','yellow','red'],
  652. f_colors = ['white','black','black','white','black','black','black','white'];
  653. positions.forEach(pos=>{
  654. let index = POSITIONS.findIndex(x=>x==pos);
  655. filterByPositions.append(`<span class="filter_position disHighlight" style="background-color:${b_colors[index]};color:${f_colors[index]};">${pos}</span>`);
  656. });
  657. filterByPositions.find('.filter_position').click(function(){
  658. $(this).css("pointer-events", "none");
  659. let isActive = !$(this).hasClass('not_active'),
  660. pos = $(this).text();
  661. $(this)[isActive?'addClass':'removeClass']('not_active').parents('div.ui-droppable').find('span.field-player').each(function(){
  662. if($('> div > div.position',this).text()==pos) $(this)[isActive?'slideUp':'slideDown'](200);
  663. });
  664. setTimeout(()=>$(this).css("pointer-events", ""),200);
  665. });
  666. }
  667. $('#squad,#bank').find('>.sorting_players input').click(function(){
  668. let div = $(this).parents('div.ui-droppable'),
  669. players = div.find('span.field-player'),
  670. positions = Tool.footballerPositions;
  671. switch(this.value){
  672. case 'Position':
  673. players.sort(function(a,b){
  674. let compare;
  675. if(compare = positions.findIndex(x=>x==$(' > div > div.position',a).text()) - positions.findIndex(x=>x==$(' > div > div.position',b).text())) return compare;
  676. else if(compare = parseInt($(' > div > div.strength',b).text())-parseInt($(' > div > div.strength',a).text())) return compare;
  677. return plObj[a.id.split('-')[2]].age-plObj[b.id.split('-')[2]].age;
  678. }).appendTo(div);
  679. break;
  680. case 'Strength':
  681. players.sort(function(a,b){
  682. let compare;
  683. if(compare = parseInt($(' > div > div.strength',b).text()) - parseInt($(' > div > div.strength',a).text())) return compare;
  684. else if(compare = positions.findIndex(x=>x==$(' > div > div.position',a).text()) - positions.findIndex(x=>x==$(' > div > div.position',b).text())) return compare;
  685. return plObj[a.id.split('-')[2]].age-plObj[b.id.split('-')[2]].age;
  686. }).appendTo(div);
  687. break;
  688. }
  689. });
  690.  
  691. let sorting_preferences = undefined || {squad:'Position',bank:'Strength'}
  692. $('#squad .sorting_players input[value="'+sorting_preferences.squad+'"]:first').click();
  693. $('#bank .sorting_players input[value="'+sorting_preferences.bank+'"]:first').click();
  694. }
  695.  
  696. if(true){ //To show the leadership values of football players
  697. $('#formation-select-captain > span > select > option:not([value="0"])').each(function(){
  698. let playerId = this.value;
  699. if(!plObj[playerId]) return true;
  700. let attr_leadership = parseInt(plObj[playerId].attr_leadership),
  701. text = $(this).html(),
  702. find = text.indexOf(')');
  703. if(find==-1) return true;
  704. $(this).html("(" + attr_leadership + ")" + text.substring(find+1));
  705. });
  706.  
  707. let selectedCaptain = plObj[$('#formation-select-captain > span > select > option:selected').val()];
  708. if(selectedCaptain){
  709. let attr_leadership = selectedCaptain.attr_leadership,
  710. text = $('#formation-select-captain > span > div.button > span.text').html(),
  711. find = text.indexOf(')');
  712. $('#formation-select-captain > span > div.button > span.text').html("(" + attr_leadership + ")" + text.substring(find+1));
  713. }
  714.  
  715. let li = $(SelectBox.instances[$('#formation-select-captain > span').attr('instance')].expand[0]).find('li') ;
  716. li.each(function(){
  717. let playerId = this.getAttribute('idvalue');
  718. if(!plObj[playerId]) return true;
  719. let attr_leadership = parseInt(plObj[playerId].attr_leadership),
  720. text = $(this).html(),
  721. find = text.indexOf(')');
  722. if(find==-1) return true;
  723. $(this).html("(" + attr_leadership + ")" + text.substring(find+1));
  724. $(this).attr('leadership',attr_leadership);
  725. });
  726.  
  727. let arr = li.map(function(_, o) {
  728. return {
  729. text : $(o).text(),
  730. idvalue : $(o).attr('idvalue'),
  731. leadership : $(o).attr('leadership')
  732. };
  733. }).get();
  734.  
  735. arr.sort((o1, o2)=>{ return o2.leadership-o1.leadership;});
  736.  
  737. li.each(function(i, option) {
  738. $(option).text(arr[i].text).attr({
  739. 'idvalue':arr[i].idvalue,
  740. 'leadership':arr[i].leadership
  741. });
  742. });
  743. }
  744. });
  745. Game.pages.add('training',{
  746. 'module':'team','action':'index'
  747. },null,[
  748. [
  749. 'groups',
  750. {'module':'team','action':'groups'}
  751. ],[
  752. 'settings',
  753. {'module':'team','action':'settings'},
  754. function(){
  755. $('#groupNameForm > table > tbody').find('input').attr('maxlength',16).mouseenter(function(){
  756. $(this).focus().attr('placeHolder',$(this).val()).val('');
  757. }).mouseleave(function(){
  758. if($(this).val().trim()=="") $(this).val($(this).attr('placeHolder'));
  759. $(this).removeAttr('placeHolder').focusout();
  760. });
  761. }
  762. ]
  763. ]);
  764. Game.pages.add('camp',{
  765. 'module':'team','action':'camp'
  766. });
  767. Game.pages.add('scout',{
  768. 'module':'transfermarket','action':'scout'
  769. });
  770. Game.pages.add('transfermarket',{
  771. 'module':'transfermarket','action':'index'
  772. },function(){
  773. /*Transfermarket Filter*/
  774. $('.table-container:first').children().first().after(
  775. '<div id="show_transfermarket_filter" style="margin:5px 0;">'+
  776. '&#10148; <span style="cursor:pointer;background-color:green;padding:2px;margin-left:-2px;border-radius:7px;" id="ShowAllPlayers">'+GetText('ShowAllPlayers')+'</span><br>'+
  777. '&#10148; <span style="cursor:pointer;" id="OnlyForeignPlayers">'+GetText('OnlyForeignPlayers')+'</span><br>'+
  778. '</div>'
  779. );
  780. $('#ShowAllPlayers').click(function(){
  781. $('#content > div.container.transfermarket > div.table-container > table > tbody > tr').each(function(i){
  782. $(this).show();
  783. $(this).attr('class',i%2==0?"odd":"even");
  784. });
  785. $(this).css({
  786. 'background-color':'green',
  787. 'padding':'2px',
  788. 'margin-left':'-2px',
  789. 'border-radius':'7px'
  790. });
  791. $('#OnlyForeignPlayers')[0].style = "cursor:pointer;";
  792. });
  793. $('#OnlyForeignPlayers').click(function(){
  794. let counter=0;
  795. $('#content > div.container.transfermarket > div.table-container > table > tbody > tr').each(function(){
  796. if(!$('td:nth-child(1) > img',this).attr('src').endsWith(Tool.flag+'.gif')){
  797. $(this).show();
  798. $(this).attr('class',counter++%2?'even':'odd');
  799. }
  800. else $(this).hide();
  801. });
  802. $(this).css({
  803. 'background-color':'green',
  804. 'padding':'2px',
  805. 'margin-left':'-2px',
  806. 'border-radius':'7px'
  807. });
  808. $('#ShowAllPlayers')[0].style = "cursor:pointer;";
  809. });
  810.  
  811.  
  812. //Kulüp arama kısmındaki tüm metni silmek için.
  813. $('#club').after('<img style="float:right;margin:2px 2px 0 0;cursor:pointer;" id="clearText" src="'+Tool.sources.getLink('https://www.clipartmax.com/png/full/301-3016667_red-cross-clipart-high-resolution-red-cross-emoji-gif.png')+'" alt="remove" width="10px">');
  814. $('#clearText').click(function(){
  815. clearText('club');
  816. function clearText(id){
  817. let text = $('#'+id).val(),
  818. length = text.length;
  819. while(length>0){
  820. setTimeout(function(){
  821. let t = $('#'+id).val();
  822. $('#'+id).val(t.substring(0,t.length-1));
  823. },(text.length-length)*25);
  824. length--;
  825. }
  826. }
  827. });
  828.  
  829.  
  830. if(Game.server == 'tr') $('#age_min').parents('li:first').next().find('>span:first').css('margin-left','-34px').html('Yerli Futbolcu');
  831.  
  832. //Kulübümüzün transfer pazarını göstermek için:
  833. $('#content > .container:first').append(CreateButton('ShowMyTransferMarket', GetText('ShowMyMarket'),'margin-Right:12px; top:71px; right:0; position:absolute; z-index:'+$('#content .search-container:first').css('z-index')+';'));
  834. $('#ShowMyTransferMarket').click(function(){
  835. $('#age_min').val(16);
  836. $('#age_max').val(34);
  837. $('#searchform > ul > li.strength > span:nth-child(2) > input[type="text"]').val(0);
  838. $('#searchform > ul > li.strength > span:nth-child(3) > input[type="text"]').val(999);
  839. $('#positions').val(0);
  840. $('#club').val(Tool.clubName);
  841. $('#searchform > ul > li.transfermarket-search-button > span > a > span').click();
  842. });
  843.  
  844.  
  845. //Show total bid
  846. if($('#club').val().trim()==Tool.clubName){
  847. let totalBid = 0;
  848. $('#content > div.container.transfermarket > div.table-container > table > tbody > tr').each(function(){
  849. var o = $('td:nth-child(7)',this).find('.currency-number');
  850. if(o.length) totalBid += parseInt(o.first().text().replace(/\./g,''));
  851. });
  852. if(totalBid>0){
  853. $('#content > div.container.transfermarket > div.table-container > table > tfoot > tr').html(
  854. `<td colspan="5"></td>`+
  855. `<td colspan="2" style="color:#edfdff;font-weight:bold;text-align:right;">${GetText('totalBid')}: ${(totalBid).toLocaleString()} <span class="icon currency"></span></td>`+
  856. `<td colspan="3"></td>`
  857. );
  858. }
  859. }
  860.  
  861.  
  862. //For the movement of the transfer page with the left and right arrow keys
  863. /*if($('#container .pager').length){
  864. $(document).keydown(function(e){
  865. document.title = "Click:"+Math.floor(Math.random()*1000);
  866. let a=undefined
  867. if(e.which==37) a = $('#container .pager > strong:first').prev()[0];
  868. else if(e.which==39) a = $('#container .pager > strong:first').next()[0];
  869. if(a!=undefined && a.tagName=='A') a.click();
  870. });
  871. }*/
  872. });
  873.  
  874. //CATEGORY: SEASON
  875. Game.pages.add('fixture',{
  876. 'module':'statistics','action':'games'
  877. });
  878. Game.pages.add('league',{
  879. 'module':'statistics','action':'table'
  880. });
  881. Game.pages.add('friendly',{
  882. 'module':'friendly'
  883. },function(){
  884. if(!$('#own-invitations-table > tbody > tr').find('.no-invites').length){
  885. //Kendi arkadaşlık maç davetlerimizin silinmesi
  886. $('#invitations > div.table-container > div:nth-child(1) > h3').append(CreateButton('ClearInvitations', GetText('CancelUnnecessaryDays'),'float:right;margin-right:5px;'));
  887. $('#ClearInvitations').click(function(){
  888. var doluTarihler = {};
  889. $('#friendly-matches > tbody > tr').each(function(){
  890. doluTarihler[$(this).find('td:nth-child(2)').attr('sortvalue')] = '';
  891. });
  892. var silinecekIstekKeyleri = [];
  893. $('#own-invitations-table > tbody > tr').each(function(){
  894. if(doluTarihler[$(this).find('td:nth-child(2)').attr('sortvalue')]!==undefined){
  895. var href = $(this).find('td.last-column > a')[0].href;
  896. silinecekIstekKeyleri.push(href.substring(href.indexOf('delete=')+7,href.lastIndexOf('&')));
  897. }
  898. });
  899. if(silinecekIstekKeyleri.length){
  900. clearInvitations();
  901. }
  902. async function clearInvitations(){
  903. if(!silinecekIstekKeyleri.length){
  904. Game.detectPage();
  905. return;
  906. }
  907. var key = silinecekIstekKeyleri[0];
  908. silinecekIstekKeyleri.splice(0,1);
  909. location.href = "#/index.php?w="+worldId+"&area=user&module=friendly&action=index&delete="+key;
  910. await Game.pageLoad();
  911. clearInvitations();
  912. }
  913. });
  914. }
  915. });
  916. Game.pages.add('simulation',{
  917. 'module':'simulation'
  918. },function(){
  919. let LeagueData = Tool.getVal('LeagueData');
  920. if(LeagueData!=undefined){
  921. if((LeagueData.lastMatchDate+86400000)>Game.getTime()){
  922. let clubs = LeagueData.clubs;
  923. $('#simulations > tbody').find('.name-column').each(function(){
  924. let a = $(this).find('a:first'),
  925. clubId = a.attr('clubid');
  926. if(!clubs.hasOwnProperty(clubId)) return;
  927. $(this).parent().css('background','green').attr({
  928. 'title': GetText('SameLeague', {tag:0}),
  929. 'tool_tt': 'SameLeague'
  930. });
  931. })
  932. }
  933. else Tool.delVal('LeagueData');
  934. }
  935. });
  936. Game.pages.add('tournament',{
  937. 'module':'tournament','action':['index','tournament','holding']
  938. });
  939. Game.pages.add('betoffice',{
  940. 'module':'betoffice'
  941. });
  942.  
  943. //CATEGORY: CLUB MANAGEMENT
  944. Game.pages.add('sponsors',{
  945. 'module':'club','action':'sponsors'
  946. });
  947. Game.pages.add('publicrelations',{
  948. 'module':'publicrelations'
  949. });
  950. Game.pages.add('assistants',{
  951. 'module':'assistants'
  952. },function(){
  953. let bars = $('#assistants').find('.bar'),
  954. values = [];
  955. bars.each(function(){
  956. values.push(parseInt(this.style.width.replace('%','')));
  957. this.style.width = '0%';
  958. });
  959. if(values.length){
  960. Tool.intervals.create(function(){
  961. for(let i = 0, width ; i < bars.length ; i++){
  962. width = bars[i].style.width;
  963. width = parseInt(width.substring(0,width.lastIndexOf('%')));
  964. if(width<values[i]) bars[i].style.width = (width+1)+'%';
  965. else{
  966. bars.splice(i,1);
  967. values.splice(i,1);
  968. }
  969. }
  970. this.delete();
  971. },20,'Asistants');
  972. }
  973. });
  974. Game.pages.add('finances',{
  975. 'module':'finances'
  976. });
  977. Game.pages.add('stadium',{
  978. 'module':'stadium'
  979. });
  980. Game.pages.add('buildings',{
  981. 'module':'buildings'
  982. });
  983. Game.pages.add('shop',{
  984. 'module':'shop'
  985. });
  986.  
  987. //CATEGORY: STATISTICS
  988. Game.pages.add('rating',{
  989. 'module':'rating'
  990. });
  991. Game.pages.add('statistics',{
  992. 'module':'statistics','action':'season'
  993. });
  994. Game.pages.add('tournament_history',{
  995. 'module':'tournament','action':'history'
  996. });
  997. Game.pages.add('squadstrenght',{
  998. 'module':'statistics','action':'squadstrenght'
  999. });
  1000. Game.pages.add('goalgetter',{
  1001. 'module':'statistics','action':'goalgetter'
  1002. });
  1003. Game.pages.add('sales',{
  1004. 'module':'statistics','action':'sales'
  1005. });
  1006. Game.pages.add('team_history',{
  1007. 'module':'team','action':'history'
  1008. });
  1009.  
  1010. //CATEGORY: COMMUNITY
  1011. Game.pages.add('press',{
  1012. 'module':'press','action':'index'
  1013. },null,[
  1014. [
  1015. 'article',
  1016. {'module':'press','action':'article'}
  1017. ],[
  1018. 'topnews',
  1019. {'module':'press','action':'topnews'}
  1020. ],[
  1021. 'settings',
  1022. {'module':'press','action':'settings'}
  1023. ],[
  1024. 'comment',
  1025. {'module':'press','action':'comment'}
  1026. ]
  1027. ]);
  1028. Game.pages.add('friends',{
  1029. 'module':'friends'
  1030. });
  1031. Game.pages.add('neighbors',{
  1032. 'module':'main','action':'neighbors'
  1033. });
  1034. Game.pages.add('signatures',{
  1035. 'module':'profile','action':'signatures'
  1036. });
  1037.  
  1038. //CATEGORY: CLUB
  1039. Game.pages.add('premium',{
  1040. 'module':'premium'
  1041. });
  1042. Game.pages.add('menager_profile',{
  1043. 'module':'profile','action':'index'
  1044. });
  1045. Game.pages.add('club_profile',{
  1046. 'module':'profile','action':'club'
  1047. });
  1048. Game.pages.add('manager',{
  1049. 'module':'profile','action':'show'
  1050. });
  1051. Game.pages.add('mail',{
  1052. 'module':'mail','action':'index'
  1053. },null,[
  1054. [
  1055. 'outbox',
  1056. {'module':'mail','action':'outbox'}
  1057. ],[
  1058. 'archive',
  1059. {'module':'mail','action':'archive'}
  1060. ],[
  1061. 'ignore',
  1062. {'module':'mail','action':'ignore'}
  1063. ]
  1064. ]);
  1065. Game.pages.add('tricotshop',{
  1066. 'module':'tricotshop'
  1067. });
  1068.  
  1069. //NON-CATEGORY
  1070. Game.pages.add('main',{
  1071. 'module':'main','action':['home','acceptSimulation','deleteSimulation','accept']
  1072. });
  1073. Game.pages.add('live',{
  1074. 'module':'live','action':'index'
  1075. },null,[
  1076. [
  1077. 'league',
  1078. {'module':'live','action':'league'}
  1079. ],[
  1080. 'match',
  1081. {'module':'live','action':'match'},
  1082. function(){
  1083. if($('#match').length){//Match is exist
  1084. // Add images
  1085. $('#goal-event-container').after(
  1086. `<div id="DivCards" class="match event-container" style="display:none;">`+
  1087. ` <img id="yellow_card" src="${Tool.sources.getLink('yellowCard','png')}" alt="yellowCard" style="display:none;">`+
  1088. ` <img id="red_card" src="${Tool.sources.getLink('redCard','png')}" alt="redCard" style="display:none;">`+
  1089. ` <img id="yellow_red_card" src="${Tool.sources.getLink('yellowRedCard','png')}" alt="yellowRedCard" style="display:none;">`+
  1090. `</div>`
  1091. );
  1092.  
  1093. // Add audios
  1094. $('#goal-event-container').after(
  1095. '<div id="Songs">'+
  1096. ' <audio id="goalSound" src="https://static.wixstatic.com/mp3/fcacd5_2794b8a8827a475eaf9a3241be0c42d5.mp3"></audio>'+
  1097. ' <audio id="whistle1" src="https://static.wixstatic.com/mp3/fcacd5_4f0052fc29104ead86761cbb08d50774.mp3"></audio>'+
  1098. ' <audio id="whistle2" src="https://static.wixstatic.com/mp3/fcacd5_b967408abf59401d9b71778ea45ae2b9.mp3"></audio>'+
  1099. ' <audio id="whistle3" src="https://static.wixstatic.com/mp3/fcacd5_c4ccd759ec62404cb59f6a8ff906e110.mp3"></audio>'+
  1100. ' <audio id="backgroundSound" loop src="https://static.wixstatic.com/mp3/fcacd5_5a27a4e8ed2a482099ea0ba8839d4db9.mp3"></audio>'+
  1101. ' <audio id="fan1" loop src="https://static.wixstatic.com/mp3/fcacd5_d7123a0a3c2f469cbdf603067579de93.mp3"></audio>'+
  1102. ' <audio id="fan2" loop src="https://static.wixstatic.com/mp3/fcacd5_fde7b7b934d24cf98771cc022eb6bee3.mp3"></audio>'+
  1103. '</div>'
  1104. );
  1105.  
  1106. // Add Goals Container
  1107. $('#match-messages').before(
  1108. '<div style="width: 840px;position: absolute;left: 65px;top: 101px;color:white;">'+
  1109. ' <div id="home-goals" style="float:left;width:48%;height:100%;text-align:center;overflow: auto;line-height:16px;height:38px;"></div>'+
  1110. ' <div id="away-goals" style="float:right;width:48%;height:100%;text-align:center;overflow: auto;line-height:16px;height:38px;"></div>'+
  1111. '</div>'
  1112. );
  1113.  
  1114. // Is this match own?
  1115. currentLive.ownMatch = $('#'+currentLive.matchId +' h3 a[clubid="'+Tool.clubId+'"]').length!=0;
  1116.  
  1117.  
  1118. unsafeWindow.jQuery('<span id="MatchEventCatcher">').hide().appendTo('#content').click(function(_, event){
  1119. if(event.message) {
  1120. switch(event.type){
  1121. case 'goal': case 'penalty': case 'penaltyShootout':
  1122. if(event.type!='penaltyShootout' || event.goal == 'goal'){
  1123. if(currentLive.lastActiveMin < 120){ // GOOOOALL : event['team']
  1124. if(event._status == 'new'){
  1125. if(currentLive.ownMatch && event.team == currentLive.ownSquad){
  1126. $('#goalSound')[0].currentTime = 0;
  1127. $('#goalSound')[0].play();
  1128. }
  1129.  
  1130. if($('#NewGoalCatcher').length){
  1131. unsafeWindow.jQuery('#NewGoalCatcher').trigger('click', {
  1132. [currentLive.matchId]: { //Note: New goal has not yet been added to the element (score-home or score-away)
  1133. "status": event.action=="end"?"ended":"active",
  1134. "home_goals": parseInt($('#'+currentLive.matchId + '> span.score > div:first > span.score-home').text()) + (event.team==currentLive.homeId?1:0),
  1135. "away_goals": parseInt($('#'+currentLive.matchId + '> span.score > div:first > span.score-away').text()) + (event.team==currentLive.awayId?1:0),
  1136. "min": event.min
  1137. }
  1138. });
  1139. }
  1140. }
  1141.  
  1142. let message = event.message,
  1143. team_matchId = event.team,
  1144. min = event.min,
  1145. team = currentLive.homeId==team_matchId?"home":"away",
  1146. goal_scorer_lastname = $('<div>').html(message).find('.'+team+':last').text().trim(),
  1147. fonded_players = Object.values(currentLive.players[team_matchId]).filter(p=>p.lastname==goal_scorer_lastname)
  1148.  
  1149. if(fonded_players.length==1){
  1150. let goal_scorer = fonded_players[0],
  1151. spn = $('#player-goals-'+goal_scorer.id);
  1152. if(!spn.length){ // player's first goal
  1153. if($('#'+team+'-goals > span').length) $('#'+team+'-goals').append(' , ');
  1154. $('#'+team+'-goals').append(
  1155. `<span style="color:${team=="home"?'#f00':'#0ec6e7'};white-space:nowrap;">`+
  1156. ` <img src="https://image.ibb.co/jdRxmK/Ads_z.png" height="15px;" style="vertical-align:middle;margin: 1px 2px 0 0;">`+
  1157. ` <span id="player-goals-${goal_scorer.id}" style="color:white;font-size: 10px;font-weight:bold;">[${min}]</span> ${goal_scorer.lastname}`+
  1158. `</span>`
  1159. );
  1160. }
  1161. else{
  1162. let text = spn.text();
  1163. spn.text(text.substring(0,text.length-1)+','+min+']');
  1164. }
  1165. }
  1166. else{
  1167. if($('#'+team+'-goals > span').length) $('#'+team+'-goals').append(' , ');
  1168. $('#'+team+'-goals').append(
  1169. `<span style="color:${team=="home"?'#f00':'#0ec6e7'};white-space:nowrap;">`+
  1170. ` <img src="https://image.ibb.co/jdRxmK/Ads_z.png" height="15px;" style="vertical-align:middle;margin: 1px 2px 0 0;"> ~`+
  1171. `</span>`
  1172. );
  1173. }
  1174. }
  1175. }
  1176. break;
  1177. case 'info':
  1178. if(event._status == 'new'){
  1179. let min = event.min,
  1180. whistle = $('#whistle'+(
  1181. min==1?1: //Match start
  1182. min==45?2: //First half end
  1183. event.action=='end'?3: //Match end
  1184. 2 //Else
  1185. ));
  1186. if(whistle.length){
  1187. whistle=whistle[0];
  1188. whistle.currentTime = 0;
  1189. whistle.play();
  1190. }
  1191. }
  1192. break;
  1193. }
  1194. }
  1195.  
  1196. switch(event.type){
  1197. case 'penaltyShootout':
  1198. if(event.goal == 'goal'){ //Penaltı atışı gol oldu
  1199. //Gol atan takım => event.team
  1200. }
  1201. else if(event.goal == 'miss'){ //Penaltı atışı kaçtı
  1202. }
  1203. break;
  1204. case 'penaltyShootoutScore': //Penaltı skor tablosu gösteriliyor
  1205. /*message = currentLive.getMessageElement(event['min']);
  1206. $(message).addClass('info');
  1207. $(message).append(event['template']);
  1208. $('#match-messages').prepend($(message));*/
  1209. break;
  1210. case 'red': case 'yellow': case 'yellow_red':
  1211. if(event._status == 'new'){
  1212. $('#whistle1')[0].currentTime=0;
  1213. $('#whistle1')[0].play();
  1214. if(currentLive.ownMatch && event.squad == currentLive.ownSquad){
  1215. $('#DivCards,#'+event.type+'_card').show();
  1216. setTimeout(()=>{
  1217. $('#DivCards,#'+event.type+'_card').hide();
  1218. },event.delay);
  1219. }
  1220. }
  1221. /*var player = $('#field-player-' + event['player']);
  1222. player.removeClass('weak');
  1223. player.addClass(event['type']);
  1224. if (event['type'] != 'yellow') {
  1225. if (event['squad'] == currentLive.ownSquad) {
  1226. $('#out-of-match').append($('#field-player-' + event['player']));
  1227. var playerObj = currentLive.players[currentLive.ownSquad][event['player']];
  1228. if (playerObj) {
  1229. $('#field-player-points-' + event['player']).html(playerObj['points']);
  1230. player.off();
  1231. }
  1232. } else {
  1233. $('#opponent-out-of-match').append($('#field-player-' + event['player']));
  1234. }
  1235. currentLive.players[event['squad']][event['player']]['a_position'] = 'Bank';
  1236. } */
  1237. break;
  1238. case 'move':
  1239. break;
  1240. case 'injured':
  1241. //var isOwnInjuredPlayer = currentLive.ownMatch && event.squad==currentLive.ownSquad;
  1242. /*currentLive.players[event['squad']][event['player']]['initial_health'] -= event['injuring'];
  1243. currentLive.setHealthStatus(event['player'], currentLive.players[event['squad']][event['player']]['initial_health']);*/
  1244. break;
  1245. case 'bonusHealthLoss':
  1246. break;
  1247. case 'bonusHealthGain':
  1248. break;
  1249. case 'bonusFormationLoss':
  1250. break;
  1251. case 'bonusFormationGain':
  1252. break;
  1253. case 'bonusLeadershipLoss':
  1254. break;
  1255. }
  1256.  
  1257. if(event.action == 'end'){
  1258. if(event._status == 'new'){
  1259. ['backgroundSound','fan1','fan2'].map(n=>$('#'+n)[0]).forEach((audio,i)=>{
  1260. if(audio.paused) return;
  1261. let j = audio.volume*100;
  1262. for(let t = j ; j>=0 ; j--){
  1263. ((j,i)=>{
  1264. setTimeout(function(){
  1265. audio.volume = j/100;
  1266. if(audio.volume < 1) audio.pause();
  1267. },(t-j)*50);
  1268. })(j,i);
  1269. }
  1270. });
  1271.  
  1272. if($('#NewGoalCatcher').length && event.min==1){ //the match is over due to insufficient number of players
  1273. let home_goals = $('<div>').html(event.message).find('span.away,span.home').first().attr('class')=="away"?3:0,
  1274. away_goals = home_goals==3?0:3;
  1275.  
  1276. unsafeWindow.jQuery('#NewGoalCatcher').trigger('click', {
  1277. [currentLive.matchId]: {
  1278. "status": "ended",
  1279. "home_goals": home_goals,
  1280. "away_goals": away_goals,
  1281. "min": event.min
  1282. }
  1283. });
  1284. }
  1285. }
  1286. else{ //Match has been already finished before, no new event will catched
  1287. $('#backgroundSound').attr('stop',true);
  1288. ['backgroundSound','fan1','fan2'].map(n=>$('#'+n)[0]).forEach(audio=>{
  1289. if(!audio.paused) audio.pause();
  1290. });
  1291. }
  1292. }
  1293. });
  1294. if(Array.isArray(Tool.uncaught_events_queue)){
  1295. Tool.uncaught_events_queue.forEach(event=>{
  1296. unsafeWindow.jQuery("#MatchEventCatcher").trigger('click', [event]);
  1297. });
  1298. delete Tool.uncaught_events_queue;
  1299. }
  1300. if(!Tool.hasOwnProperty('goalTrigger')) Tool.goalTrigger = 0;
  1301. if(Tool.goalTrigger<3) ++Tool.goalTrigger;
  1302.  
  1303. //Show or hide home/away team's players in field.
  1304. for(let squadId in currentLive.players){
  1305. ((index,playersClass)=>{ //eslint-disable-line no-loop-func
  1306. let data = {
  1307. home:{
  1308. style:'position:absolute;top:600px;',
  1309. id:"homePlayersFilter",
  1310. text:GetText('ShowHomeSquad')
  1311. },
  1312. away:{
  1313. style:"position:absolute;top:600px;right:20px;",
  1314. id:"awayPlayersFilter",
  1315. text:GetText('ShowAwaySquad')
  1316. }}[index];
  1317.  
  1318. $('#formation-container').append(
  1319. `<div style="${data.style}">`+
  1320. ` <input id="${data.id}" type="checkBox">`+
  1321. ` <label for="${data.id}" style="cursor:pointer;">${data.text}</label>`+
  1322. `</div>`
  1323. );
  1324.  
  1325. if(index==="away"){
  1326. $('#match-handle-container').css('height',"36px");
  1327. $('#match-handle-container > li:first').css('height',"36px");
  1328. }
  1329. $('#'+data.id).click(function(){
  1330. let checked = this.checked;
  1331. $('#field').find('.field-player').each(function(){
  1332. if($(this).hasClass(playersClass)){
  1333. $(this)[checked?'addClass':"removeClass"]('hover');
  1334. }
  1335. });
  1336. });
  1337. })(
  1338. squadId == currentLive.homeId?"home":"away",
  1339. squadId == currentLive.ownSquad?"own-player":"opponent"
  1340. );
  1341. }
  1342.  
  1343. try{
  1344. //Background Sound is playing
  1345. setTimeout(function(){
  1346. let backgroundSound = $('#backgroundSound')[0];
  1347. backgroundSound.currentTime = 0;
  1348. backgroundSound.volume = 0;
  1349. backgroundSound.play();
  1350. let intervals = [];
  1351. [...Array(51).keys()].slice(1).forEach(i=>{ // 1 to 50
  1352. intervals.push(setTimeout(()=>{
  1353. if(!$('#backgroundSound').attr('stop')){
  1354. backgroundSound.volume = i/100;
  1355. }
  1356. else{
  1357. intervals.forEach(id=>{ clearTimeout(id);});
  1358. }
  1359. },(i-1)*50));
  1360. });
  1361. },250);
  1362. }
  1363. catch(err){console.error(err);};
  1364. }
  1365. }
  1366. ]
  1367. ]);
  1368.  
  1369. class Feature{
  1370. constructor(name,page_names,run,hover_selector=null){
  1371. this.name = name;
  1372. this.page_names = page_names;
  1373. this.run = run;
  1374. this.active = null;
  1375. this.work = null;
  1376. if(typeof hover_selector == 'string' && (hover_selector=hover_selector.trim())!="") this.hover_selector = hover_selector;
  1377. }
  1378. deactivate(){
  1379. this.active = false;
  1380. }
  1381. activate(){
  1382. this.active = true;
  1383. }
  1384. }
  1385.  
  1386. let Tool = new (class{
  1387. constructor(){
  1388. this.sources = {
  1389. getLink: (url)=>{
  1390. return url;/*Thanks to mot33*/
  1391. }
  1392. };
  1393. this.features = [];
  1394. this.features.getByName = function(name){
  1395. return this.find(f=>f.name==name);
  1396. }
  1397. this.features.add = function(name,page_names,run,hover_selector=null,otherPages=null){
  1398. if(this.getByName(name) instanceof Feature) throw new Error(`A feature with this name(${name}) was previously created.`);
  1399.  
  1400. let feature = new Feature(name, page_names, run, hover_selector);
  1401. if(!Array.isArray(page_names)) page_names = [page_names];
  1402.  
  1403. page_names.forEach(page_name=>{
  1404. let page = Game.pages.getByName(page_name);
  1405. if(page === undefined) throw new Error(`Page(${page_name}) doesn't exist, therefore feature(${name}) can't be added.`);
  1406. page.addFeature(feature);
  1407. });
  1408.  
  1409. if(otherPages!=null){
  1410. if(!Array.isArray(otherPages[0])) otherPages=[otherPages];
  1411. otherPages.forEach(p=>{
  1412. let page_name = p[0],
  1413. run = p[1],
  1414. page = Game.pages.getByName(page_name)
  1415. if(page === undefined) throw new Error(`Page(${page_name}) doesn't exist, therefore feature(${name}) can't be added. (Page is in otherPages)`);
  1416.  
  1417. //Extends page's run function
  1418. let page_run = page.run;
  1419. if(typeof page_run=='function'){ //If page's run function already exist, it will be extended
  1420. page_run = page_run.toString();
  1421. page_run = page_run.substring(0,page_run.lastIndexOf('}'));
  1422. run = run.toString();
  1423. run = run.substring(run.indexOf('{')+1);
  1424. eval('page.run = '+page_run+`\n\t\t/*Extended by feature named ${name}*/`+run);
  1425. }
  1426. else{
  1427. run = run.toString();
  1428. let find = run.indexOf('{');
  1429. eval('page.run = ' + run.substring(0,find+1)+`\n\t\t/*Created by feature named ${name}*/`+run.substring(find+1));
  1430. }
  1431. });
  1432. }
  1433.  
  1434. this.push(feature);
  1435. };
  1436. this.log_intervals=false;
  1437. this.intervals = new (class{
  1438. constructor(){
  1439. this.named = {};
  1440. this.anonymous = [];
  1441. }
  1442. create(func,delay,name=null){
  1443. let that = this;
  1444. if(typeof name == "string" && (name=name.trim())!=""){
  1445. if(this.named.hasOwnProperty(name)) throw new Error(`Intervals.create with name(${name}) was already used in one of previous intervals`);
  1446.  
  1447. let interval = {
  1448. created_at : new Date().getTime(),
  1449. name : name,
  1450. delete : function(){
  1451. clearInterval(that.named[this.name]);
  1452. let diff = new Date().getTime()-this.created_at;
  1453. if(Tool.log_intervals) console.log('[intervals] Named('+this.name+') interval deleted itself after ' + SecToTime(parseInt((diff)/1000))+'.'+(diff%1000));
  1454. delete that.named[this.name];
  1455. },
  1456. func : func
  1457. };
  1458. this.named[name] = setInterval(function(){
  1459. func.call(interval);
  1460. },delay);
  1461. if(Tool.log_intervals) console.log('[intervals] Created named('+name+') interval with '+delay+' ms delay');
  1462. }
  1463. else{
  1464. let id,
  1465. interval = {
  1466. created_at : new Date().getTime(),
  1467. delete : function(){
  1468. clearInterval(id);
  1469. let diff = new Date().getTime()-this.created_at;
  1470. if(Tool.log_intervals) console.log('[intervals] Anonymous interval deleted itself id: '+id+' after ' + SecToTime(parseInt((diff)/1000))+'.'+(diff%1000));
  1471. that.anonymous.find((item,index,array)=>{
  1472. if(item==id){
  1473. array.splice(index,1);
  1474. if(Tool.log_intervals) console.log('[intervals]\t\t id in annoymous splice index: '+index);
  1475. return 1;
  1476. }
  1477. });
  1478. }
  1479. };
  1480. id = setInterval(function(){
  1481. func.call(interval);
  1482. },delay);
  1483. this.anonymous.push(id);
  1484. if(Tool.log_intervals) console.log('[intervals] Created anonymous interval with '+delay+' ms delay , id: '+id);
  1485. }
  1486. }
  1487. clear(){
  1488. if(Tool.log_intervals) console.log('[intervals] Clear all intervals');
  1489. let named = this.named;
  1490. for(var name in named){
  1491. clearInterval(named[name]);
  1492. delete named[name];
  1493. }
  1494.  
  1495. for(let i=0, len=this.anonymous.length; i<len; i++) clearInterval(this.anonymous[i])
  1496. this.anonymous=[];
  1497. }
  1498. })();
  1499. this.defaultFeaturesActiveStatus = {
  1500. "ConstructionCountdown" : !0,
  1501. "RematchMatch" : !0,
  1502. "NumberOfFootballerChecker" : !0,
  1503. "MatchAnalyst" : !0,
  1504. "TrainingControl" : !0,
  1505. "ClubExchange" : !0,
  1506. "RankingOfPlayers" : !0,
  1507. "ShowStrengthChange" : !0,
  1508. "ShowRealStrength" : !1,
  1509. "CalculateNonYoungPlayersStrength": !0,
  1510. "CalculatingStrengthOfYoungPlayer": !0,
  1511. "YoungPlayersHistory" : !0,
  1512. "TrainingGroups" : !1,
  1513. "CampHistory" : !0,
  1514. "TransferDates" : !0,
  1515. "GoOffer" : !0,
  1516. "ShowBoughtPlayers" : !0,
  1517. "ShowOwnOfferInMarket" : !0,
  1518. "FilterOwnOffers" : !0,
  1519. "FilterTransferMarket" : !0,
  1520. "DownloadTable" : !0,
  1521. "CancelFriendlyMatchInvites" : !0,
  1522. "QuickBet" : !0,
  1523. "ShowAsistantLevelIncrease" : !0,
  1524. "QuickShopping" : !0,
  1525. "AddImage" : !0,
  1526. "InviteSimulationMatch" : !0,
  1527. "ShowEloRating" : !0,
  1528. "LiveMatchesTable" : !0,
  1529. "SortTournaments" : !0,
  1530. };
  1531. }
  1532.  
  1533. async start(){
  1534. delete this.__proto__.start;
  1535.  
  1536. if($('#ChangeContent').length) throw new Error("Script already works!");
  1537.  
  1538. //Fix tool values and print
  1539. this.fixValues();
  1540. this.printValues();
  1541.  
  1542. //Wait game page loading first time
  1543. await new Promise(res=>{
  1544. let a, b = setTimeout(()=>{
  1545. clearInterval(a);
  1546. res();
  1547. },2500);
  1548. a = setInterval(()=>{
  1549. if($('body').hasClass('loading')){
  1550. clearInterval(a);
  1551. clearTimeout(b);
  1552. res();
  1553. }
  1554. },10);
  1555. });
  1556.  
  1557. //Wait game page loaded
  1558. let ms = await Game.pageLoad();
  1559. console.log('Wait for the game to load for the first time : ' + ms + ' ms');
  1560.  
  1561. if($('#logout').length==0) throw new Error("Logout button doesn't exist");
  1562.  
  1563. await Game.initialConfigure(); //After that initialize game configure
  1564.  
  1565. //Get game server and check if it's datas is already in the script
  1566. Game.server = $('body').attr('class').replace('loading','').trim();
  1567. if(!(Game.server in serversDatas)){
  1568. Game.giveNotification(false,"This server is not available in the script!");
  1569. throw new Error("This server is not available in the script!");
  1570. }
  1571.  
  1572. //Get tool features active status data. (Note: getVal use Game.server)
  1573. this.featuresActiveStatus = this.getVal('featuresActiveStatus', this.defaultFeaturesActiveStatus);
  1574.  
  1575. //Tool datas
  1576. for(const [key,value] of Object.entries(serversDatas[Game.server])) this[key] = value;
  1577. serversDatas = undefined;
  1578.  
  1579. let Positions = this.footballerPositions;
  1580. this.strengthFactors = new Proxy({ // this is required to calculate strength of a player
  1581. [['goalkeeper',Positions[0]].join('|')] : [[ 0,5], [ 1,5], [3,4], [ 8,3], [ 6,2], [10,1], [4,1], [2,1]],
  1582. [['defense',...Positions.slice(1,4)].join("|")] : [[ 6,4], [ 9,4], [3,3], [ 8,2], [10,2], [ 4,2], [5,2], [7,2], [11,2], [2,1]],
  1583. [['midfield',...Positions.slice(4,6)].join("|")] : [[ 3,4], [10,4], [8,3], [ 5,3], [ 6,2], [ 4,2], [7,2], [9,2], [11,2], [2,1]],
  1584. [['offensive',...Positions.slice(6,8)].join("|")]: [[11,4], [ 3,3], [8,3], [10,3], [ 2,3], [ 6,2], [4,2], [5,1], [ 7,1], [9,1]]
  1585. }, {
  1586. get: function(target, property, receiver) {
  1587. for(let k in target)
  1588. if(new RegExp(k).test(property))
  1589. return target[k];
  1590. return null;
  1591. }
  1592. });
  1593.  
  1594. (()=>{
  1595. let penalty_area_safety=0, catch_safety=1, two_footed=2, fitness=3, shot=4, header=5, duell=6, cover=7, speed=8, pass=9, endurance=10, running=11, ball_control=12, aggressive=13;
  1596. this.trainingPlan = { // this is required to check whether player skill that is being improved is true
  1597. [Positions[0]]: [penalty_area_safety, catch_safety, fitness, speed, duell, endurance, shot, two_footed], //TW
  1598. [Positions[1]]: [pass, duell, fitness, cover, speed, endurance, header, shot, running, two_footed], //AV
  1599. [Positions[2]]: [pass, duell, fitness, cover, speed, endurance, header, shot, running, two_footed], //IV
  1600. [Positions[3]]: [duell, pass, fitness, cover, endurance, speed, shot, running, header, two_footed], //DM
  1601. [Positions[4]]: [endurance, fitness, speed, header, pass, running, duell, shot, cover, two_footed], //LM
  1602. [Positions[5]]: [endurance, fitness, speed, header, pass, running, duell, shot, cover, two_footed], //RM
  1603. [Positions[6]]: [running, fitness, speed, endurance, two_footed, shot, duell, pass, header, cover], //OM
  1604. [Positions[7]]: [running, fitness, speed, two_footed, endurance, duell, shot, header, pass, cover] //ST
  1605. };
  1606. })();
  1607. Positions=undefined;
  1608.  
  1609. //Get translations
  1610. let userLanguages = GM_getValue('userLanguage',{}),
  1611. result, gameDefLanguage = this.language, chooseAlternative=!1;
  1612. if(userLanguages.hasOwnProperty(Game.server) && Translate.existLanguage(userLanguages[Game.server])){
  1613. result = Translate.start(userLanguages[Game.server]); //User preference language
  1614. }
  1615. else{
  1616. if(Translate.existLanguage(gameDefLanguage)) result = Translate.start(this.language); //Default server language
  1617. else{
  1618. result = Translate.start(); //Alternative language
  1619. chooseAlternative=!0;
  1620. }
  1621. }
  1622.  
  1623. if(result.status=='error'){
  1624. Game.giveNotification(false, result.msg);
  1625. throw new Error(JSON.stringify(result, null, '\t'));
  1626. }
  1627. this.language = Translate.locale.name;
  1628. if(chooseAlternative){
  1629. Game.giveNotification(true, `This script hasn't yet been translated into ${gameDefLanguage}!<br>Alternative language[${this.language}] selected!`);
  1630. }
  1631.  
  1632. //Get club datas
  1633. let clubDatas = Tool.getVal('clubDatas'),
  1634. dataResult = this.checkClubData(clubDatas);
  1635. if(dataResult == 'not-exist'){
  1636. clubDatas = await this.createWelcomeMenu();
  1637. dataResult = this.checkClubData(clubDatas);
  1638. }
  1639. delete this.__proto__.createWelcomeMenu;
  1640. delete this.__proto__.checkClubData;
  1641.  
  1642. if(dataResult!='correct'){
  1643. Game.giveNotification(false,"Club datas isn't correct!");
  1644. throw new Error("Club datas isn't correct!");
  1645. }
  1646. for(let [key,val] of Object.entries(clubDatas)) this[key] = val;
  1647.  
  1648. //
  1649. this.checkDatas();
  1650.  
  1651. //...
  1652. this.createToolMenu();
  1653. this.createMenuEvents();
  1654. this.checkVersion();
  1655. this.createNoticeArea();
  1656.  
  1657. //plObj[Oyuncu verileri] nin kaydedilmesi
  1658. /*$.get('?area=user&module=formation&action=index&layout=none',function(response) {
  1659. let r = response.content,
  1660. b = r.lastIndexOf('var plObj');
  1661. if(b!=-1){
  1662. b = r.indexOf('=',b);
  1663. playerObject = JSON.parse(r.substring(b+1,r.indexOf('}};',b)+2));
  1664. if(!typeof playerObject=='object' //Kadroda oyuncu olunca "plObj = {...};" oluyor.
  1665. || Array.isArray(playerObject) //Kadroda hic oyuncu olmazsa "plObj = [];" oluyor.
  1666. ) playerObject = undefined;
  1667. }
  1668. });*/
  1669.  
  1670. $('<span id="ChangeContent">').hide().appendTo('body').click(function(){
  1671. if(!$('#content').find('h2').first().attr('Fixed'))
  1672. Game.detectPage(); //Sayfa değiştirilince Fixed özelliği olmayacağı için undefined değeri dönecek ve main fonksiyonu çalıştırılacak.
  1673. });
  1674. Game.detectPage(false);
  1675. }
  1676. checkDatas(){
  1677. delete this.__proto__.checkDatas;
  1678.  
  1679. //ageDatas
  1680. if(Array.isArray(this.ageDates)){
  1681. let ageDates = this.ageDates.slice(0),
  1682. serverTime = Game.getTime();
  1683. if(ageDates[ageDates.length-1]*60000<serverTime) this.ageDates = undefined;
  1684. else{
  1685. while(ageDates.length){
  1686. let date = ageDates[0]*60000;
  1687. if(date>serverTime) break;
  1688. ageDates.splice(0,1);
  1689. }
  1690. if(!ageDates.length) this.ageDates = undefined;
  1691. else this.ageDates = ageDates.slice(0);
  1692. }
  1693. }
  1694. else delete this.ageDates;
  1695.  
  1696. //featuresActiveStatus
  1697. let updated=0; //Veri de herhangi bir güncelleme olursa onu kaydetmek için
  1698. Object.entries(this.defaultFeaturesActiveStatus).map(e=>{return {k:e[0],v:e[1]};}).forEach(f=>{ //Yeni bir özellik geldiğinde veya var olan özellik bir şekilde kaybolduysa eklemek için;
  1699. if(!this.featuresActiveStatus.hasOwnProperty(f.k)){
  1700. this.featuresActiveStatus[f.k] = f.v;
  1701. ++updated;
  1702. }
  1703. });
  1704. delete this.defaultFeaturesActiveStatus;
  1705. for(let [featureKey,enable] of Object.entries(this.featuresActiveStatus)){ //Tool'a eklenen özelliklere başlangıç durumunu(etkin/devre dışı) verecek
  1706. let feature = this.features.getByName(featureKey);
  1707. if(feature==undefined){ //Özellik kaldırıldı veya verilerde yanlış düzenleme mevcut
  1708. delete this.featuresActiveStatus[featureKey];
  1709. ++updated;
  1710. continue;
  1711. }
  1712. feature.active = enable;
  1713. }
  1714. if(updated>0) this.setVal('featuresActiveStatus',this.featuresActiveStatus);
  1715. delete this.featuresActiveStatus;
  1716. }
  1717. checkClubData(clubDatas){
  1718. if(typeof clubDatas == "object"){
  1719. if(clubDatas.trainerLevel==undefined ||
  1720. clubDatas.yTrainerLevel==undefined ||
  1721. clubDatas.clubId==undefined ||
  1722. clubDatas.clubName==undefined
  1723. ) return 'incorrect';
  1724. return 'correct';
  1725. }
  1726. return 'not-exist';
  1727. }
  1728.  
  1729. createWelcomeMenu(){
  1730. delete this.__proto__.createWelcomeMenu;
  1731. //Eğer kulüp bilgileri mevcut değilse, kullanıcının verileri silinmiş olabilir yada kullanıcı scripti ilkkez yüklüyordur.
  1732. return new Promise((res,rej)=>{
  1733. let header = { //Scriptin açılış menüsünün baş kısmı
  1734. content : GetText('NeedNecessaryInformation')+`<img src="${Tool.sources.getLink('unhappy','png')}" alt="unhappy" height="25px" style="position:absolute;margin: 4px 0 4px 5px;">`,
  1735. css : {'text-align':'center'}
  1736. };
  1737.  
  1738. let div = { //Scriptin açılış menüsünün içeriği
  1739. footer : !0,
  1740. close : !0,
  1741. class : 'container'
  1742. };
  1743. div.content=
  1744. `<p style="color:red;margin-bottom:10px;font-weight:bold;text-align:left;font-size:12px;">${GetText('InformScriptWorking')}</p>`+
  1745. `<p style="color:blue;font-weight:bold;text-align:left;font-size:12px;margin-Bottom:10px;">${GetText('HelpDataUploading')}</p>`+
  1746. `<p style="text-align:center;margin-bottom:25px;">`+
  1747. ` <img id="uploadDatas" class="grow" title="${GetText('UploadDatas', {tag:0})}" tool_tt="UploadDatas" src="https://i.ibb.co/WzvZS4s/Untitled.png" style="cursor:pointer;" height="40px">`+
  1748. `</p>`+
  1749. `<h3>${GetText('EnterClubInformation')} :</h3>`+
  1750. `<table style="width:280px;margin:0 auto 15px auto;border-radius:6px;color:#111b9c;background-color:white;box-shadow: 5px 10px 8px #3939398c;">`+
  1751. ` <tbody>`+
  1752. ` <tr class="odd">`+
  1753. ` <td style="border:0;text-align:center;padding-Left:5px;">${GetText('TrainerLevel')}</td>`+
  1754. ` <td style="border:0;">`+
  1755. ` <label class="menü">`+
  1756. ` <select id="AntrenörSeviyesi1" style="font-size:12px;width:55px;margin:0 auto;text-align-last: center;"></select>`+
  1757. ` </label>`+
  1758. ` </td>`+
  1759. ` </tr>`+
  1760. ` <tr class="even">`+
  1761. ` <td style="border:0;border-radius:6px 0 0 6px;text-align:center;padding-Left:5px;">${GetText('YoungTrainerLevel')}</td>`+
  1762. ` <td style="border:0;border-radius:0 6px 6px 0;">`+
  1763. ` <label class="menü">`+
  1764. ` <select id="GAntrenörSeviyesi1" style="font-size:12px;width:55px;margin:0 auto;text-align-last: center;"></select>`+
  1765. ` </label>`+
  1766. ` </td>`+
  1767. ` </tr>`+
  1768. ` </tbody>`+
  1769. `</table>`+
  1770. `<p style="text-align:center;">${CreateButton('butonOnayla', GetText('Confirm')+' !')}</p>`;
  1771.  
  1772. ShowDialog(div,header);
  1773.  
  1774. //Adding level options to selects
  1775. let selects = $('#AntrenörSeviyesi1, #GAntrenörSeviyesi1');
  1776. selects.append(`<option value="10" selected tool_ot="SortLevel_10 {X}">10 ${GetText('SortLevel', {tag:0})}</option>`)
  1777. for(let lvl=9; lvl>-1; lvl--) selects.append(`<option value="${lvl}" tool_ot="SortLevel_${lvl} {X}">${lvl} ${GetText('SortLevel', {tag:0})}</option>`)
  1778.  
  1779. $('#butonOnayla').click(async function(){
  1780. $(this).off();
  1781. let span = $(this).find('span:last'),
  1782. html = span.html(),
  1783. clubDatas = {
  1784. "trainerLevel" : parseInt($('#AntrenörSeviyesi1').val()),
  1785. "yTrainerLevel" : parseInt($('#GAntrenörSeviyesi1').val())
  1786. },
  1787. self = $('.self-link');
  1788. span.html('<img src="/designs/redesign/images/icons/loading/16x16.gif" style="margin-top: -1px;">');
  1789. if(self.length){
  1790. clubDatas.clubId = $('.self-link').first().attr('clubid');
  1791. clubDatas.clubName = $('.self-link').first().text().trim();
  1792. }
  1793. else{
  1794. try{
  1795. let profile_show = await Game.getPage('?w='+worldId+'&area=user&module=profile&action=show','#profile-show');
  1796. clubDatas.clubId = profile_show.find('div.container.profile-trophy > div.profile > ul.profile-box-club > li:nth-child(2) > a')[0].href.split('&').find(a=>a.split('=')[0]=='clubId').split('=')[1];
  1797. clubDatas.clubName = profile_show.find('h2').first().text().replace(Tool.replaceClubName,'').trim();
  1798. }
  1799. catch(err){
  1800. alert("An error is exist.\n"+err);
  1801. return;
  1802. }
  1803. }
  1804.  
  1805. span.html(html);
  1806. Tool.setVal('clubDatas',clubDatas);
  1807. closeFocus({target: $('.close')});
  1808. res(clubDatas);
  1809. });
  1810. $('#uploadDatas').click(function(){
  1811. ReadTextFile(
  1812. function(valuesText){
  1813. valuesText.split('CookieKey&:').slice(1).forEach(data=>{
  1814. let b = data.indexOf(':');
  1815. GM_setValue(data.substring(0,b),JSON.parse(data.substring(b+1)));
  1816. });
  1817. Tool.fixValues();
  1818. closeFocus({target: $('.close')});
  1819. Game.giveNotification(true, GetText('DataLoaded'));
  1820. res(Tool.getVal('clubDatas'));
  1821. }
  1822. );
  1823. });
  1824. });
  1825. }
  1826.  
  1827. createToolMenu(){
  1828. delete this.__proto__.createToolMenu;
  1829.  
  1830. $('html, body').animate({ scrollTop: 0 }, 'fast'); //Sayfanın başına getiriliyor. Menü ortaya çıkartılacak.
  1831.  
  1832. //Script menüsü için toogle buton ekleniyor ve açılıp-kapanabilmesi için click eventi ekleniyor.
  1833. $('#section-inner-container').after('<div id="scriptMenuToggleBtn" class="active"></div>');
  1834. $('#scriptMenuToggleBtn').click(function(){
  1835. let active = $(this).hasClass('active');
  1836. $(this)[active?'removeClass':'addClass']('active');
  1837. $('#ScriptMenu')[active?'slideUp':'slideDown']();
  1838. });
  1839.  
  1840. //Script menüsü butondan sonra ekleniyor.
  1841. $('#section-inner-container').after(
  1842. `<div id="ScriptMenu" class="box" style="position:absolute;">`+
  1843. ` <h2>${GetText('ScriptMenuTitle')}</h2>`+
  1844. ` <table class="table">`+
  1845. ` <thead>`+
  1846. ` <tr>`+
  1847. ` <th>${GetText('Explanation')}</th>`+
  1848. ` <th>${GetText('Action')}</th>`+
  1849. ` </tr>`+
  1850. ` </thead>`+
  1851. ` <tbody>`+
  1852. ` <tr class="odd">`+
  1853. ` <td>${GetText('DownloadData')}</td>`+
  1854. ` <td>${CreateButton('downloadValues', GetText('Download'), '', 'width:35px;')}</td>`+
  1855. ` </tr>`+
  1856. ` <tr class="even">`+
  1857. ` <td>${GetText('UploadDatas')}</td>`+
  1858. ` <td>${CreateButton('uploadValues', GetText('Load'), '', 'width:35px;')}</td>`+
  1859. ` </tr>`+
  1860. ` <tr class="odd">`+
  1861. ` <td>${GetText('DeleteData')}</td>`+
  1862. ` <td>${CreateButton('deleteValues', GetText('Delete'), '', 'width:35px;')}</td>`+
  1863. ` </tr>`+
  1864. ` <tr class="even">`+
  1865. ` <td>${GetText('GameLanguage')}</td>`+
  1866. ` <td>`+
  1867. ` <label class="menü">`+
  1868. ` <select id="gameLanguage" style="width:69px;margin:0 auto;text-align-last: center;">`+
  1869. ` <option selected value="${Tool.language}">${GetText('Language', {tag:0})} *</option>`+
  1870. ` </select>`+
  1871. ` </label>`+
  1872. ` </td>`+
  1873. ` </tr>`+
  1874. ` </tbody>`+
  1875. ` <tbody id="ExtraSettings" style="display:none;">`+
  1876. ` <tr class="odd">`+
  1877. ` <td>${GetText('TrainerLevelS')}</td>`+
  1878. ` <td>`+
  1879. ` <label class="menü">`+
  1880. ` <select id="AntrenörSeviyesi" k="trainerLevel" currentvalue="${Tool.trainerLevel}" style="width:55px; margin:0 auto; text-align-last:center;"></select>`+
  1881. ` </label>`+
  1882. ` </td>`+
  1883. ` </tr>`+
  1884. ` <tr class="even">`+
  1885. ` <td>${GetText('YoungTrainerLevelS')}</td>`+
  1886. ` <td>`+
  1887. ` <label class="menü">`+
  1888. ` <select id="GAntrenörSeviyesi" k="yTrainerLevel" currentvalue="${Tool.yTrainerLevel}" style="width:55px;margin:0 auto;text-align-last: center;"></select>`+
  1889. ` </label>`+
  1890. ` </td>`+
  1891. ` </tr>`+
  1892. ` <tr style="height:20px;line-height:20px;display:none;">`+
  1893. ` <td colspan="2" style="text-align:center;">${CreateButton('saveChangeProperties', GetText('Update'), '', 'padding:3px 8px; width:43px;')}</td>`+
  1894. ` </tr>`+
  1895. ` </tbody>`+
  1896. ` <tfoot>`+
  1897. ` <tr style="line-height:10px;height:10px;">`+
  1898. ` <td colspan="2">`+
  1899. ` <p style="width: 60px;border-top:1px solid gray;margin:0 auto 2px;">`+
  1900. ` <img id="toggleExtraSettings" src="${Tool.sources.getLink('https://img.favpng.com/11/7/10/computer-icons-eye-png-favpng-b9eV1DRv9qP55UTXxRh6EACiV.jpg')}" alt="show" height="15px" width="25px" style="cursor:pointer;margin-top:10px;">`+
  1901. ` </p>`+
  1902. ` </td>`+
  1903. ` </tr>`+
  1904. ` </tfoot>`+
  1905. ` </table>`+
  1906.  
  1907. //Scriptin özelliklerinin gösterileceği tablo ekleniyor.
  1908. ` <table id="featureList" class="table" style="margin-Top:10px;display:none;table-layout:fixed;">`+
  1909. ` <thead>`+
  1910. ` <tr style="background:none;">`+
  1911. ` <th width="60%">${GetText('Features')}</th>`+
  1912. ` <th>${GetText('Action')}</th>`+
  1913. ` </tr>`+
  1914. ` </thead>`+
  1915. ` <tbody></tbody>`+
  1916. ` </table>`+
  1917.  
  1918. //Script menüsünün en alt kısmı ekleniyor.
  1919. ` <div style="font-family:Comic Sans MS; color:white; font-weight:bold; background-color:black; margin:15px -5px -6px -5px; border-radius: 0 0 6px 6px; padding:5px 0; text-align:center;">`+
  1920. ` <p style="font-size:10px;margin:0;">`+
  1921. ` ${GetText('QuestionHelp')} : `+
  1922. ` <a href="https://forum.fussballcup.de/showthread.php?t=417372&page=22 "style="color:#14ffff; text-decoration:none; font-size:10px;" target="_blank">`+
  1923. ` ${GetText('ClickMe')}`+
  1924. ` </a>`+
  1925. ` </p>`+
  1926. ` <p style="font-size:10px;margin:0;">`+
  1927. ` ${GetText('ScriptWriter')} : `+
  1928. ` <a href="#/index.php?w=${worldId}&area=user&module=profile&action=show&clubId=${Tool.ScriptAuthorClubId}" style="color:#14ffff; text-decoration:none; cursor:pointer; font-size: 10px;">`+
  1929. ` Criyessei | mot33`+
  1930. ` </a>`+
  1931. ` </p>`+
  1932. ` </div>`+
  1933. `</div>`
  1934. );
  1935.  
  1936. //Script menüsüne seçili dil eklenmiş durumda fakat diğer diller şimdi ekleniyor.
  1937. for(let [key,name] of Object.entries(Translate.locale.texts.OtherLanguages)) $('#gameLanguage').append(`<option value="${key}">${name}</option>`);
  1938.  
  1939. let selects = $('#AntrenörSeviyesi, #GAntrenörSeviyesi');
  1940. for(let lvl=10; lvl>-1; lvl--) selects.append(`<option value="${lvl}">${lvl} ${GetText('SortLevel', {tag:0})}</option>`)
  1941.  
  1942. //Geçerli olan antrenör ve genç antrenör seviyeleri aktif ediliyor ve sonlarına ' *' ekleniyor.
  1943. $('#AntrenörSeviyesi').val(Tool.trainerLevel);
  1944. $('#AntrenörSeviyesi > option:selected')[0].innerHTML+=' *';
  1945. $('#GAntrenörSeviyesi').val(Tool.yTrainerLevel);
  1946. $('#GAntrenörSeviyesi > option:selected')[0].innerHTML+=' *';
  1947.  
  1948. //CSS Ekle
  1949. $('head').append('<link id="font-awesome" rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">');
  1950. GM_addStyle(`.disHighlight{ user-select: none; -webkit-user-select: none; -ms-user-select: none; -webkit-touch-callout: none; -o-user-select: none; -moz-user-select: none; } @keyframes flickerAnimation { 0% { opacity:1; } 50% { opacity:0; } 100% { opacity:1; } } @-o-keyframes flickerAnimation{ 0% { opacity:1; } 50% { opacity:0; } 100% { opacity:1; } } @-moz-keyframes flickerAnimation{ 0% { opacity:1; } 50% { opacity:0; } 100% { opacity:1; } } @-webkit-keyframes flickerAnimation{ 0% { opacity:1; } 50% { opacity:0; } 100% { opacity:1; } } .animate-flicker { -webkit-animation: flickerAnimation 1s infinite; -moz-animation: flickerAnimation 1s infinite; -o-animation: flickerAnimation 1s infinite; animation: flickerAnimation 1s infinite; } #scriptMenuToggleBtn{ position:absolute; top:-44px; right:-23px; height:40px; width:40px; background-image: url(https://i.ibb.co/tJC5RX3/HFWRRt6.png); z-index:20; opacity:.5; cursor:pointer; } #scriptMenuToggleBtn:hover , #scriptMenuToggleBtn.active{ opacity:1; } #ScriptMenu > table > tbody > tr > td{ word-wrap: break-word; white-space: normal; line-height: 15.5px; padding:3px 6px; } #ScriptMenu{ z-index:10; position: absolute; width: 180px; background: white; top: 0; right: -180px; overflow-wrap: break-word; display: block; margin: 0 auto; padding:5px; border-radius: 8px; font-size:10px; border: 1px solid black!important; box-sizing: border-box; } #ScriptMenu > h2{ width: 100%; color: white; font-weight: bold; border: 0; margin: -5px 0 0 -5px; text-align: center; font-size: 14px; height: 30px; background:url(/designs/redesign/images/layout/headlines_sprite.gif) 0 -70px repeat-x; border-radius: 7px 7px 0 0; margin-bottom:5px; cursor:move; } table.table thead th:first-of-type{ border-radius : 7px 0 0 7px; } table.table thead th:last-of-type{ border-radius : 0 7px 7px 0; } table.table th{ background : #c01700; } table.table tbody tr.even > td{ background: #eee; } table.table tbody tr > td:first-of-type{ padding-left:5px; text-align:left; } table.table tbody tr.even > td:first-of-type{ border-radius : 7px 0 0 7px; } table.table tbody tr.even > td:last-of-type{ border-radius : 0 7px 7px 0; } table.table tbody td{ border-bottom: 0; } div.box p{ margin-Bottom:5px; } .slideThree input[type=checkbox]{ visibility: hidden; } .slideThree { width: 55px; height: 21px; background: #333; margin: 0; -webkit-border-radius: 55px; -moz-border-radius: 50px; border-radius: 50px; position: relative; -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2); -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2); box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2); } .slideThree:after { content: \'Off\'; font: 9px/26px Arial, sans-serif; color: red; position: absolute; right: 7px; top: -2px; z-index: 0; font-weight: bold; text-shadow: 1px 1px 0px rgba(255,255,255,.15); } .slideThree:before { content: \'On\'; font: 9px/26px Arial, sans-serif; color: #00bf00; position: absolute; left: 7px; top: -2px; z-index: 0; font-weight: bold; } .slideThree label { display: block; width: 25px; height: 17px; -webkit-border-radius: 50px; -moz-border-radius: 50px; border-radius: 50px; -webkit-transition: all .4s ease; -moz-transition: all .4s ease; -o-transition: all .4s ease; -ms-transition: all .4s ease; transition: all .4s ease; cursor: pointer; position: absolute; top: 2px; left: 3px; z-index: 1; -webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3); -moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3); box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3); background: #fcfff4; background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%); background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%); background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%); background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%); background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\'#fcfff4\', endColorstr=\'#b3bead\',GradientType=0 ); } .slideThree input[type=checkbox]:checked + label { left: 26px; } label.menü > select { padding:4px; margin: 0; -webkit-border-radius:9px; -moz-border-radius:4px; border-radius:4px; -webkit-box-shadow: 0 px 0 #ccc, 0 -1px #fff inset; -moz-box-shadow: 0 2px 0 #ccc, 0 -1px #fff inset; box-shadow: 0 2px 0 #ccc, 0 -1px #fff inset; background: #f8f8f8; color:#888; border:none; outline:none; display: inline-block; -webkit-appearance:none; -moz-appearance:none; appearance:none; cursor:pointer; } label.menü > select { padding-right:18px; font-size:9px; width:45px; margin:0 auto; text-align-last: center; } label.menü { position:relative } label.menü:after { content:'<>'; font:8px \"Consolas\", monospace; color:#aaa; -webkit-transform:rotate(90deg); -moz-transform:rotate(90deg); -ms-transform:rotate(90deg); transform:rotate(90deg); right:2px; top:2px; padding:0 0 2px; border-bottom:0px solid #ddd; position:absolute; pointer-events:none; } label.menü:before { content:''; right:0px; top:0px; width:5px; height:px; background:#f8f8f8; position:absolute; pointer-events:none; display:block; } @keyframes fadeInDown { 0% { opacity: 0; transform: translateY(-1.25em); } 100% { opacity: 1; transform: translateY(0); } } .openClose[open] { animation-name: fadeInDown; animation-duration: 0.5s; } @keyframes fadeInDown { 0% { opacity: 0; transform: translateY(-1.25em); } 100% { opacity: 1; transform: translateY(0); } } .details5[open] { animation-name: fadeInDown; animation-duration: 0.5s; } @keyframes fadeInUp { 0% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(-1.25em); } } .openClose[close] { animation-name: fadeInUp; animation-duration: 0.5s; } .checkbox_1 { display: none; } .checkbox_1 + label:before { cursor: pointer; content: \'\\2714\'; border: 0.1em solid #d95555; border-radius: 0.2em; display: inline-block; width: 1.1em; height: 1em; padding-left: 0em; padding-bottom: 0.3em; padding-top:-0.1em; margin-right: 0em; vertical-align: middle; text-align:center; color: #d95555; transition: .2s; } .checkbox_1 + label:active:before { transform: scale(0); } .checkbox_1:checked + label:before{ background-color: red; border-color: red; color: #fff; } /*** custom checkboxes ***/ .checkbox_2 { display:none; } /* to hide the checkbox itself */ .checkbox_2 + label:before { font-family: FontAwesome; display: inline-block; } .checkbox_2 + label:before { content: \'\\f096\'; } /* unchecked icon */ .checkbox_2 + label:before { letter-spacing: 2px; } /* space between checkbox and label */ .checkbox_2:not(:checked):hover + label:before{content: \'\\f046\';color:#6f6e6e;letter-spacing: 0;} .checkbox_2:checked + label:before { content: \'\\f046\'; } /* checked icon */ .checkbox_2:checked + label:before { letter-spacing: 0; } /* allow space for check mark */ .sorting_players{ font-size:10px; text-align:center; padding:5px 0; margin-bottom: 9px; border-bottom: 1px solid white; line-height:1.5; } .sorting_players > label{ display:inline-block; } .sorting_players > label:not(:first-child){ margin-left:8px; } .sorting_players > label > input{ vertical-align:middle; margin:-3px 1px 0 0; cursor:pointer; } .sorting_players st{ color:#c8c7c7; } .sorting_players input:checked + st{ color : #04da97; } .filterByPositions{ margin: -3px 0 7px; text-align: center; } .filterByPositions > .filter_position{ border-radius: 20%; background-color:green; cursor: pointer; display:inline-block; padding:2px 0; font-size: 8px; color: white; min-width: 20px; opacity:1; margin:2px; } .filterByPositions > .filter_position.not_active{ opacity:0.3; } .grow,.grow2 { transition: all .2s ease-in-out; } .grow:hover { transform: scale(1.1); } .grow2:hover{ transform: scale(1.5); } .slider { -webkit-appearance: none; width: 100%; height: 20px; background: #d3d3d3; outline: none; opacity: 0.7; -webkit-transition: .2s; transition: opacity .2s; } .slider:hover { opacity: 1; } .slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; border-radius:6px; width: 30px; height: 20px; background: #4CAF50; cursor: pointer; } .slider::-moz-range-thumb { border-radius:6px; width: 30px; height: 20px; background: #4CAF50; cursor: pointer; }`);
  1951.  
  1952. //For Features Table
  1953. this.featuresList = {
  1954. clear:function(){
  1955. $('#featureList > tbody').html('');
  1956. $('#featureList > tbody').parent().hide();
  1957. },
  1958. show:function(features){
  1959. let counter=0;
  1960. features.forEach(feature=>{
  1961. let div = $('<div class="slideThree"></div>'),
  1962. featureId = feature.name,
  1963. featureName = Translate.locale.texts.FeaturesName[featureId] || featureId;
  1964. if(feature.hover_selector!=undefined){
  1965. div.attr('hover_selector',feature.hover_selector);
  1966. $(feature.hover_selector).css('transition','background-color 1s;');
  1967. }
  1968. div.append(
  1969. `<input type="checkbox" id="${featureId}" class="slideThreeInput" ${feature.active?'checked="checked"':''}>`+
  1970. `<label for="${featureId}"></label>`
  1971. );
  1972. $('#featureList > tbody').append(
  1973. `<tr class="${counter++%2?'even':'odd'}">`+
  1974. ` <td><label k="${featureId}">${featureName}</label></td>`+
  1975. ` <td>${div[0].outerHTML}</td>`+
  1976. '</tr>'
  1977. );
  1978. if(feature.active && !feature.work){
  1979. $('#featureList > tbody > tr:last > td:first').css({
  1980. 'color':'#e23f3fb5',
  1981. 'font-style':'italic'
  1982. });
  1983. }
  1984. });
  1985.  
  1986. if(counter>0){
  1987. $('#featureList > tbody').parent().show();
  1988. $('#featureList > tbody > tr .slideThreeInput').click(function(){
  1989. console.log(this);
  1990. Tool.features.getByName(this.id)[this.checked?'activate':'deactivate']();
  1991. Tool.setVal('featuresActiveStatus',Tool.features.reduce((acc,feature)=>{acc[feature.name]=feature.active;return acc},{}));
  1992. if(!this.checked) $('.addedBy_'+this.id).remove();
  1993. });
  1994. $('#featureList > tbody .slideThreeInput:checked').parent('[hover_selector]').mouseenter(function(){
  1995. $($(this).attr('hover_selector')).addClass('animate-flicker').css('background-color','#910e0ea8');
  1996. }).mouseleave(function(){
  1997. $($(this).attr('hover_selector')).removeClass('animate-flicker').css('background-color','');
  1998. });
  1999. }
  2000. else{
  2001. $('#featureList > tbody').parent().hide();
  2002. }
  2003. }
  2004. }
  2005. }
  2006. createMenuEvents(){
  2007. delete this.__proto__.createMenuEvents;
  2008.  
  2009. //Script menüsü hareket ettirilebilecek.
  2010. $("#ScriptMenu").draggable({ handle: "h2" });
  2011.  
  2012. //Oyun dili değiştirilmek istendiğinde yapılacak kodlar ekleniyor.
  2013. $('#gameLanguage').change(function(){
  2014. //Select box kitleniyor.Bu sayede dil değiştirilene kadar tekrar değiştirilmesine izin verilmiyor.
  2015. this.disabled = true;
  2016. this.style.cursor = 'not-allowed';
  2017.  
  2018. //Change Language
  2019. let result = Translate.changeLanguage(this.value, this.selectedIndex);
  2020. if(result.status=='success'){
  2021. Tool.language = Translate.locale.name;
  2022.  
  2023. //Update User Servers Language Preferences
  2024. let userLanguage = GM_getValue('userLanguage',{});
  2025. if(typeof userLanguage != 'object') userLanguage = {};
  2026. userLanguage[Game.server] = Tool.language;
  2027. GM_setValue('userLanguage', userLanguage);
  2028. }
  2029. else{
  2030. Game.giveNotification(false, result.msg);
  2031. throw new Error(JSON.stringify(result, null, '\t'));
  2032. }
  2033.  
  2034. //Kitlenen select box açılıyor.
  2035. this.disabled = false;
  2036. this.style.cursor = '';
  2037. });
  2038.  
  2039. //Script menüsünde çok yer kaplamaması için gizlenen antrenör ve genç antrenör select boxlarının gizlenip-gösterilebilmesi için click eventi oluşturuluyor.
  2040. $('#toggleExtraSettings').click(function(){
  2041. $('#ExtraSettings').toggle();
  2042. let a = $('#toggleExtraSettings').attr('alt')=='hide'?'show':'hide';
  2043. $(this).attr({
  2044. 'src': Tool.sources.getLink('https://img.favpng.com/11/7/10/computer-icons-eye-png-favpng-b9eV1DRv9qP55UTXxRh6EACiV.jpg'),
  2045. 'alt': a
  2046. });
  2047. if(a=='hide' && $('#saveChangeProperties').parents('tr:first').is(':visible')){ //Restore
  2048. $('#AntrenörSeviyesi').val($('#AntrenörSeviyesi').attr('currentvalue'));
  2049. $('#GAntrenörSeviyesi').val($('#GAntrenörSeviyesi').attr('currentvalue'));
  2050. $('#saveChangeProperties').parents('tr').first().hide();
  2051. }
  2052. });
  2053.  
  2054. //Antrenör veya genç antrenör seviyesi güncel seviyesinden farklı olursa kayıt etme butonu gösteriliyor,aksi taktirde gizleniyor.
  2055. $('#AntrenörSeviyesi').add($('#GAntrenörSeviyesi')).change(function(){
  2056. let o=$('#'+(this.id=='AntrenörSeviyesi'?'GAntrenörSeviyesi':'AntrenörSeviyesi'));
  2057. $('#saveChangeProperties').parents('tr').first()[
  2058. this.value!=$(this).attr('currentvalue') || o.val()!=o.attr('currentvalue')?'show':'hide'
  2059. ]();
  2060. });
  2061.  
  2062. //Değiştirilen antrenör ve|veya genç antrenör seviyeleri kayıt ediliyor ve sayfa yenilenerek değişikli(ğin|klerin) gösterilmesi sağlanıyor.
  2063. $('#saveChangeProperties').click(function(){
  2064. $(this).parents('tr').first().hide();
  2065. let clubDatas = Tool.getVal('clubDatas');
  2066. clubDatas.trainerLevel = parseInt($('#AntrenörSeviyesi').val());
  2067. clubDatas.yTrainerLevel = parseInt($('#GAntrenörSeviyesi').val());
  2068. Tool.setVal('clubDatas',clubDatas);
  2069. location.reload();
  2070. });
  2071.  
  2072. //Script verilerilerinin indirilmesi
  2073. $('#downloadValues').click(function(){
  2074. let cookies = GM_listValues().sort(function(a,b){
  2075. let s1=a.substring(0,a.indexOf('_')+1),
  2076. s2=b.substring(0,b.indexOf('_')+1);
  2077. if((a=a.substring(a.indexOf('_')+1))>(b=b.substring(b.indexOf('_')+1))) return 1;
  2078. else if(a<b) return -1;
  2079. return s1>s2;
  2080. }),
  2081. cookiesText = '',
  2082. ekle='',
  2083. veri;
  2084. for(let i = 0; i < cookies.length ; i++){
  2085. ekle = '';
  2086. if(!(veri = GM_getValue(cookies[i]))) continue;
  2087. ekle = Array.isArray(veri)?returnArrayString(veri):JSON.stringify(veri,null,'\t');
  2088. cookiesText +='CookieKey&:'+cookies[i]+':'+ekle+'\n\n';
  2089. }
  2090. if(cookiesText.trim()) DownloadAsTextFile(cookiesText,'Fcup Script Datas');
  2091. else Game.giveNotification(false, GetText('NotDataExist'));
  2092. function returnArrayString(array){
  2093. let o='[';
  2094. for(let i = 0 ; i < array.length ; i++){
  2095. o+=Array.isArray(array[i])?returnArrayString(array[i]):JSON.stringify(array[i],null,'\t')+',';
  2096. }
  2097. o = o.substring(0,o.length-1)+']';
  2098. return o;
  2099. }
  2100. });
  2101.  
  2102. //İndirilen script verilerinin yüklenmesi
  2103. $('#uploadValues').click(function(){
  2104. ReadTextFile((valuesText)=>{
  2105. valuesText.split('CookieKey&:').slice(1).forEach(data=>{
  2106. let b = data.indexOf(':');
  2107. GM_setValue(data.substring(0,b),JSON.parse(data.substring(b+1)));
  2108. });
  2109. Tool.fixValues();
  2110. Game.giveNotification(true, GetText('DataLoaded')+'!!');
  2111. location.reload();
  2112. });
  2113. });
  2114.  
  2115. //Scriptin sıfırlanması
  2116. $('#deleteValues').click(function(){
  2117. let globaldatas = GM_listValues().filter(key=>{return key.indexOf('_')==-1}),
  2118. opt = ["1","2"],
  2119. exit = "3";
  2120. if(globaldatas.length!=0){
  2121. opt.push("3");
  2122. exit = "4";
  2123. };
  2124. let wrongChoise = $(this).attr('wrong_choise'),
  2125. choise = prompt(
  2126. (wrongChoise==undefined?"":"Wrong choise: "+wrongChoise+"\n\n")+
  2127. "1: Delete all servers datas\n"+
  2128. "2: Delete all current server["+Game.server+"] datas\n"+
  2129. (globaldatas.length==0?"":"3: Delete global datas: "+globaldatas.join(', ')+"\n")+
  2130. exit+": Exit\n"+
  2131. "Enter your choise:",2
  2132. );
  2133. $(this).removeAttr('wrong_choise');
  2134.  
  2135. if(choise==null || choise==exit) return;
  2136. if(!opt.includes(choise)){
  2137. $('#deleteValues').attr('wrong_choise',choise).click();
  2138. return;
  2139. }
  2140.  
  2141. let keys;
  2142. if(choise=="1") //Delete all servers datas
  2143. keys = GM_listValues();
  2144. else if(choise=="2"){ //Delete current server datas
  2145. keys = GM_listValues().filter(key=>{
  2146. let find = key.indexOf('_');
  2147. return find!=-1 && key.substring(0,find).trim() == Game.server
  2148. });
  2149. }
  2150. else keys = globaldatas;
  2151.  
  2152. keys.forEach(key=>GM_deleteValue(key));
  2153. Game.giveNotification(true, GetText('DataCleared'));
  2154. location.reload();
  2155. });
  2156. }
  2157. checkVersion(){
  2158. delete this.__proto__.checkVersion;
  2159.  
  2160. GM_xmlhttpRequest({
  2161. method: "GET",
  2162. url: "https://greasyfork.org/scripts/40715-fcup-script/code/FCup%20Script.meta.js",
  2163. onload: function(response) {
  2164. let text = response.responseText,
  2165. b = text.indexOf('@version')+8,
  2166. b1 = text.indexOf('/',b),
  2167. version = text.substring(b,b1).trim(),
  2168. currentVersion = GM_info.script.version;
  2169. if(version!=currentVersion){
  2170. let header = {
  2171. css : {'text-align':'center'},
  2172. content :
  2173. `<span class="icon" style="background:url(/designs/redesign/images/layout/icons_sprite.png?v=2.2.6.14231) 0 -1180px no-repeat;margin-Right:10px;float:left;margin:6px;"></span>`+
  2174. GetText('ReleasedVersion', {args:[version]})
  2175. };
  2176. let div = {
  2177. footer : !0,
  2178. close : !0,
  2179. class : 'container'
  2180. };
  2181. div.content =
  2182. `<img src="https://image.ibb.co/jrcFap/Untitled.png" style="height:73px; float:left; margin:-15px 0 0 -15px;">`+
  2183. `<p style="font-size:15px; margin-Bottom:10px; font-weight:bold; color:red; text-align:center;">`+
  2184. ` ${GetText('CurrentVersion')+' '+currentVersion}`+
  2185. ` <label style="color:green; margin-Left:50px;">${GetText('NewVersion')+" : "+ version}</label>`+
  2186. `</p>`+
  2187. `<p style="font-size:14px; font-weight:bold; color:blue;">`+
  2188. ` ${GetText('UpdateTheScriptInfo', {args:['<a href="https://greasyfork.org/scripts/40715-fcup-script/code/FCup%20Script.user.js" style="font-size:14px">','</a>']})}`+
  2189. `</p>`+
  2190. `<p style="margin-Top:20px;text-align:center;">${CreateButton('relaodPage', GetText('RefreshPage'))}</p>`;
  2191. ShowDialog(div,header);
  2192. $('#relaodPage').click(()=>location.reload());
  2193. }
  2194. else console.log('[Version control] => %cVersion up to date.','color:green;');
  2195. },
  2196. onerror: function() {
  2197. console.log('[Version control] => %cFail!','color:red;');
  2198. }
  2199. });
  2200. }
  2201. createNoticeArea(){
  2202. delete this.__proto__.createNoticeArea;
  2203.  
  2204. GM_addStyle(`#notice_in { color: white; font-size: 12px; background-color: #088A08; padding: 3px; width: 130px; margin: auto; border-radius: 10px; cursor: pointer; letter-spacing: 0.11em; } #notice_out { width: 100%; background-color: transparent; padding: 10px; border: 0px solid #088A08; } #Notizbereich { position: static; margin: 5px; height: 150px; background-color: #FFFFFF; border: 1px solid #DF0101; border-radius: 10px; padding: 4px 5px; min-height: 59px; min-width: 345px; } .notiz_button { border-radius: 12px; background-color: #B40404; border: none; color: #FFFFFF; text-align: center; font-size: 13px; padding: 4px; width: 106px; transition: all 0.5s; cursor: pointer; margin: 2px 8px; }`);
  2205. $('body').prepend(
  2206. `<div id="notice_area">`+
  2207. ` <div id="notice_in" class="disHighlight" lock="0">${GetText('OpenNote')}</div>`+
  2208. ` <div id="notice_out">`+
  2209. ` <p>`+
  2210. ` <textarea id="Notizbereich" cols="80" rows="5" placeholder="${GetText('WriteANote', {tag:0})}" tool_pt="WriteANote" style="max-width:${$('#header').width()}px;">${Tool.getVal('Notiz','')}</textarea>`+
  2211. ` <p>`+
  2212. ` <input id="notiz_save_btn" class="notiz_button" type="button" value="${GetText('SaveNote', {tag:0})}" tool_vt="SaveNote">`+
  2213. ` <input id="notiz_clr_btn" class="notiz_button" type="button" value="${GetText('ClearField', {tag:0})}" tool_vt="ClearField">`+
  2214. ` </p>`+
  2215. ` </p>`+
  2216. ` <p>`+
  2217. ` <font id="change_clue" style="color:#1C6125;border-radius:7px;padding:3px 4px;text-align:center;opacity:0;"></font>`+
  2218. ` </p>`+
  2219. ` </div>`+
  2220. `</div>`
  2221. );
  2222. $('#notice_out').attr('outerHeight',$('#notice_out').outerHeight()).hide();
  2223. $("#chatToggleBtn").css('top','+='+$('#notice_area').outerHeight()+'px');//Düzenleme yapılıyor.
  2224.  
  2225. $('#notice_in').click(function(){
  2226. if($(this).attr('lock')!=0) return;
  2227. $(this).attr('lock',1);
  2228.  
  2229. let open = !$('#notice_out').is(':visible'),
  2230. time = 750;
  2231. $('#notice_in').html(open?GetText('CloseNote'):GetText('OpenNote'));
  2232.  
  2233. $('#notice_out').slideToggle(time);
  2234. $("#chatToggleBtn").animate({ "top": (open?"+":"-")+"="+$('#notice_out').attr('outerHeight')+"px" }, time);
  2235. setTimeout(()=>{ $(this).attr('lock',0); },time);
  2236. });
  2237.  
  2238. $('#notiz_save_btn').click(function(){
  2239. Tool.setVal('Notiz', $('#Notizbereich').val());
  2240. change_clue(GetText('SavedNote'));
  2241. });
  2242. $('#notiz_clr_btn').click(function(){
  2243. $('#Notizbereich').val('');
  2244. Tool.delVal('Notiz');
  2245. change_clue(GetText('ClearedNote'));
  2246. });
  2247.  
  2248. let interval;
  2249. function change_clue(value){
  2250. $('#change_clue').animate({'opacity':1});
  2251. clearTimeout(interval);
  2252. $('#change_clue').html(value);
  2253. interval = setTimeout(function() {
  2254. $('#change_clue').animate({'opacity':0},200);
  2255. setTimeout(()=>{
  2256. $('#change_clue').html('');
  2257. },200);
  2258. }, 2800);
  2259. }
  2260. }
  2261.  
  2262. pipe(func=()=>{}){func(Tool)}
  2263.  
  2264. printValues(){
  2265. delete this.__proto__.printValues;
  2266. console.clear();
  2267. let values = this.fixValues();
  2268. if(!values.length){
  2269. console.log("%c! ANY COOKIES ARE EXIST",'color:red;font-weight:bold;font-size:15px;');
  2270. return;
  2271. }
  2272.  
  2273. console.log("%cVALUES","color:white;text-align:center;font-size:15px;padding:2px 500px;background-color:black;border-radius:7px;text-weight:bold;display:inline;");
  2274. values.sort(function(a,b){
  2275. let s1=a.substring(0,a.indexOf('_')+1),
  2276. s2=b.substring(0,b.indexOf('_')+1);
  2277. if((a=a.substring(a.indexOf('_')+1))>(b=b.substring(b.indexOf('_')+1))) return 1;
  2278. else if(a<b) return -1;
  2279. return s1>s2;
  2280. });
  2281.  
  2282. let maxLongKey = values.reduce((acc,val)=>{return Math.max(acc,val);},-1);
  2283. values.forEach(cookieKey=>{
  2284. let find = cookieKey.indexOf('_');
  2285. console.log(
  2286. '%c' + cookieKey.substring(0,find) + '%c' + (find!=-1?'_':' ') + '%c' + cookieKey.substring(find+1) + (" ").repeat(Math.abs(maxLongKey-cookieKey.length+(find!=-1?0:-3))) + ' %c: %c%o',
  2287. 'font-weight:bold;color:blue;',
  2288. 'font-weight:bold;color:orange;',
  2289. 'font-weight:bold;color:green;',
  2290. 'font-weight:bold;color:black;',
  2291. 'color:black;',
  2292. GM_getValue(cookieKey)
  2293. );
  2294. });
  2295. console.log('\n');
  2296. }
  2297. fixValues(valuesList=GM_listValues()){
  2298. for(let i=0,find,server,valueKey,valueName,deleteValue ; i < valuesList.length ; i++){
  2299. valueKey = valuesList[i];
  2300. deleteValue = !1;
  2301.  
  2302. if((find=valueKey.indexOf('_'))==-1) server=null;
  2303. else server = valueKey.substring(0,find);
  2304.  
  2305. switch(valueName=valueKey.substring(find+1)){
  2306. case 'clubDatas':
  2307. var clubDatas = GM_getValue(valueKey);
  2308. if(typeof clubDatas == 'object'){
  2309. if(clubDatas.hasOwnProperty('trainingProgram')){
  2310. delete clubDatas.trainingProgram;
  2311. GM_setValue(valueKey,clubDatas);
  2312. }
  2313. }
  2314. else deleteValue = !0;
  2315. break;
  2316. case 'LeagueData':
  2317. var LeagueData = GM_getValue(valueKey);
  2318. if(typeof LeagueData == 'object' && !$.isEmptyObject(LeagueData)){
  2319. if(LeagueData.hasOwnProperty('IlkMacTarihi')){
  2320. LeagueData.firstMatchDate = LeagueData.IlkMacTarihi;
  2321. LeagueData.firstHalfFinalMatchDate = LeagueData.IlkYarıSonMacTarihi;
  2322. LeagueData.lastMatchDate = LeagueData.SonMacTarihi;
  2323. LeagueData.league = LeagueData.lig;
  2324. delete LeagueData.IlkMacTarihi;
  2325. delete LeagueData.IlkYarıSonMacTarihi;
  2326. delete LeagueData.SonMacTarihi;
  2327. delete LeagueData.lig;
  2328. GM_setValue(valueKey,LeagueData);
  2329. }
  2330. }
  2331. else deleteValue = !0;
  2332. break;
  2333. /*case 'ClubExchange':
  2334. let ClubExchange = GM_getValue(cookieKey);
  2335. if(typeof ClubExchange == 'object' && !$.isEmptyObject(ClubExchange)){
  2336. for(let PlayerId in ClubExchange){
  2337. let date = ClubExchange.date; //03.02.2019
  2338. }
  2339. }
  2340. else deleteCookie = !0;
  2341. break;
  2342. case 'YoungPlayers':
  2343. let YoungPlayers = GM_getValue(cookieKey);
  2344. if(typeof YoungPlayers == 'object'){
  2345.  
  2346. }
  2347. else deleteCookie = !0;
  2348. break;*/
  2349. case 'AutomaticTraining':case 'PlayersHealth':case 'SquadsStrength':
  2350. deleteValue = !0;
  2351. break;
  2352. case 'FeaturesOfScript': case 'featuresActiveStatus':
  2353. var featuresActiveStatus = GM_getValue(valueKey);
  2354. if(valueName=='FeaturesOfScript'){
  2355. GM_setValue(server+'_featuresActiveStatus',featuresActiveStatus);
  2356. GM_deleteValue(valueKey);
  2357. }
  2358.  
  2359. if(typeof featuresActiveStatus == 'object'){
  2360. let changed = 0;
  2361. if(featuresActiveStatus.PlayersHealth){
  2362. delete featuresActiveStatus.PlayersHealth;
  2363. changed++;
  2364. }
  2365. /*
  2366. ...
  2367. */
  2368. if(changed){
  2369. if($.isEmptyObject(featuresActiveStatus)) deleteValue = !0;
  2370. else GM_setValue(valueKey,featuresActiveStatus);
  2371. }
  2372. }
  2373. break;
  2374. case 'YoungPlayers':
  2375. var YoungPlayers = GM_getValue(valueKey), //Structure: http://prntscr.com/ucg9s3
  2376. updated = 0;
  2377. if(typeof YoungPlayers != 'object') YoungPlayers = {};
  2378. if(typeof YoungPlayers.MessageBox != 'object'){ YoungPlayers.MessageBox = {}; ++updated; }
  2379. if(!Array.isArray(YoungPlayers.show)){ YoungPlayers.show = []; ++updated; }
  2380.  
  2381. var MessageBox = YoungPlayers.MessageBox,
  2382. show = YoungPlayers.show;
  2383. for(let playerName in MessageBox){
  2384. var date = MessageBox[playerName];
  2385. if(show.find(p=>{return p.name==playerName && p.date==date;}) != undefined){ //eslint-disable-line no-loop-func
  2386. delete MessageBox[playerName];
  2387. ++updated;
  2388. }
  2389. }
  2390. if(updated) GM_setValue(valueKey,YoungPlayers);
  2391. break;
  2392. }
  2393. if(deleteValue){
  2394. GM_deleteValue(valueKey);
  2395. valuesList.splice(i--,1);
  2396. }
  2397. }
  2398. return valuesList;
  2399. }
  2400. modifyGameFunction(funcName, callBack){
  2401. let v = unsafeWindow[funcName];
  2402. if(typeof v != 'function') throw new Error(`Game function(${funcName}) try to been modified but it was't found!`);
  2403. let codes = v.toString(),
  2404. anonFunc = codes.substring(0,codes.indexOf('(')).replace('function','').trim() == "";
  2405. $(`<script id="modifyFunction_${funcName}" type="text/javascript">`).html(
  2406. "/*This function was modified by FCUP Script*/\n"+
  2407. (anonFunc?'window.'+funcName+"=":"")+
  2408. codes.substring(0, codes.indexOf('{')+1) + callBack(codes.substring(codes.indexOf('{')+1, codes.lastIndexOf('}'))) + '}'
  2409. ).appendTo('body').remove();
  2410. }
  2411. setVal(key,data){
  2412. GM_setValue(Game.server+'_'+key, data);
  2413. }
  2414. getVal(key,defaultValue=undefined){
  2415. return GM_getValue(Game.server+'_'+key, defaultValue);
  2416. }
  2417. delVal(key){
  2418. GM_deleteValue(Game.server+'_'+key);
  2419. }
  2420. })();
  2421. unsafeWindow.toolPipe = Tool.pipe;
  2422.  
  2423. //Live game function is in minified.js that is external function in head tag. This function had been already declarated and it must be modify before first game page loaded.
  2424. //Before Sammy->get->updateLayout->$('#content').html(value)
  2425. Tool.modifyGameFunction('Live',content=>{
  2426. content = `\n\t$('#content > h2:first').append('<img src="https://cdn1.iconfinder.com/data/icons/interface-elements/32/accept-circle-512.png" height="25px" style="position:absolute;right: 3px;top: 3px;">');\n`+
  2427. content;
  2428. let b = content.search(/this.writeMessage\s*=\s*function/);
  2429. b = content.indexOf('{',b)+1;
  2430. b = content.indexOf('{',b)+1;
  2431. content = content.substring(0,b)+ GetFuncContent(()=>{
  2432. /*This codes were written by FCUP Script.*/
  2433. try{
  2434. var event_ = Object.assign({'_status': this.requestMin==0?'old':'new'}, arguments[1]);
  2435. if($("#MatchEventCatcher").length){
  2436. $("#MatchEventCatcher").trigger('click', [event_]);
  2437. }
  2438. else{ //Match event catcher not yet created
  2439. toolPipe(Tool=>{
  2440. if(!Tool.uncaught_events_queue) Tool.uncaught_events_queue = [];
  2441. Tool.uncaught_events_queue.push(event_);
  2442. });
  2443. }
  2444. }
  2445. catch(err){console.error('MatchEventCatcher Trigger ERROR: ' + err.message);}
  2446. }) + content.substring(b);
  2447.  
  2448. b = content.search(/this\s*\.\s*commit\s*=/);
  2449. let c = content.substring(b).search(/\$\s*\.\s*get/);
  2450. return content.substring(0, b+c) + GetFuncContent(()=>{
  2451. /*This codes were written by FCUP Script for Live League Table*/
  2452. $('#MatchEndCatcher').trigger('click', [this.matchId]);
  2453. }) + content.substring(b+c);
  2454. });
  2455.  
  2456. //Click event of .negotiation-bid-player is will declerate asap in body script tag.
  2457. //When the click event declarate, it will be deleted and new event created for them asap.
  2458. Tool.intervals.create(function(){
  2459. let events = unsafeWindow.jQuery._data($('body')[0], "events");
  2460. if(typeof events != 'object') return;
  2461. if(events.click.filter(e=>e.selector=='.negotiation-bid-player').length == 0) return;
  2462. this.delete();
  2463.  
  2464. unsafeWindow.jQuery('body')
  2465. .off('click', '.negotiation-bid-player')
  2466. .on('click', '.negotiation-bid-player', function(e) {
  2467. /* eslint no-multi-spaces: 0*/
  2468. /* global amountControl,durationControl,updateAds*/
  2469. let element = $(this), //Onaylama butonu
  2470. id = element.attr('unique'), //return player-29820872
  2471. playerId = element.attr('player'), //Oyuncunun id si alınıyor.
  2472. clubId = element.attr('club'), //Bizim kulüp id'imiz alınıyor.
  2473. offer = '', //Teklif ettiğimiz ücret
  2474. amount = '', //Oyuncuya vereceğimiz maaş
  2475. duration = '', //Oyuncuyla anlaşacağımız sezon sayısı
  2476. params, //Servere gönderilecek data
  2477. negotiation_type, //Müzakere tipi = [offer,negotiateDebts,negotiateWithOwnPlayer,acceptNegotiation]
  2478. pl; //Satın alınan oyuncunun isminin alınabilmesi için
  2479.  
  2480. //Onaylama butonu gizleniyor.
  2481. element.hide();
  2482.  
  2483. //Onaylama butonunun olduğu yere yükleniyor gifi ekleniyor.
  2484. element.parent().append($('<div class="load-icon loading" id="loading-'+id+'"></div>'));
  2485.  
  2486. if($('#bid-offer-'+id).length && $('#bid-offer-'+id).val()){ //Oyuncuyu satın almak için kulübe teklif ettiğimiz input mevcutsa ve değeri boş değilse
  2487. negotiation_type = 'offer'; //Oyuncuya teklif veriliyor.
  2488. $('#info-player-'+playerId+' .abort-negotiation-button-container').first().hide(); //Geri dönmeyi sağlayan buton gizleniyor.
  2489. offer = $('#bid-offer-' + id).val();
  2490. params = {//Example : {"elements": '{"offer":{"0":"1111;2222;3333"}}'}
  2491. 'elements': JSON.stringify({
  2492. 'offer': {
  2493. 0: playerId+';'+clubId+';'+offer
  2494. }
  2495. })
  2496. };
  2497. }
  2498. else if($('#bid-amount-' + id).length && $ ('#bid-amount-' + id).val()){ //Teklif ettiğimiz maaş inputu mevcutsa ve değeri boş değilse
  2499. if($('#own-offers').length){//Transfer pazarı sayfası açık ise ya kendi oyuncumuzla yeni sözleşme imzalıyoruz. Yada yeni bir oyuncu satın alırken futbolcuyla sözleşme imzalıyoruz.
  2500. if((pl = $('#own-offers').find('tbody > tr span[pid="player-'+playerId+'"]')).length){ //Sözleşme imzalanan oyuncu tekliflerimiz tablosunda ise yeni bir oyuncu alarak sözleşme imzalıyoruz
  2501. negotiation_type = 'negotiateDebts';
  2502. pl = pl.parents('tr').first();
  2503. }
  2504. else//Tekliflerimizin bulunduğu tabloda yoksa, kendi oyuncumuz ile sözleşme imzalıyoruzdur.
  2505. negotiation_type = 'negotiateWithOwnPlayer'; //Oyuncu ile sözleşme yapılıyor.
  2506. }
  2507. else //Transfer pazarı sayfası açık değil. Not : Burada sıkıntı olabilir.
  2508. negotiation_type = 'negotiateWithOwnPlayer';
  2509.  
  2510. amount = amountControl[id].numberUnFormat($('#bid-amount-'+id).val()); //Formatı sıfırlıyor.Noktalar kaldırılıyor.Artık integer.
  2511.  
  2512. if($('#bid-duration-' + id).length && $('#bid-duration-'+id).val()) //Teklif ettiğimiz sezon inputu mevcutsa ve değeri boş değilse
  2513. duration = durationControl[id].numberUnFormat($('#bid-duration-'+id).val()); //Formatı sıfırlıyor.Noktalar kaldırılıyor.
  2514.  
  2515. params = {//Example : {"elements":'{"negotiateDebts":{"0":"1111;2222;amount=33333;duration=3"}}'}
  2516. 'elements': JSON.stringify({
  2517. 'negotiateDebts': {
  2518. 0: playerId+';'+clubId+';amount='+amount+';duration='+duration
  2519. }
  2520. })
  2521. };
  2522. }
  2523. else{
  2524. negotiation_type = 'acceptNegotiation'; //Gözlemcinin getirdiği oyuncu için kapora ödeniyor.
  2525. params = { //Example : {"elements":'{"acceptNegotiation":{"0":"1111;2222"}}'}
  2526. 'elements': JSON.stringify({'acceptNegotiation': {0: playerId+';'+clubId}})
  2527. };
  2528. }
  2529.  
  2530. $.get( //Servere istek gönderiliyor.
  2531. '/index.php?w='+worldId+'&area=user&module=player&action=negotiate&complex=0',
  2532. params,
  2533. function(response) { //İstek başarılı oldu!
  2534. $('#loading-'+id).remove(); //Yükleniyor gifi kaldırılıyor.
  2535. let div = $('<div>').html(response);
  2536. try{
  2537. let texts,negotiate_success = !1;
  2538. switch(negotiation_type){
  2539. case "offer":case "acceptNegotiation":break;
  2540. case "negotiateDebts": //Yeni bir oyuncu satın alırken kontrat yapıyoruz
  2541. case "negotiateWithOwnPlayer": //Kendi oyuncumuzla kontrat yeniliyoruz
  2542. div.find('script').each(function(i){
  2543. texts = $(this).html();
  2544. //window.location.href = $('span[pid=player-' + 29823205 + ']').first().attr('ref')
  2545. if(-1 != texts.search(new RegExp(`window\\s*.\\s*location\\s*.\\s*href\\s*=\\s*\\$\\s*\\(\\s*'span\\[pid=player-'\\s*\\+\\s*${playerId}\\s*\\+\\s*']'\\s*\\)`))){
  2546. div.find('script')[i].remove();
  2547. negotiate_success = !0;
  2548. let notification_text;
  2549. if(negotiation_type=="negotiateWithOwnPlayer"){//Kendi oyuncumuz ile başarılı bir şekilde sözleşme imzaladık!
  2550. notification_text = GetText('SuccessfullyContract');
  2551. }
  2552. else{//Yeni bir oyuncuyu sözleşme imzalayarak satın aldık.
  2553. let data = Tool.getVal('PlayersData',{BuyPlayers:[]}); //Structure: http://prntscr.com/uc2p4v
  2554. if(!Array.isArray(data.BuyPlayers)) data.BuyPlayers = [];
  2555. let playerName = pl.find('.player-name:first').text().trim(),
  2556. BuyPlayers = data.BuyPlayers;
  2557. BuyPlayers.splice(0,0,{
  2558. playerCountry : pl.find('td:nth-child(1) > img').attr('src').match(/\w+.gif/)[0].replace('.gif',''),
  2559. playerId : playerId,
  2560. playerName : playerName,
  2561. position : pl.find('td:nth-child(3)').text().trim(),
  2562. strength : parseInt(pl.find('td:nth-child(4)').text()),
  2563. age : parseInt(pl.find('td:nth-child(5)').text()),
  2564. salary : parseInt(amount),
  2565. price : parseInt(pl.find('td:nth-child(8)').attr('sortvalue')),
  2566. season : parseInt(duration),
  2567. club : {
  2568. id : parseInt(pl.find('td:nth-child(6) > a').attr('clubid')),
  2569. name : pl.find('td:nth-child(6) > a').text().trim()
  2570. },
  2571. date : GetDateText(Game.getTime()),
  2572.  
  2573. });
  2574. Tool.setVal('PlayersData',data);
  2575. notification_text = GetText('SuccessfullyTransferred', {args:[playerName]});
  2576. }
  2577. //Onaylama butonunu gizlemeye gerek yok çünkü en başta gizliyoruz : element.hide();
  2578. //$('#negotiation-bid-player-' + playerId).hide();
  2579. //Böyle bir element yok ki!
  2580. $('#info-window-player-' + playerId + ' .abort-negotiation-button-container').first().hide();
  2581. setTimeout(async function(){
  2582. location.href = $('span[pid=player-'+playerId+']').first().attr('ref');
  2583. if(notification_text){
  2584. await Game.pageLoad();
  2585. Game.giveNotification(true, notification_text);
  2586. }
  2587. },2000);
  2588. $('.negotiation table, .negotiation .info').each(function(key, e) {
  2589. e.hide();
  2590. });
  2591. return false;
  2592. }
  2593. });
  2594. break;
  2595. }
  2596. }
  2597. catch(err){
  2598. CatchError(err,'negotiation-bid-player');
  2599. }
  2600.  
  2601. $('#negotiate-container-'+id).html(div.html()); //Konteynıra server tarafından verilen cevap konuluyor.
  2602.  
  2603. updateAds(); //Reklamları güncelleme
  2604.  
  2605. $('body').trigger('content:changed');
  2606. }
  2607. ).fail(function(){
  2608. }).always(function(){
  2609. });
  2610. });
  2611. },20);
  2612.  
  2613. //openCard function is will declerate asap in body script tag.
  2614. //When it is exist it will be updated to display captain image
  2615. Tool.intervals.create(function(){
  2616. if(typeof unsafeWindow.openCard != 'function') return
  2617. this.delete();
  2618.  
  2619. Tool.modifyGameFunction('openCard',function(content){/*To show Captain Image*/
  2620. /*global element,pid*/
  2621. return content + GetFuncContent(()=>{
  2622. /*New codes added here by FCUP Script*/
  2623. let div_dialog = element.parent();
  2624. div_dialog.css('display','none').fadeIn(400);
  2625. if(parseInt($('#agreement-info-'+pid+' > li:nth-child(8) > div > div.bar-text').text())>=55 && !$('#info-'+pid+' > div.name > img.captain_icon').length){
  2626. $('#info-'+pid+' > div.name').append(
  2627. `<img class="captain_icon" title="Captain" src="https://i.ibb.co/Sy52rxz/Captain.png" style="height:20px; float:none; margin:-7px 0 0 3px; vertical-align:middle; cursor:info;">`
  2628. );
  2629. }
  2630. });
  2631. });
  2632. },20);
  2633.  
  2634. Tool.features.add('ConstructionCountdown','main',function(){
  2635. $('.likebox').css('bottom','-28px');
  2636. $('#clubinfocard > ul').append(
  2637. `<li>`+
  2638.  
  2639. ` <span class="label">${GetText('Buildings')}:</span>`+
  2640. ` <span id="countdown_buildings">${GetText('Loading')}...</span>`+
  2641. `</li>`+
  2642.  
  2643. `<li>`+
  2644.  
  2645. ` <span class="label">${GetText('Stadium')}:</span>`+
  2646. ` <span id="countdown_stadium">${GetText('Loading')}...</span>`+
  2647. `</li>`
  2648. );
  2649. ['buildings','stadium'].forEach(module=>{
  2650. if(Tool.hasOwnProperty(["finishDate_"+module])){
  2651. let seconds = parseInt((Tool["finishDate_"+module] - Game.getTime()) /1000);
  2652. let cd = $('#countdown_'+module);
  2653. cd.attr('title',new Date(Tool["finishDate_"+module]).toLocaleString());
  2654. startTimer(seconds,cd);
  2655. }
  2656. else getData(module);
  2657. });
  2658. function getData(module){
  2659. Game.getPage(`?w=${worldId}&area=user&module=${module}&action=index&_=squad`, '#content').then(content=>{
  2660. let cd = content.find('.countdown');
  2661. if(cd.length){
  2662. let seconds = parseInt(cd.first().attr('x')),
  2663. finishDate = Game.getTime()+seconds*1000;
  2664. Tool["finishDate_"+module] = finishDate; //Bitiş süresinin bir kere alınması yeterli.
  2665. cd = $('#countdown_'+module);
  2666. cd.attr('title',new Date(Tool["finishDate_"+module]).toLocaleString());
  2667. startTimer(seconds,cd);
  2668. }
  2669. else{
  2670. let result = '';
  2671. if(module=='buildings'){//buildings
  2672. if(content.find('.build').length)
  2673. result = `<a href="#/index.php?w=${worldId}&area=user&module=${module}&action=index" style="color:#51ff44;">${GetText('GoToBuildings')}</a>`;
  2674. else result = `<font color="white">${GetText('Full')}</font>`;
  2675. }
  2676. else{//stadium
  2677. let capacity = parseInt(content.find('.stadium-separator').parent().find('>span').last().text().replace('.','').trim());
  2678. let full_infrastructure = undefined == $(content[0].querySelector('#infrastructure')).find('ul.options-list > li > .imagesprite-container > div[class]').toArray().find(d=>{return $(d).hasClass('inactive')});
  2679. if(capacity == 77800 && full_infrastructure) result = `<font color="white">${GetText('Full')}</font>`;
  2680. else result = `<a href="#/index.php?w=${worldId}&area=user&module=${module}&action=index" style="color:#51ff44;">${GetText('GoToStadium')}</a>`;
  2681. }
  2682.  
  2683. $('#countdown_'+module).html(result);
  2684. }
  2685. }).catch(err=>{
  2686. $('#countdown_'+module).html(`<font color="#751b1b">${GetText('error')}</font>`);
  2687. console.error(err);
  2688. });
  2689. }
  2690. function startTimer(seconds,e){
  2691. e.html(SecToTime(seconds--));
  2692. Tool.intervals.create(function(){
  2693. if(seconds<1){
  2694. e.html(`<font style="color:#b20b0b; font-weight:bold;">${GetText('ItIsOver')} !</font>`);
  2695. this.delete();
  2696. return;
  2697. }
  2698. e.html(SecToTime(seconds--));
  2699. },1000,e[0].id);
  2700. }
  2701. },'#clubinfocard > ul > li:nth-child(6),#clubinfocard > ul > li:nth-child(7)');
  2702. Tool.features.add('RematchMatch','main',function(){
  2703. let requests = {
  2704. "myRequest":{
  2705. "accepted":[],
  2706. "unaccepted":[]
  2707. },
  2708. "otherRequest":{
  2709. "accepted":[],
  2710. "unaccepted":[]
  2711. }
  2712. };
  2713. $('#matches > ul.matches.simulations > li').each(function(){
  2714. let ul = $('ul',this),
  2715. o = ul.find('.squad-home .self-link').length?"myRequest":"otherRequest",
  2716. u;
  2717. if(o=="otherRequest")
  2718. u = ul.find('.show-button a[href*="acceptSimulation"]').length?"unaccepted":"accepted";
  2719. else//myRequest
  2720. u = ul.find('.show-button a[href*="match&id="]').length?"accepted":"unaccepted";
  2721. requests[o][u].push(ul);
  2722. });
  2723. let oa = requests.otherRequest.accepted,
  2724. i;
  2725. //Kabul etmiş olduğumuz deplasman isteğimiz olacak fakat o takıma gönderdiğimiz bir simülasyon davetimiz olmayacak.
  2726. for(i = 0; i < oa.length ; i++){
  2727. let find = !1,
  2728. clubId = $('li.col.info > span.squad-home > a',oa[i]).attr('clubid'),
  2729. m = requests.myRequest.accepted.concat(requests.myRequest.unaccepted),
  2730. j;
  2731. for(j = 0; j < m.length ; j++){
  2732. if(clubId == $('li.col.info > span.squad-away > a',m[j]).attr('clubid')){
  2733. find = true;
  2734. break;
  2735. }
  2736. }
  2737. if(!find){
  2738. let ul = oa[i];
  2739. ul.find('.show-button').append(`<img class="sendSimulation" k="${clubId}" src="${Tool.sources.getLink('https://www.pinclipart.com/picdir/big/130-1304128_left-curved-arrow-clipart-black-curved-arrow-png.png')}" alt="again" style="cursor:pointer; vertical-align:middle;" width="25x">`);
  2740. }
  2741. }
  2742.  
  2743. let images = $('img.sendSimulation');
  2744. if(!images.length) return false;
  2745.  
  2746. let get_club_matchId = (clubId)=>{
  2747. return new Promise((res,rej)=>{
  2748. Game.getPage(`?w=${worldId}&area=user&module=profile&action=show&clubId=${clubId}`,'#profile-show').then(profile_show=>{
  2749. res(profile_show.find('.button-container-friendly-invite-button > a')[0].href.split('&').find(a=>a.split('=')[0]=='invite').split('=')[1]);
  2750. }).catch(err=>{rej(err)});
  2751. });
  2752. };
  2753. let send_similation_request = (matchId)=>{
  2754. return new Promise((res,rej)=>{
  2755. Game.getPage(`?w=${worldId}&area=user&module=simulation&action=index&squad=${matchId}`,'#feedback').then(feedback=>{
  2756. res(!feedback.find('.error').length);
  2757. }).catch(err=>{rej(err)});
  2758. });
  2759. };
  2760.  
  2761. images.click(function(){
  2762. let success,
  2763. img = $(this).hide().after('<img src="/designs/redesign/images/icons/loading/16x16.gif" style="vertical-align:middle; margin-left:7px;">');
  2764.  
  2765. get_club_matchId($(this).attr('k'))
  2766. .then(match_id=>send_similation_request(match_id))
  2767. .then(status=>{
  2768. success = true;
  2769. if(status) Game.giveNotification(true, GetText('SimulationRequestSent'));
  2770. else Game.giveNotification(false, GetText('SimulationRequestAvailable'));
  2771. }).catch(err=>{
  2772. console.error(err);
  2773. }).finally(function(){
  2774. img.next().remove();
  2775. if(success) img.remove();
  2776. });
  2777. });
  2778. },'.sendSimulation');
  2779. Tool.features.add('NumberOfFootballerChecker','main',function(){
  2780. this.hover_selector = '#li_'+this.name;
  2781. $('#clubinfocard > div.club-avatar').append(
  2782. `<li>`+
  2783. ` <span id="li_${this.name}" class="label">`+
  2784. ` ${GetText('Team')}: <label id='auf_count_number'> ... </label>`+
  2785. ` </span>`+
  2786. `</li>`
  2787. );
  2788. Game.getPage(`?w=${worldId}&area=user&module=formation&action=index`, '#formation-count')
  2789. .then(formation_count=>{
  2790. let count_number = formation_count.text();
  2791. if(count_number == "11") $('#auf_count_number').html('11/11');
  2792. else $('#auf_count_number').html(`<font style="color:red; text-shadow:0.5px 0.5px white;">${count_number}/11</font>`);
  2793. })
  2794. .catch(err=>{
  2795. $('#auf_count_number').html(`<font color="#751b1b">${GetText('error')}</font>`);
  2796. console.error(err);
  2797. });
  2798. });
  2799. Tool.features.add('MatchAnalyst', 'main',function(){
  2800. let box = $('#matches > ul.matches.next'), matches;
  2801. if(box.find('.no-entry').length || !(matches = box.find('>li')).length) return false;
  2802.  
  2803. let get_club_info = (tricot,squad)=>{
  2804. return {
  2805. id : squad.find('> a').attr('clubid'),
  2806. name: squad.find('> a').text().trim(),
  2807. logo: (squad.find('> .club-logo-container > img:first').attr('src')||"").split('/').splice(-2).shift() || 0,
  2808. tricot : {
  2809. shorts: tricot.find('img[src$="shorts.png"]').attr('color'),
  2810. tricot: tricot.find('img[src$="tricot.png"]').attr('color'),
  2811. design: tricot.find('img[src$="design.png"]').attr('color'),
  2812. model : tricot.find('img[src$="details.png"]').attr('model')
  2813. }
  2814. }
  2815. };
  2816. matches= matches.toArray().map(m=>{
  2817. let match={},
  2818. li = $(m).find('>ul>li');
  2819. match.type = $(li[0]).find('.icon.match')[0].className.replace('icon','').replace('match','').trim();
  2820. match.time = $(li[1]).find('>p').text().match(/([0-9]{2}:[0-9]{2}:[0-9]{2})/)[0];
  2821. match.date = $(li[1]).find('>p').text().replace(match.time,'').trim();
  2822. match.home = get_club_info($(li[2]), $(li[3]).find('>.squad-home:first'));
  2823. match.away = get_club_info($(li[4]), $(li[3]).find('>.squad-away:first'));
  2824. if(match.type == 'tournament' && parseInt(match.time.split(':')[0])>17) match.isSpecialTournament = !0;
  2825. return match;
  2826. });
  2827. get_club_info = undefined;
  2828.  
  2829. box.html('');
  2830. box[0].style="display:none; margin:0px; height:214px; background:url('https://i.ibb.co/pxPRgSL/background-image.png'); color:white; padding:5px; position:relative;";
  2831.  
  2832. //Create Next Matches Tables
  2833. let create_tricot = (t)=>$(
  2834. `<div class="tricot-container" style="display:inline-block;">`+
  2835. ` <img class="background shorts png" src="/tricots/${t.model+'/'+t.shorts}/shorts.png" alt="shorts" model="${t.model}" color="${t.shorts}">`+
  2836. ` <img class="background tricot png" src="/tricots/${t.model+'/'+t.tricot}/tricot.png" alt=tricot"" model="${t.model}" color="${t.tricot}">`+
  2837. ` <img class="background design png" src="/tricots/${t.model+'/'+t.design}/design.png" alt="design" model="${t.model}" color="${t.design}">`+
  2838. ` <img class="png" src="designs/redesign/images/tricots/${t.model}/details.png" alt="model" model="${t.model}">`+
  2839. `</div>`
  2840. );
  2841. let create_comparision = (compares)=>{
  2842. let e=$(`<div>`+compares.map(key=>`<p><strong>${GetText(key)}:</strong> <span>...</span></p>`).join('')+'</div>');
  2843. e.find('>p').css({
  2844. 'text-align':'right',
  2845. 'font-size':'12px',
  2846. 'margin-bottom':'1px'
  2847. });
  2848. e.find('>p:not(:last)').css({
  2849. 'border-bottom':'1px solid white',
  2850. 'padding':'1px 0'
  2851. });
  2852. e.find('>p >strong').css('float','left');
  2853. return e;
  2854. }
  2855.  
  2856. let pages={rating:{}, manager:{}, squadstrenght:{}, fixture:{}};
  2857. for(let i=0; i<matches.length; i++){
  2858. let match = matches[i],
  2859. p_match= i-1>-1?matches[i-1]:0,
  2860. n_match= i+1<matches.length?matches[i+1]:0,
  2861. matchId= match.home.id+'_'+match.away.id+'_'+i;
  2862.  
  2863. let compares = [];
  2864. switch(match.type){
  2865. case "tournament":
  2866. //Turnuva sayfasına gidip, katıldığımız turnuvaları çek
  2867. if(match.isSpecialTournament){// 20:00:00
  2868. /*compare = {
  2869. rating: {
  2870. elo_rating: 1
  2871. },
  2872. manager : {
  2873. squad_strength : 1,
  2874. strongest_player: 1,
  2875. trophy: -1
  2876. }
  2877. };*/
  2878. }
  2879. else{// 14:00:00
  2880. compares = ['EloRank', 'SquadStrength', 'StrongestPlayer'];
  2881. [match.home.id, match.away.id].forEach((id,away)=>{
  2882. let squad = away?'away':'home',
  2883. e = matchId+'_'+squad;
  2884.  
  2885. if(!pages.rating.hasOwnProperty(id)) pages.rating[id] = {n:match[squad].name, e:[]};
  2886. pages.rating[id].e.push(e);
  2887.  
  2888. if(!pages.manager.hasOwnProperty(id)) pages.manager[id] = {};
  2889. ['ss', 'sp'].forEach(k=>{
  2890. if(Array.isArray(pages.manager[id][k])) pages.manager[id][k].push(e);
  2891. else pages.manager[id][k] = [e]
  2892. });
  2893. });
  2894. }
  2895. break;
  2896. case "friendly":// 16:00:00
  2897. compares = ['StadiumCapacity', 'StadiumInfrastructure', 'HomeBonusCount', 'SquadStrength', 'StrongestPlayer'];
  2898.  
  2899. [match.home.id, match.away.id].forEach((id,away)=>{
  2900. let squad = away?'away':'home',
  2901. e = matchId+'_'+squad;
  2902.  
  2903. if(!pages.manager.hasOwnProperty(id)) pages.manager[id] = {};
  2904. ['sc', 'si', 'hb', 'ss', 'sp',].forEach(k=>{
  2905. if(Array.isArray(pages.manager[id][k])) pages.manager[id][k].push(e);
  2906. else pages.manager[id][k] = [e]
  2907. });
  2908. });
  2909. break;
  2910. case "league":// 18:00:00
  2911. compares = ['EloRank', 'LeagueRank', 'SquadStrength', 'StrengthDetails', 'PrevMatchesScores', 'StrongestPlayer'];
  2912.  
  2913. if(!pages.squadstrenght.hasOwnProperty(Tool.clubId)) pages.squadstrenght[Tool.clubId] = {};
  2914. if(!pages.fixture.hasOwnProperty(Tool.clubId)) pages.fixture[Tool.clubId] = {};
  2915.  
  2916. [match.home.id, match.away.id].forEach((id,away)=>{
  2917. let squad = away?'away':'home',
  2918. e = matchId+'_'+squad;
  2919.  
  2920. if(!pages.rating.hasOwnProperty(id)) pages.rating[id] = {n:match[squad].name, e:[]};
  2921. pages.rating[id].e.push(e);
  2922.  
  2923. if(!pages.manager.hasOwnProperty(id)) pages.manager[id] = {};
  2924. ['ss', 'sp', 'lr'].forEach(k=>{
  2925. if(Array.isArray(pages.manager[id][k])) pages.manager[id][k].push(e);
  2926. else pages.manager[id][k] = [e]
  2927. });
  2928.  
  2929. if(!pages.squadstrenght[Tool.clubId].hasOwnProperty(id)) pages.squadstrenght[Tool.clubId][id] = [];
  2930. pages.squadstrenght[Tool.clubId][id].push(e);
  2931.  
  2932. if(!pages.fixture[Tool.clubId].hasOwnProperty(id)) pages.fixture[Tool.clubId][id] = [];
  2933. pages.fixture[Tool.clubId][id].push(e);
  2934. });
  2935. break;
  2936. }
  2937.  
  2938. $(`<div class="matches" style="height:100%; position:relative;${i>0?" display:none;":""}">`+
  2939. ` <p style="font-size:15px; color:white; text-align:center; font-weight:bold;">`+
  2940. ` ${GetText(match.type=='tournament'?(match.isSpecialTournament?'specialTournamentMatch':'tournamentMatch'):(match.type+'Match'))} - ${match.date}, ${match.time}</p>`+
  2941. ` <span class="fixture ${match.type}" style="width:128px; position:absolute; bottom:0; left:0;"></span>`+
  2942. ` <div style="height:70%; width:90%; margin:5px auto 0 auto; position:relative; z-index:1;">`+
  2943. /* Home Club*/
  2944. ` <div style="height:100%; width:49%; float:left;">`+
  2945. ` <div style="position:relative; margin-bottom: 22px;">`+
  2946. ` ${create_tricot(match.home.tricot).css('margin','0 5px -14px 0')[0].outerHTML}`+
  2947. ` <a href="#/index.php?w=${worldId}&area=user&module=profile&action=show&clubId=${match.home.id}" clubid="${match.home.id}" ${match.home.id==Tool.clubId?'class="self-link"':''} style="font-size:13px; font-weight:bold; text-decoration:none;">${match.home.name}</a>`+
  2948. ` ${match.home.logo?`<img src="/avatars/${worldId}/squad/${match.home.logo}/${match.home.id}" style="position:absolute; top:7px; right:5px;">`:''}`+
  2949. ` </div>`+
  2950. ` ${create_comparision(compares).attr('id',`comparison_${matchId}_home`)[0].outerHTML}`+
  2951. ` </div>`+
  2952.  
  2953. ` <div style="width:0.1%; height:100%; background-color:white; float:left; margin-left:5px;"></div>`+
  2954.  
  2955. /* Away Club*/
  2956. ` <div style="height:100%; width:49%; float:right; text-align:right;">`+
  2957. ` <div style="position:relative; margin-bottom:22px;">`+
  2958. ` ${match.away.logo?`<img src="/avatars/${worldId}/squad/${match.away.logo}/${match.away.id}" style="position:absolute; top:7px; left:5px;">`:''}`+
  2959. ` <a href="#/index.php?w=${worldId}&area=user&module=profile&action=show&clubId=${match.away.id}" clubid="${match.away.id}" ${match.away.id==Tool.clubId?'class="self-link"':''} style="font-size:13px; font-weight:bold; text-decoration:none;">${match.away.name}</a>`+
  2960. ` ${create_tricot(match.away.tricot).css('margin','0 0 -14px 5px')[0].outerHTML}`+
  2961. ` </div>`+
  2962. ` ${create_comparision(compares).attr('id',`comparison_${matchId}_away`)[0].outerHTML}`+
  2963. ` </div>`+
  2964. ` </div>`+
  2965. `</div>`
  2966. ).attr({
  2967. id: matchId,
  2968. prev_match: p_match? p_match.home.id+'_'+p_match.away.id+'_'+(i-1): null,
  2969. next_match: n_match? n_match.home.id+'_'+n_match.away.id+'_'+(i+1): null
  2970. }).appendTo(box);
  2971. }
  2972. create_tricot = create_comparision = undefined;
  2973.  
  2974. Object.values(pages.rating).forEach(data=>{
  2975. let e = data.e = $(data.e.map(e=>$(`#comparison_${e} strong>[k="EloRank"]`).parent().next())).map($.fn.toArray),
  2976. club_name = data.n;
  2977.  
  2978. e.html('<img src="/designs/redesign/images/icons/loading/16x16.gif" style="margin-left:10px; vertical-align:middle;">');
  2979. Game.getPage(`index.php?w=${worldId}&area=user&module=rating&action=index&club=${club_name}&_qf__form=&league=&path=index.php&layout=none`,'#container-rating')
  2980. .then(div=>{
  2981. let row = div.find('.table-rating > tbody > tr.odd,tr.even');
  2982. if(!row.length){
  2983. e.html('~');
  2984. return;
  2985. }
  2986. row = row.first();
  2987. let rank = parseInt(row.find('>td:first').text().split('.').join('')),
  2988. change_r = parseInt(row.find('>td:nth-child(2)').text().split('.').join('')),
  2989. points = parseInt(row.find('>td:nth-child(4)').text().split('.').join('')),
  2990. points_r = parseInt(row.find('>td:nth-child(5)').text().split('.').join(''));
  2991. e.html(rank);
  2992. })
  2993. .catch(err=>{
  2994. e.html(`<font color="#f34949" style="border-bottom:1px dashed red;">${GetText('error')}</font>`);
  2995. console.error(err);
  2996. });
  2997. });
  2998.  
  2999. Object.entries(pages.manager).forEach(d=>{
  3000. let clubId = d[0],
  3001. data = d[1],
  3002. ss = data.ss = $((Array.isArray(data.ss)?data.ss:[]).map(e=>$(`#comparison_${e} strong>[k="SquadStrength"]`).parent().next())).map($.fn.toArray),
  3003. sp = data.sp = $((Array.isArray(data.sp)?data.sp:[]).map(e=>$(`#comparison_${e} strong>[k="StrongestPlayer"]`).parent().next())).map($.fn.toArray),
  3004. lr = data.lr = $((Array.isArray(data.lr)?data.lr:[]).map(e=>$(`#comparison_${e} strong>[k="LeagueRank"]`).parent().next())).map($.fn.toArray),
  3005. sc = data.sc = $((Array.isArray(data.sc)?data.sc:[]).map(e=>$(`#comparison_${e} strong>[k="StadiumCapacity"]`).parent().next())).map($.fn.toArray),
  3006. si = data.si = $((Array.isArray(data.si)?data.si:[]).map(e=>$(`#comparison_${e} strong>[k="StadiumInfrastructure"]`).parent().next())).map($.fn.toArray),
  3007. hb = data.hb = $((Array.isArray(data.hb)?data.hb:[]).map(e=>$(`#comparison_${e} strong>[k="HomeBonusCount"]`).parent().next())).map($.fn.toArray);
  3008.  
  3009. let all = ss.add(sp).add(lr).add(sc).add(si).add(hb);
  3010.  
  3011. if(0 == all.length) return;
  3012. all.html('<img src="/designs/redesign/images/icons/loading/16x16.gif" style="margin-left:10px; vertical-align:middle;">');
  3013.  
  3014. Game.getPage(`?w=${worldId}&area=user&module=profile&action=show&clubId=${clubId}&layout=none`, '#profile-show')
  3015. .then(node=>{
  3016. let contents = node.find('ul.profile-box-squad > li:nth-child(1)').contents();
  3017. if(!contents.length) return; //Kein Verein gefunden.
  3018.  
  3019. if(ss.length) ss.html(node.find('ul.profile-box-squad > li:nth-child(1)').contents()[1].textContent); //Squad_Strength
  3020.  
  3021. if(lr.length){
  3022. let leaguetable = node[0].querySelector('#leaguetable');
  3023. if(leaguetable && !$('.no-entry',leaguetable).length){
  3024. //$('>h2',leaguetable).text().trim()+", " +
  3025. lr.html($('> div.container > div > table',leaguetable).find(`a[clubid="${clubId}"]`).parents('tr:first').find('td:first').text().trim()); //League
  3026. }
  3027. else lr.html('~');
  3028. }
  3029.  
  3030. if(sp.length){
  3031. let o = $('.profile-box-squad .open-card',node);
  3032. if(!o.length){
  3033. sp.html(GetText('NotFound'));
  3034. return;
  3035. }
  3036. let name = o.next().find('.ellipsis'),
  3037. playerDetails;
  3038. if(name.length){
  3039. let p = $(name.parent()[0].outerHTML);
  3040. name = name[0].title;
  3041. p.find('.ellipsis').remove();
  3042. playerDetails = p.html();
  3043. }
  3044. else{
  3045. name = o.next().text();
  3046. let idx = name.indexOf('(');
  3047. playerDetails = name.substring(idx).trim();
  3048. name = name.substring(0,idx).trim();
  3049. }
  3050. sp.html(`<span pid="player-${o.attr('pid').split('-')[1]}" class="icon details open-card" style="float:none;"></span>${/*name +" "+*/playerDetails}`);
  3051. }
  3052.  
  3053. if(sc.length) sc.html(node.find('.profile-box-stadium').text().trim().match(/[\d,\.]+/)[0]||"~");
  3054.  
  3055. if(hb.length + si.length){
  3056. unsafeWindow.jQuery.get(`/index.php?w=${worldId}&area=user&module=trophy&action=index&complex=0&clubId=${clubId}`).success(function(r){
  3057. if(si.length){
  3058. let node = $('<div>').html(r);
  3059. si.html(node.find('.trophy-50').hasClass('trophy-unavailable')?GetText("Missing"):GetText("Full"));
  3060. }
  3061.  
  3062. if(hb.length){
  3063. try{
  3064. let b = r.lastIndexOf('toolTipObj.addTooltips(')+23;
  3065. r = JSON.parse(r.substring(b,r.indexOf(');',b)));
  3066. let text= r.tt_trophy_70.trim(),
  3067. num = parseInt(text.substring(text.lastIndexOf(':')+1,text.lastIndexOf('<')))
  3068. hb.html(Number.isInteger(num)?num:"~");
  3069. }
  3070. catch(err){
  3071. hb.html(`<font color="#f34949" style="border-bottom:1px dashed red;">${GetText('error')}</font>`);
  3072. }
  3073. }
  3074. });
  3075. }
  3076. })
  3077. .catch(err=>{
  3078. $(all.toArray().filter(span=>$(span).find('>img').length)).html(`<font color="#f34949" style="border-bottom:1px dashed red;">${GetText('error')}</font>`);
  3079. console.error(err);
  3080. });
  3081. });
  3082.  
  3083. Object.entries(pages.squadstrenght).forEach(d=>{
  3084. let clubId = d[0];
  3085. if(clubId != Tool.clubId) return;
  3086. let data = d[1] = Object.entries(d[1])
  3087. .map(d=>[d[0], $(d[1].map(e=>$(`#comparison_${e} strong>[k="StrengthDetails"]`).parent().next())).map($.fn.toArray)])
  3088. .reduce((acc,d)=>{acc[d[0]]=d[1];return acc;},{});
  3089.  
  3090. $(Object.values(data)).map($.fn.toArray).html('<img src="/designs/redesign/images/icons/loading/16x16.gif" style="margin-left:10px; vertical-align:middle;">');
  3091.  
  3092. Game.getPage(`?w=${worldId}&area=user&module=statistics&action=squadstrenght&layout=none`, '#squad-strengths')
  3093. .then(table=>{
  3094. let tbody = table.find('>tbody:first');
  3095. Object.entries(data).forEach(d=>{
  3096. let clubId = d[0],
  3097. e = d[1],
  3098. a = tbody.find(`td.name-column > a[clubid="${clubId}"]:first`);
  3099. if(!a.length){
  3100. e.html('~');
  3101. return;
  3102. }
  3103. e.html(a.parents('tr').find('>td[sortvalue]:not(.last-column)').toArray().map(e=>$(e).attr('sortvalue')).join(' | '));
  3104. });
  3105. })
  3106. .catch(err=>{
  3107. $($(Object.values(data)).map($.fn.toArray).toArray().filter(span=>$(span).find('>img').length)).html(`<font color="#f34949" style="border-bottom:1px dashed red;">${GetText('error')}</font>`);
  3108. console.error(err);
  3109. });
  3110. });
  3111.  
  3112. Object.entries(pages.fixture).forEach(d=>{
  3113. let clubId = d[0];
  3114. if(clubId != Tool.clubId) return;
  3115.  
  3116. let data = d[1] = Object.entries(d[1])
  3117. .map(d=>[d[0], $(d[1].map(e=>$(`#comparison_${e} strong>[k="PrevMatchesScores"]`).parent().next())).map($.fn.toArray)])
  3118. .reduce((acc,d)=>{acc[d[0]]=d[1];return acc;},{});
  3119.  
  3120. let all = $(Object.values(data)).map($.fn.toArray);
  3121. all.html('<img src="/designs/redesign/images/icons/loading/16x16.gif" style="margin-left:10px; vertical-align:middle;">');
  3122.  
  3123. let images = {
  3124. 'W': 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMTZweCIgaGVpZ2h0PSIxNnB4IiB2aWV3Qm94PSIwIDAgMTYgMTYiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iV2luIj4KICAgICAgICAgICAgPGNpcmNsZSBpZD0iT3ZhbCIgZmlsbD0iIzNBQTc1NyIgY3g9IjgiIGN5PSI4IiByPSI4Ij48L2NpcmNsZT4KICAgICAgICAgICAgPHBvbHlnb24gaWQ9IlBhdGgiIGZpbGw9IiNGRkZGRkYiIGZpbGwtcnVsZT0ibm9uemVybyIgcG9pbnRzPSI2LjQgOS43NiA0LjMyIDcuNjggMy4yIDguOCA2LjQgMTIgMTIuOCA1LjYgMTEuNjggNC40OCI+PC9wb2x5Z29uPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+Cg==',
  3125. 'D': 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMTZweCIgaGVpZ2h0PSIxNnB4IiB2aWV3Qm94PSIwIDAgMTYgMTYiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iRHJhdyI+CiAgICAgICAgICAgIDxjaXJjbGUgaWQ9Ik92YWwiIGZpbGw9IiM5QUEwQTYiIGN4PSI4IiBjeT0iOCIgcj0iOCI+PC9jaXJjbGU+CiAgICAgICAgICAgIDxwb2x5Z29uIGlkPSJQYXRoIiBmaWxsPSIjRkZGRkZGIiBwb2ludHM9IjUgNyAxMSA3IDExIDkgNSA5Ij48L3BvbHlnb24+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4K',
  3126. 'L': 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMTZweCIgaGVpZ2h0PSIxNnB4IiB2aWV3Qm94PSIwIDAgMTYgMTYiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iTG9zcyI+CiAgICAgICAgICAgIDxjaXJjbGUgaWQ9Ik92YWwiIGZpbGw9IiNFQTQzMzUiIGN4PSI4IiBjeT0iOCIgcj0iOCI+PC9jaXJjbGU+CiAgICAgICAgICAgIDxwb2x5Z29uIGlkPSJQYXRoIiBmaWxsPSIjRkZGRkZGIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg4LjAwMDAwMCwgOC4wMDAwMDApIHJvdGF0ZSgtMzE1LjAwMDAwMCkgdHJhbnNsYXRlKC04LjAwMDAwMCwgLTguMDAwMDAwKSAiIHBvaW50cz0iMTIgOC44IDguOCA4LjggOC44IDEyIDcuMiAxMiA3LjIgOC44IDQgOC44IDQgNy4yIDcuMiA3LjIgNy4yIDQgOC44IDQgOC44IDcuMiAxMiA3LjIiPjwvcG9seWdvbj4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPgo=',
  3127. '-': 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMTZweCIgaGVpZ2h0PSIxNnB4IiB2aWV3Qm94PSIwIDAgMTYgMTYiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8ZyBpZD0iRW1wdHkiIGZpbGw9IiNGRkZGRkYiIHN0cm9rZT0iI0JEQzFDNiIgc3Ryb2tlLXdpZHRoPSIyIj4KICAgICAgICAgICAgPGNpcmNsZSBpZD0iT3ZhbCIgY3g9IjgiIGN5PSI4IiByPSI3Ij48L2NpcmNsZT4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPgo='
  3128. }
  3129. Game.getPage(`?w=${worldId}&area=user&module=statistics&action=games&layout=none`)
  3130. .then(content=>{
  3131. let table ,ul, trs;
  3132. if(!(table=content.find('#league-crosstable')).length ||
  3133. !(ul=content.find('.date-selector > ul:first')).length ||
  3134. !(trs=table.find('>tbody > tr')).length){
  3135. all.html('~');
  3136. return;
  3137. }
  3138. let played = ul.find('li.day.past').length,
  3139. getDatas = (td)=>{
  3140. let goals, week;
  3141. if((goals=$('>p',td).text().trim().split(':').map(n=>parseInt(n))).length!=2 ||
  3142. undefined !== goals.find(n=>isNaN(n)) ||
  3143. (week=$('>p',td).attr('title').trim().split(':')).length!=2 ||
  3144. isNaN(week=parseInt(week[1]))
  3145. ) return false;
  3146. return {goals:goals, week:week};
  3147. }, r,
  3148. thead = $('> thead > tr:nth-child(1)',table);
  3149. Object.entries(data).forEach(d=>{
  3150. let clubId = d[0],
  3151. e = d[1],
  3152. a = trs.find(`> td > a[clubid="${clubId}"]:first`);
  3153. if(!a.length){
  3154. e.html('~');
  3155. return;
  3156. }
  3157. let tr = a.parents('tr:first'),
  3158. results = ["-","-","-","-","-"];
  3159. tr.find('td:not(.nomatch):not(:first)').each(function(){ //Satırdaki bölümler incelenecek
  3160. if(!(r = getDatas(this))){
  3161. e.html('~');
  3162. return;
  3163. }
  3164. if(r.week<played-4 || played<r.week) return; //Too old score
  3165. results[4-Math.max(0,5-played)-played+r.week] = {
  3166. s: r.goals[0]>r.goals[1]?"W":r.goals[0]==r.goals[1]?"D":"L",
  3167. g: r.week+": " + a.text().trim() + " " + r.goals[0]+'-'+r.goals[1] + " " + thead.find(`>th:nth-child(${$(this).index()+1})`).text().trim()
  3168. };
  3169. });
  3170. trs.find(`>td:nth-child(${1+tr.index()+1}):not(.nomatch)`).each(function(i){ //Sutundaki bölümler incelenecek
  3171. if(!(r = getDatas(this))){
  3172. e.html('~');
  3173. return;
  3174. }
  3175. if(r.week<played-4 || played<r.week) return; //Too old score
  3176. results[4-Math.max(0,5-played)-played+r.week] = {
  3177. s: r.goals[1]>r.goals[0]?"W":r.goals[0]==r.goals[1]?"D":"L",
  3178. g: r.week+": " + $(this).parent().find('a[clubid]').text().trim() + " " + r.goals[0]+'-'+r.goals[1] + " " + a.text().trim()
  3179. };
  3180. });
  3181. e.html(`[${results.reduce((acc,r)=>acc+({W:3,D:1}[r.s]||0),0)} ${GetText('SPoints')}] `+results.map(r=>`<img src="${images[r=="-"?r:r.s]}" ${r=="-"?"":`title="${r.g}"`} style="margin:0 2px -1px 0">`).join(''));
  3182. });
  3183. })
  3184. .catch(err=>{
  3185. $(all.toArray().filter(span=>$(span).find('>img').length)).html(`<font color="#f34949" style="border-bottom:1px dashed red;">${GetText('error')}</font>`);
  3186. console.error(err);
  3187. });
  3188. });
  3189.  
  3190. //Create Animation
  3191. if(matches.length>1){
  3192. box.append(
  3193. `<img id="prev_match" matches_length="${matches.length}" src="https://i.ibb.co/p468SYn/Untitled.png" style="height:18px; position:absolute; left:2px; top:50%; cursor:pointer; transform:translate(0,-50%); display:none; ">`+
  3194. `<img id="next_match" matches_length="${matches.length}" src="https://i.ibb.co/p468SYn/Untitled.png" style="height:18px; position:absolute; right:2px; top:50%; cursor:pointer; transform:translate(0,-50%); -moz-transform:scaleX(-1); -o-transform:scaleX(-1); -webkit-transform:scaleX(-1); transform:scaleX(-1);">`
  3195. );
  3196. $('#prev_match,#next_match').click(function(){
  3197. $('#prev_match,#next_match').css("pointer-events", "none");
  3198. let k = this.id=='next_match'?1:0,
  3199. close_e = $('#matches > ul.matches.next').find('>div.matches:visible'),
  3200. open_e = $('#'+close_e.attr(k?'next_match':'prev_match'));
  3201. close_e.hide("slide", { direction: k?'left':'right' }, 200);
  3202. setTimeout(()=>{
  3203. open_e.show("slide", { direction: k?'right':'left' }, 300);
  3204. $('#prev_match,#next_match').css("pointer-events", "auto");
  3205. },250);
  3206. $('#prev_match')[open_e.attr('prev_match')?'show':'hide']();
  3207. $('#next_match')[open_e.attr('next_match')?'show':'hide']();
  3208. });
  3209. }
  3210.  
  3211. },'#matches > ul.matches.next,#matches-handle-container > li.handle:nth-child(2)');
  3212. Tool.features.add('TrainingControl',['squad','training->groups'],function(){
  3213. function getElementOffsetWidth(e) {
  3214. var element = $(e).clone().appendTo('body');
  3215. var width = element.outerWidth();
  3216. element.remove();
  3217. return width;
  3218. }
  3219. let trainingPlan = Tool.trainingPlan,
  3220. Positions = Tool.footballerPositions,
  3221. SkillsName = Translate.locale.texts.Skills,
  3222. alerts = {i:[],e:[]};
  3223. $('#players-table-skills > tbody > tr').each(function(){
  3224. let position = $(this).find('td:nth-child(3)').text().trim(),
  3225. developSkills = trainingPlan[position];
  3226. if(!developSkills) return true;
  3227.  
  3228. let skills = $(this).find('.skill-column');
  3229.  
  3230. for(let i = 0 ; i < developSkills.length ; i++){//Geliştirilecek yetenek aranıyor
  3231. let s = $(skills[developSkills[i]]).find('span');
  3232. if(s.hasClass("maximum")) continue;//Bu geliştirilecek yetenek maksimumsa bir sonraki geliştirilecek yeteneğe bak.
  3233. else if(s.hasClass("next-training")) break;//Bu geliştirilecek yetenek geliştirilmeye devam ediyorsa doğru yoldasın.
  3234. else{//Bu geliştirilecek yetenek maksimum değil ve geliştirilmeye devam edilmiyorsa.Bir sıkıntı var.
  3235. //Ya farklı bir yetenek geliştiriliyor yada hiçbir yetenek geliştirilmiyor.
  3236. let skillName = SkillsName[developSkills[i]],
  3237. left = (getElementOffsetWidth(s[0])-15)/2,
  3238. value = s.text().trim(),
  3239. playerName = $(this).find('.player-name').text().trim();
  3240. s.html(
  3241. `<img title="${GetText('ImproveSkillTitle', {tag:0, args:[skillName]})}!!!" tool_tt="ImproveSkillTitle_${encodeURIComponent(JSON.stringify([skillName]))}" src="${Tool.sources.getLink('https://c.tenor.com/nByXaSdQ13EAAAAi/down-arrow-going-down.gif')}" alt="here" width="30px" height="30px" style="-webkit-transform:rotate(0deg); margin:-25px -15px -15px -5px; position:absolute;">`+
  3242. value
  3243. );
  3244. if($(skills[0]).parent().find('span.next-training').length) alerts.e.push(playerName+'-> '+skillName.toLowerCase());
  3245. else alerts.i.push(playerName+'-> '+skillName.toLowerCase());
  3246. break;
  3247. }
  3248. }
  3249. });
  3250. if(alerts.i.length || alerts.e.length){
  3251. let content="";
  3252. if(alerts.i.length){
  3253. content= `<span style="text-decoration:underline; color:#3fffe4;">${GetText('TrainingMessage')}</span><br>`+alerts.i.join('<br>');
  3254. }
  3255. if(alerts.e.length){
  3256. if(content!="") content+="<br><br>"
  3257. content+= `<span style="text-decoration:underline; color: #3fffe4;">${GetText('FaultyTrainingMessage')}</span><br>`+alerts.e.join('<br>');
  3258. }
  3259. Game.giveNotification(true,content);
  3260. }
  3261. },null);
  3262. Tool.features.add('ClubExchange','squad',function(){
  3263. let ClubExchange = {
  3264. initial_data : Tool.getVal('ClubExchange',{}),
  3265. new : {},// Exp : {3252352:0,234131:1} , 0=>error , 1=>success
  3266. selector : [],
  3267. finish : 0,
  3268. initial : function(){
  3269. let initial_data = ClubExchange.initial_data;
  3270. $('#players-table-overview > tbody > tr').add($('#players-table-overview-club > tbody > tr')).each(function(){
  3271. let openCard;
  3272. if(!(openCard = $(this).find('.open-card')).length) return true;
  3273. let playerId = openCard.attr('pid').split('-')[1],
  3274. table = $(this).parents('table')[0].id.replace('players-table-',''),// overview or overview-club
  3275. index = $(this).index(),
  3276. td_contract = $('td:nth-child(11)',this);
  3277. if(td_contract.text().indexOf(Tool.ClubExchange)!=-1){//td_contract da Kulüp Değişimi yazıyor olmali...
  3278. //Bu futbolcu kulüp değiştiriyor!!!
  3279. let playerData = initial_data[playerId];
  3280. if(!playerData) //Oyuncunun gidiş bilgileri mevcut değilse
  3281. ClubExchange.getPage(playerId,table,index);
  3282. else //Oyuncunun gidiş bilgileri mevcutsa
  3283. ClubExchange.addImage(playerData,table,index);
  3284. }
  3285. });
  3286. },
  3287. getPage : function(playerId,table,index){
  3288. ClubExchange.new[playerId]=0;//Varsayılan değer olarak sayfa çekmeyi başarısız sayıyoruz.
  3289. $.get(`index.php?w=${worldId}&area=user&module=player&action=index&complex=0&id=${playerId}`, function(response){
  3290. ClubExchange.new[playerId]=1;//default olarak başarısız olarak varsayılan değeri başarılı değere çeviriyoruz.
  3291. let li = $('<div>'+response+'</div>').find('.data.attributes > ul > li:last'),
  3292. a = li.find('a'),
  3293. club = {
  3294. id : a.attr('clubid'),
  3295. name : a.text().trim()
  3296. };
  3297. li.find('a,strong').remove();
  3298. let li_text = li.text().trim(),
  3299. date = li_text.match(/(3[01]|[12][0-9]|0?[1-9])\.(1[012]|0?[1-9])\.((?:19|20)\d{2})/g);
  3300. if(date){
  3301. date=date[0];
  3302. let playerData = {date:date,club:club},
  3303. data = Tool.getVal('ClubExchange',{});
  3304. data[playerId] = playerData;
  3305. Tool.setVal('ClubExchange',data);
  3306. ClubExchange.addImage(playerData,table,index)
  3307. }
  3308. }).always(function() {
  3309. let _new = ClubExchange.new;
  3310. if(ClubExchange.finish++==Object.keys(_new).length){//Tüm istekler başarılı yada başarısız bir şekilde bitti!
  3311. //Eğer daha önceden kayıtlı edilmiş bir futbolcu varsa(kulübü terkeden) şimdi o oyuncu bulunmazsa kulübü terk etmiştir. Onu kayıtlardan çıkarmamız lazım.
  3312. let initial_data = ClubExchange.initial_data,
  3313. current_data = Tool.getVal('ClubExchange',{}),
  3314. counter = 0;
  3315. for(let playerId in initial_data){
  3316. if(_new[playerId]==undefined){//Oyuncu çoktan kulübü terk etmiş..
  3317. counter++;
  3318. delete current_data[playerId];
  3319. }
  3320. }
  3321. if(counter) Tool.setVal('ClubExchange',current_data);
  3322. }
  3323. });
  3324. },
  3325. addImage : function(playerData,table,index){
  3326. let d = playerData.date.split('.'),
  3327. sec = parseInt((new Date(d[2],parseInt(d[1])-1,d[0],3).getTime()-Game.getTime())/1000),
  3328. tds = [
  3329. $(`#players-table-${table} >tbody >tr:nth-child(${index+1}) >td:nth-child(11)`),
  3330. $(`#players-table-${table=='overview'?'agreements':'agreements-club'} >tbody >tr:nth-child(${index+1}) >td:nth-child(8)`)
  3331. ];
  3332. //this.selector.push('#players-table-'+table+' > tbody > tr:nth-child('+(index+1)+') > td:nth-child(11)','#players-table-'+(table=='overview'?'agreements':'agreements-club')+' > tbody > tr:nth-child('+(index+1)+') > td:nth-child(8)');
  3333. $(tds).each(function(){
  3334. let time_text = $('<div>'+SecToTime(sec)+'</div>').text(),
  3335. args = [playerData.date, playerData.club.name];
  3336. $(this).html(
  3337. `<a href="#/index.php?w=${worldId}&area=user&module=profile&action=show&clubId=${playerData.club.id}" target="_blank">`+
  3338. ` <img title="${GetText('ClubExchange', {tag:0, args:args})}" tool_tt="ClubExchange_${encodeURIComponent(JSON.stringify(args))}" src="${Tool.sources.getLink('https://thumbs.dreamstime.com/z/arrow-up-down-stock-%C3%A2%E2%82%AC-121724975.jpg')}" alt="exchange" height="15px" style="background-color:#00fff7; border-radius:50%; cursor:pointer; margin-right:4px;">`+
  3339. `</a>`+
  3340. `<font title="${GetText('RemainingTime', {tag:0})} : ${time_text}" tool_tt="RemainingTime_{X} : ${time_text}">${playerData.date}</font>`
  3341. );
  3342. });
  3343. }
  3344. };
  3345. ClubExchange.initial();
  3346. },null);
  3347. Tool.features.add('RankingOfPlayers','squad',function(){
  3348. if($('#players-table-overview > tbody > tr').find('.open-card').length==0) return false;
  3349.  
  3350. let players = $('#players-table-overview > tbody > tr');
  3351. players.each(function(i){
  3352. $(this).find('td:nth-child(6) >span >input[type="text"]').attr('tabindex', i+1);
  3353. });
  3354. $('#squad-handle-container').append(`<input id="RankingOfPlayersButton" type="button" value="${GetText('SortPlayers', {tag:0})}" tool_vt="SortPlayers" title="${GetText('rankOfPlayerExplanation', {tag:0})}" tool_tt="rankOfPlayerExplanation" style="-webkit-border-radius:7px !important; padding:2px 5px; border:1px solid #999; font-size:9px; margin:16px 90px 0 40px;">`);
  3355. $('#RankingOfPlayersButton').click(function(){
  3356. let klText = Tool.footballerPositions[0],
  3357. kl=[],genc=[],diger=[];
  3358. $('#players-table-overview > tbody > tr').each(function(i){
  3359. let mevki = $(this).find('td:nth-child(3)')[0].textContent.trim(),
  3360. güc = parseInt($(this).find('td:nth-child(4)')[0].textContent),
  3361. yas = parseInt($(this).find('td:nth-child(5)')[0].textContent);
  3362. if(IsYoungPlayer($(this).find('td:nth-child(12)'))){
  3363. let tarih = $(this).find('td:nth-child(11)')[0].textContent.split('.');
  3364. tarih = new Date(tarih[2],parseInt(tarih[1])-1,tarih[0]).getTime();
  3365. genc.push({'i':i,tarih:tarih});
  3366. }
  3367. else if(mevki===klText){
  3368. kl.push({'i':i,güc:güc,yas:yas});
  3369. }
  3370. else{
  3371. diger.push({'i':i,güc:güc,yas:yas});
  3372. }
  3373. });
  3374. let maxKl = {güc:0,i:null},
  3375. spliceIndex = null;
  3376. for(let i = 0 ; i < kl.length; i++){
  3377. if(kl[i].güc>maxKl.güc){
  3378. maxKl.güc = kl[i].güc;
  3379. maxKl.i = kl[i].i;
  3380. spliceIndex = i;
  3381. }
  3382. }
  3383. let no = 1;
  3384. if(maxKl.i!=null){
  3385. //Kaleci varsa, en güçlü kaleciyi 1.sıraya al!
  3386. $('#players-table-overview > tbody > tr:nth-child('+(maxKl.i+1)+') > td:nth-child(6) > span > input[type="text"]').val(no);
  3387. $('#players-table-overview > tbody > tr:nth-child('+(maxKl.i+1)+') > td:nth-child(6) > span > input[type="text"]').attr('tabindex',no++);
  3388.  
  3389. //En güçlü kaleciyi çıkart ve geri kalanını diger adlı diziye aktar
  3390. kl.splice(spliceIndex,1);
  3391. for(let i = 0 ; i < kl.length ; i++){
  3392. diger.push({'i':kl[i].i,'güc':kl[i].güc,'yas':kl[i].yas});
  3393. }
  3394. }
  3395.  
  3396. //En güçlüden en güçsüze göre sırala
  3397. diger.sort(function(a,b){
  3398. if(b.güc-a.güc!==0) return b.güc-a.güc;
  3399. else return a.yas-b.yas;
  3400. });
  3401.  
  3402. //Genç hariç geri kalanını sırala
  3403. for(let i = 0 ; i < diger.length ; i++){
  3404. $('#players-table-overview > tbody > tr:nth-child('+(diger[i].i+1)+') > td:nth-child(6) > span > input[type="text"]').val(no);
  3405. $('#players-table-overview > tbody > tr:nth-child('+(diger[i].i+1)+') > td:nth-child(6) > span > input[type="text"]').attr('tabindex',no++);
  3406. }
  3407.  
  3408. //Genç oyuncuları geliş tarihlerine göre sırala. Geliş tarihi en küçük olan ilk olmalı!
  3409. genc.sort(function(a,b){
  3410. return a.tarih-b.tarih;
  3411. });
  3412.  
  3413. //Genç oyuncuları 90 dan başlayarak sırala
  3414. for(let i = 0 ; i < genc.length ; i++){
  3415. $('#players-table-overview > tbody > tr:nth-child('+(genc[i].i+1)+') > td:nth-child(6) > span > input[type="text"]').val(90+i);
  3416. $('#players-table-overview > tbody > tr:nth-child('+(genc[i].i+1)+') > td:nth-child(6) > span > input[type="text"]').attr('tabindex',90+i);
  3417. }
  3418. $('#players-table-overview > tfoot > tr > td:nth-child(2) > span > a > span').click();
  3419. });
  3420. $('#squad-handle-container > li').click(function(){
  3421. $('#RankingOfPlayersButton')[$(this).index()?'slideUp':'slideDown']('slow');
  3422. });
  3423. },'#RankingOfPlayersButton');
  3424. Tool.features.add('ShowStrengthChange','squad',function(){
  3425. if($('#players-table-overview > tbody > tr').find('.open-card').length==0) return false;
  3426. let BuyPlayers = Tool.getVal('PlayersData',{BuyPlayers:[]}).BuyPlayers; //Structure: http://prntscr.com/uc2p4v
  3427. if(!Array.isArray(BuyPlayers) || BuyPlayers.length==0) return false;
  3428. let players = $('#players-table-changes > tbody > tr .open-card');
  3429. if(!players.length) return false;
  3430. players.each(function(){
  3431. let p_data = BuyPlayers.find(p=>p.playerId==$(this).attr('pid').split('-')[1]);
  3432. if(p_data===undefined) return;
  3433. let tr = $(this).parents('tr').first(),
  3434. currentStrength = parseInt(tr.find('td:nth-child(4)').text()),
  3435. oldStrength = p_data.strength,
  3436. difference = currentStrength-oldStrength;
  3437. if(difference>0) tr.find('td:nth-child(4)').append(`<span class="changed-property new-player" style="color:#42ff35; margin-left:2px;">(+${difference})</span>`);
  3438.  
  3439. //tr.find('.last-column').last().css('position','relative').append(
  3440. // `<img title="${GetText('InfoStrengthChange', {tag:0})}" tool_tt="InfoStrengthChange" src="${Tool.sources.getLink('data','png')}" alt="data" height="15px" style="position:absolute; top:9px; right:10px;">`
  3441. //);
  3442. });
  3443.  
  3444. },'#players-table-changes > tbody span.changed-property.new-player');
  3445. Tool.features.add('ShowRealStrength','squad',function(){
  3446. let tables =
  3447. [
  3448. ["#players-table-overview", "#players-table-agreements", "#players-table-skills"],
  3449. ["#players-table-overview-club", "#players-table-agreements-club", "#players-table-skills-club"]
  3450. ],
  3451. counter = 0;
  3452. for(let i = 0 ; i < tables.length ; i++){
  3453. let first_table = $(tables[i][0]);
  3454. if(!first_table.find('.open-card').length) continue;
  3455. $('>tbody>tr',first_table).each(function(rowIndex){ //eslint-disable-line no-loop-func
  3456. let row = $(this),
  3457. position = row.find('> td:nth-child(3)').text().trim();
  3458. let skills = [];
  3459. $(tables[i][2]).find('> tbody > tr:nth-child('+(rowIndex+1)+')').find('.skill-column').each(function(){
  3460. skills.push(parseFloat($(this).text()));
  3461. });
  3462. let strengthColumn = row.find('> td:nth-child(4)'),
  3463. currentStrength = parseInt(strengthColumn.attr('sortvalue')),
  3464. realStrength = GetRealStrength(skills,position);
  3465.  
  3466. if(isNaN(realStrength)) return true;
  3467. realStrength = realStrength.toFixed(2);
  3468.  
  3469. let difference = (realStrength - currentStrength).toFixed(2),
  3470. color = difference>0?"green":difference<0?"#a62c2c":"#d9d9d9";
  3471.  
  3472. for(let j = 0 ; j < 3 ; j++){
  3473. strengthColumn = $(tables[i][j]).find('>tbody > tr:nth-child('+(rowIndex+1)+') > td:nth-child(4)');
  3474. strengthColumn.html(strengthColumn.html().replace(currentStrength,realStrength)).css('color',color).attr('title',(difference>0?'+':'')+difference).attr('realstrength',realStrength);
  3475. }
  3476. ++counter;
  3477. });
  3478. }
  3479. if(counter==0) return false;
  3480. },"#players-table-overview > tbody td:nth-child(4)[realstrength],#players-table-overvie-club > tbody td:nth-child(4)[realstrength],#players-table-agreements > tbody td:nth-child(4)[realstrength],#players-table-agreement-club > tbody td:nth-child(4)[realstrength],#players-table-skills > tbody td:nth-child(4)[realstrength],#players-table-skill-club > tbody td:nth-child(4)[realstrength]");
  3481. Tool.features.add('CalculateNonYoungPlayersStrength','squad',function(){
  3482. if(!(Array.isArray(Tool.ageDates) && Tool.ageDates.length>0)) return false;
  3483.  
  3484. let tables =
  3485. [
  3486. ['#players-table-overview', '#players-table-skills'],
  3487. ['#players-table-overview-club', '#players-table-skills-club']
  3488. ],
  3489. add =
  3490. `<h3>${GetText('CalculateNonYoungPlayersStrength')}</h3>`+
  3491. `<div id="CalculateFutureStrength" style="text-align:center; margin:5px auto; border-radius:15px; background-color:#4a6b3247;">`+
  3492. `<div style="border-radius:15px 15px 0 0; background-color:#4a6b32; padding:15px 15px 5px 15px; margin-bottom:20px;">`,
  3493. select =
  3494. `<select id="selectPlayers" style="margin:0 0 0 20px; text-align-last:center; border-radius:10px; padding:3px 2px; background-color:black; color:green;" onfocus="this.style.backgroundColor='green'; this.style.color='black';" onfocusout="this.style.backgroundColor='black'; this.style.color='green';">`+
  3495. `<option value="0" tool_ot="ChoosePlayer">${GetText('ChoosePlayer', {tag:0})}</option>`;
  3496.  
  3497. for(let i=0 ; i<tables.length; i++){
  3498. let first_table = $(tables[i][0]);
  3499. if(!first_table.find('.open-card').length) continue;
  3500. first_table.find('> tbody > tr').each(function(rowIndex){ //eslint-disable-line no-loop-func
  3501. let row = $(this);
  3502. if(IsYoungPlayer(row.find('td:nth-child(12)'))) return true;
  3503. let position = row.find('td:nth-child(3)').text().trim(),
  3504. playerId = row.find('.open-card').attr('pid').split('-')[1],
  3505. playerName = row.find('.player-name').text(),
  3506. skills = [];
  3507. $(tables[i][1]+' > tbody > tr:nth-child('+(rowIndex+1)+') .skill-column').each(function(){
  3508. skills.push(parseFloat($(this).text()));
  3509. });
  3510. select+=`<option value="${playerId}" position="${position}" age="${row.find('td:nth-child(5)').text()}" skill="${skills.join(',')}">[${position}] ${playerName}</option>`;
  3511. });
  3512. }
  3513. select += '</select>';
  3514. add+= GetText('ChoosePlayer')+': ' + select;
  3515. add+='</div></div>';
  3516. $('#squad > div.squad.personal').append('<hr>'+add);
  3517. tables = add = select = undefined;
  3518.  
  3519. let ageDates = Tool.ageDates,
  3520. age_length = ageDates.length,
  3521. serverTime = Game.getTime(),
  3522. nextAgesDates = [];
  3523. for(let i = 0 ; i < age_length ; i++){
  3524. if(ageDates[i]*60000>serverTime){
  3525. nextAgesDates.push(ageDates[i]);
  3526. };
  3527. }
  3528. $('#selectPlayers').attr('nextAgesDates',nextAgesDates.join(','));
  3529. ageDates = age_length = serverTime = nextAgesDates = undefined;
  3530.  
  3531. $('#selectPlayers').change(function(){
  3532. $('#Comparison').add($(this).nextAll()).remove();
  3533. if(this.value!=0){
  3534. let nextAgesDates = $(this).attr('nextAgesDates').split(','),
  3535. selectedOption = $('option:selected',this),
  3536. age = parseInt(selectedOption.attr('age')),
  3537. position = selectedOption.attr('position'),
  3538. skills = selectedOption.attr('skill').split(','),
  3539. text =
  3540. `<span id="ChoosedPlayer" class="icon details open-card" pid="player-${this.value}" style="float:none; margin-top:-3px;"></span>`+
  3541. `<p style="margin-top:5px;">`+
  3542. ` ${GetText('SkillPassLimitPoint')} : `+
  3543. ` <input id="ChangeSkillLimit" type="number" style="border-radius:7px; border:1px solid gray; width:75px; text-align:center; padding:0 2px;" value="990" step="10" max="990" min="0" onkeypress="return event.charCode >= 48 && event.charCode <= 57">`+
  3544. `</p>`+
  3545. `<p style="margin-top:5px;">`+
  3546. ` ${GetText('TrainerLevel')} : ${Tool.trainerLevel} ${GetText('SortLevel')}`+
  3547. `</p>`+
  3548. `<p id="chooseRange" style="margin:10px 0;">`+
  3549. ` ${GetText('ChooseAge')} :`+
  3550. ` <input id="ageRange" class="slider" type="range" min="${age}" max="${Math.min(age+nextAgesDates.length, (position==Tool.footballerPositions[0]?(age<43?43:age+1):(age<41?41:age+1)))}" value="${age}" style="vertical-align:middle; margin:0 5px; border-radius:8px; width:300px;">`+
  3551. ` <label id="lblageRange">${age}</label>`+
  3552. `</p>`;
  3553. selectedOption = undefined;
  3554.  
  3555. for(let i in skills) skills[i] = parseFloat(skills[i]);
  3556.  
  3557. $(this).after(text);
  3558. text = undefined;
  3559.  
  3560. $('#ChangeSkillLimit').keyup(function(){
  3561. let val = $(this).val();
  3562. if(isNaN(val)) val = 0;
  3563. val = parseInt(val);
  3564. if(val<$(this).attr('min')) val = $(this).attr('min');
  3565. else if(val>$(this).attr('max')) val = $(this).attr('max');
  3566. if($(this).val() != val) $(this).val(val);
  3567. }).mouseenter(function(){
  3568. $(this).focus();
  3569. $(this).select();
  3570. }).change(function(){
  3571. $('#ageRange').trigger('oninput');
  3572. });
  3573.  
  3574. document.getElementById('ageRange').oninput = function() {
  3575. $('#Comparison').remove();
  3576. $('#lblageRange').text(this.value);
  3577.  
  3578. if(parseInt(this.value)>age){
  3579. let now = Game.getTime(),
  3580. targetDate = nextAgesDates[parseInt(this.value)-age-1]*60000,
  3581. result = CalculateFutureStrength(now, targetDate, skills, position, false, parseInt($('#ChangeSkillLimit').val()));
  3582. if(!isNaN(result.current_strength)) result.current_strength = result.current_strength.toFixed(2);
  3583. if(!isNaN(result.future.normal.strength)) result.future.normal.strength = result.future.normal.strength.toFixed(2);
  3584. if(!isNaN(result.future.premium.strength)) result.future.premium.strength = result.future.premium.strength.toFixed(2);
  3585.  
  3586. let tables =
  3587. [
  3588. {
  3589. title : GetText('Now')+' ('+GetDateText(now)+')',
  3590. skills : skills,
  3591. age : age,
  3592. strength : result.current_strength
  3593. },
  3594. {
  3595. title : GetText('NonCreditTraining')+' ('+GetDateText(targetDate)+')',
  3596. skills : result.future.normal.skills,
  3597. age : parseInt(this.value),
  3598. strength : result.future.normal.strength,
  3599. numberOfTraining : result.future.normal.trainings
  3600. },
  3601. {
  3602. title : GetText('CreditTraining')+' ('+GetDateText(targetDate)+')',
  3603. skills : result.future.premium.skills,
  3604. age : parseInt(this.value),
  3605. strength : result.future.premium.strength,
  3606. numberOfTraining : result.future.premium.trainings
  3607. }
  3608. ],
  3609. skillsId = ['penalty_area_safety', 'catch_safety', 'two_footed', 'fitness', 'shot', 'header', 'duell', 'cover', 'speed', 'pass', 'endurance', 'running', 'ball_control', 'aggressive'],
  3610. code = '<div id="Comparison" class="infosheet" style="text-align:center; margin-bottom:10px;">';
  3611. now = targetDate = undefined;
  3612.  
  3613. for(let tablesIndex = 0 ; tablesIndex < 3 ; tablesIndex++){
  3614. code +=
  3615. '<div class="data skills" style="height:100%; padding:5px; background-color:#58793d; border-radius:5px; position:static;'+(tablesIndex!=2?" margin-right:25px;":"")+'">'+
  3616. '<h2 style="font-size:12px; margin-bottom:5px; border:none; line-height:25px; height:25px; background:#4a6b32; width:auto; font-weight:bold;">'+
  3617. tables[tablesIndex].title+
  3618. '</h2>'+
  3619. '<ul style="margin:3px 0;">'+
  3620. '<li class="odd">'+
  3621. '<span style="float:left;">Ø</span>'+
  3622. '<span style="color:white;font-weight:bold;">'+
  3623. (typeof tables[tablesIndex].strength == 'number'?(tables[tablesIndex].strength).toFixed(2):tables[tablesIndex].strength)+
  3624. '</span>'+
  3625. '</li>'+
  3626. '<li class="odd">'+
  3627. '<span style="float:left;">'+
  3628. GetText('Age')+
  3629. '</span>'+
  3630. '<span style="color:white;font-weight:bold;">'+
  3631. tables[tablesIndex].age+
  3632. '</span>'+
  3633. '</li>'+
  3634. '</ul>'+
  3635. '<ul style="margin:0;">';
  3636.  
  3637. for(let j = 0 ; j < 14 ; j++){
  3638. var span='<span',
  3639. prevValOfSkill = tables[0].skills[j],
  3640. valueOfSkill = prevValOfSkill,
  3641. changedValue = '';
  3642. if(tablesIndex!=0 && tables[tablesIndex].skills[j]){
  3643. valueOfSkill = tables[tablesIndex].skills[j];
  3644. if(valueOfSkill!=prevValOfSkill){
  3645. span+= ' style="color:#ff0808"';
  3646. changedValue=
  3647. '<span class="changed-property" style="color:#3db3d5e6">'+
  3648. '(+'+(valueOfSkill-prevValOfSkill).toFixed(2)+')'+
  3649. '</span>';
  3650. }
  3651. }
  3652. if(valueOfSkill>=990) span+=' class="maximum"';
  3653. span+='>'+valueOfSkill+changedValue+'</span>';
  3654.  
  3655. let skillId = skillsId[j];
  3656. code +=
  3657. '<li class="odd">'+
  3658. '<strong>'+
  3659. '<span class="icon '+skillId+'" tooltip="tt_'+skillId+'"></span>'+
  3660. '</strong>'+
  3661. span+
  3662. '</li>';
  3663. }
  3664. code += '</ul>';
  3665.  
  3666. if(tablesIndex>0){
  3667. code +=
  3668. '<ul style="margin:4px auto 2px auto">'+
  3669. '<li class="odd" style="float:none;margin:auto;margin-bottom:1px;">'+
  3670. '<span style="float:left;">'+
  3671. GetText('Training')+
  3672. '</span>'+
  3673. '<span style="color:white;font-weight:bold;">'+
  3674. tables[tablesIndex].numberOfTraining+
  3675. '</span>'+
  3676. '</li>'+
  3677. '</ul>';
  3678. }
  3679. code +='</div>';
  3680. }
  3681. code += '</div>';
  3682. $('#chooseRange').parent().parent().append(code);
  3683. }
  3684. };
  3685. }
  3686. });
  3687. },'CalculateFutureStrength');
  3688. Tool.features.add('CalculatingStrengthOfYoungPlayer','squad',function(){
  3689. if(!(Array.isArray(Tool.ageDates) && Tool.ageDates.length>0)) return false;
  3690.  
  3691. let tables = [
  3692. ["#players-table-overview","#players-table-agreements","#players-table-skills"],
  3693. ["#players-table-overview-club","#players-table-agreements-club","#players-table-skills-club"]
  3694. ], featureElements = [];
  3695.  
  3696. for(let i = 0 ; i < tables.length ; i++){
  3697. let first_table = $(tables[i][0]);
  3698. if(!first_table.find('.open-card').length) continue;
  3699. $('>tbody>tr',first_table).each(function(rowIndex){ //eslint-disable-line no-loop-func
  3700. let row = $(this);
  3701. if(!IsYoungPlayer(row.find('td:nth-child(12)'))) return true;
  3702. let startDate = Game.getTime(),
  3703. position = row.find('td:nth-child(3)').text().trim(),
  3704. currentAge = parseInt(row.find('td:nth-child(5)').text()),
  3705. skills = [];
  3706. $(tables[i][2]+' > tbody > tr:nth-child('+(rowIndex+1)+')').find('.skill-column').each(function(){
  3707. skills.push(parseFloat($(this).text()));
  3708. });
  3709. let finishDate = row.find('td:nth-child(11)').text().trim().match(/(3[01]|[12][0-9]|0?[1-9])\.(1[012]|0?[1-9])\.((?:19|20)\d{2})/g);
  3710. if(!finishDate.length) return true;
  3711. finishDate = finishDate[0].split('.');
  3712. finishDate = new Date(finishDate[2],parseInt(finishDate[1])-1,parseInt(finishDate[0])+1).getTime();
  3713.  
  3714. let result = CalculateFutureStrength(startDate, finishDate, skills, position, true);
  3715.  
  3716. if(!isNaN(result.current_strength)) result.current_strength = result.current_strength.toFixed(2);
  3717. if(!isNaN(result.future.normal.strength)) result.future.normal.strength = result.future.normal.strength.toFixed(2);
  3718. if(!isNaN(result.future.premium.strength)) result.future.premium.strength = result.future.premium.strength.toFixed(2);
  3719.  
  3720. let nextAge = currentAge,
  3721. dates = [],
  3722. remainingDay = '-',
  3723. start = !1,
  3724. ageDates = Tool.ageDates;
  3725. for(let p = 0 ; p < ageDates.length ; p++){
  3726. let date = ageDates[p]*60000;
  3727. if(start){
  3728. if(date <= finishDate){
  3729. dates.push({
  3730. s : 'color:white;',
  3731. v : GetDateText(date)
  3732. });
  3733. nextAge++;
  3734. }
  3735. else{
  3736. dates.push({
  3737. s : 'color:aqua; border-top:1px solid white; padding-top:1px; margin-top:1px; display:block;',
  3738. v : GetDateText(date)
  3739. });
  3740. remainingDay = ((date-finishDate)/86400000).toFixed(1);
  3741. break;
  3742. }
  3743. continue;
  3744. }
  3745. if(startDate<date){
  3746. start = !0;
  3747. p--;
  3748. }
  3749. }
  3750.  
  3751. let title =
  3752. GetText('EndYouth', {tag:0, args:[
  3753. ((finishDate-startDate)/86400000).toFixed(1),
  3754. Pad2(new Date(finishDate).getDate())+'.'+
  3755. Pad2(new Date(finishDate).getMonth()+1)+'.'+
  3756. new Date(finishDate).getFullYear()
  3757. ]})+';\n'+
  3758. GetText('Age', {tag:0})+' : '+nextAge+'\n'+
  3759. 'Ø : '+result.future.normal.strength+' - ' + result.future.premium.strength+'\n'+
  3760. GetText('YoungTrainerLevelS', {tag:0})+' : '+Tool.yTrainerLevel+' '+GetText('SortLevel', {tag:0})+'\n'+
  3761. GetText('RemainingNumberOfNormalTraining', {tag:0})+' : ' + result.future.normal.trainings+'\n'+
  3762. GetText('RemainingNumberOfCreditTraining', {tag:0})+' : ' + (result.future.premium.trainings-result.future.normal.trainings)+'\n'+
  3763. GetText('RemainingNextAgeDay', {tag:0, args:[remainingDay]});
  3764.  
  3765. let selector = "";
  3766. for(let tablesIndex = 0 ; tablesIndex < 2 ; tablesIndex++){
  3767. MouseEnterLeaveEvent(
  3768. $(selector = tables[i][tablesIndex]+' > tbody > tr:nth-child('+(rowIndex+1)+') > td:nth-child(4)'), // Strength column
  3769. $(tables[i][tablesIndex]+' > tbody > tr:nth-child('+(rowIndex+1)+') > td:nth-child(5)'), // Age column
  3770. result.future.normal.strength,
  3771. nextAge,
  3772. result.future.premium.strength,
  3773. result.current_strength,
  3774. currentAge,
  3775. row.find('.open-card').attr('pid').split('-')[1],
  3776. row.find('> td.name-column > span.player-name').text().trim(),
  3777. dates
  3778. );
  3779. featureElements.push(selector);
  3780. featureElements.push(tables[i][tablesIndex]+' > tbody > tr:nth-child('+(rowIndex+1)+') > td:nth-child(5)');
  3781. $(selector = tables[i][tablesIndex]+' > tbody > tr:nth-child('+(rowIndex+1)+') > td:nth-child('+[11,8][tablesIndex]+')').attr('title',title);
  3782. featureElements.push(selector);
  3783. }
  3784.  
  3785. //$('#players-table-agreements > tbody > tr:nth-child('+(i+1)+') > td:nth-child(8)')[0].title = title;
  3786. if(i==0){
  3787. let u = this.getElementsByClassName('open-card')[0];
  3788. let TrainingSkills = Tool.trainingPlan[position]; // [9,6,3,7,8,10,5]
  3789. if(!Array.isArray(TrainingSkills)) return true;
  3790. for(let tablesIndex = 0 ; tablesIndex < tables[i].length ; tablesIndex++)
  3791. ClickOpenCard(
  3792. $(tables[i][tablesIndex]+' > tbody > tr:nth-child('+(rowIndex+1)+') .open-card'),
  3793. TrainingSkills
  3794. );
  3795. }
  3796. });
  3797. }
  3798. if(featureElements.length==0) return false;
  3799. this.hover_selector = featureElements.join(',');
  3800. tables = featureElements= undefined;
  3801.  
  3802. function MouseEnterLeaveEvent(strengthColumn, ageColumn, newStrength, nextAge, premiumNewStrength, currentStrength, currentAge, playerId, playerName, dates){
  3803. let strengthColHtml=strengthColumn.html(),
  3804. ageColHtml=ageColumn.html();
  3805.  
  3806. if(!toolTipObj.data['youngPlayerStrengthInfo_'+playerId]){
  3807. let tr =
  3808. [
  3809. [GetText('Strength'), strengthColumn.attr('sortvalue')],
  3810. [GetText('RealStrength'), currentStrength],
  3811. [GetText('YoungTrainerLevelS'), Tool.yTrainerLevel+' '+GetText('SortLevel')],
  3812. [GetText('NonCreditTraining'), newStrength + ' (' + (newStrength-currentStrength>0?'+':'') + (newStrength-currentStrength).toFixed(2)+')'],
  3813. [GetText('CreditTraining'), premiumNewStrength + ' (' + (premiumNewStrength-currentStrength>0?'+':'') + (premiumNewStrength-currentStrength).toFixed(2)+')']
  3814. ],
  3815. html =
  3816. `<h3 style="text-align:center; margin-bottom:2px;">`+
  3817. ` <label style="border-bottom:1px solid white;padding:0 2px;">${playerName}</label>`+
  3818. `</h3>`+
  3819. `<table>`+
  3820. ` <tbody>`;
  3821. playerName = currentStrength = undefined;
  3822. for(let i = 0 ; i < tr.length ; i++){
  3823. html +=
  3824. `<tr style="line-height:20px; height:20px;">`+
  3825. ` <td style="border-bottom:none; text-align:left;">`+
  3826. ` ${tr[i][0]}`+
  3827. ` <span style="float:right; margin:0 2px;">:</span>`+
  3828. ` </td>`+
  3829. ` <td style="border-bottom:none; text-align:left;">`+
  3830. ` ${tr[i][1]}`+
  3831. ` </td>`+
  3832. `</tr>`;
  3833. }
  3834. html += `</tbody></html>`;
  3835. toolTipObj.data['youngPlayerStrengthInfo_'+playerId] = html;
  3836.  
  3837. html =
  3838. `<h3 style="text-align:center; margin-bottom:2px;">`+
  3839. ` <label style="border-bottom:1px solid white; padding:0 2px;">`+
  3840. ` Age : ${currentAge} => ${nextAge} (${(nextAge-currentAge>0?'+':'')+(nextAge-currentAge)})`+
  3841. ` </label>`+
  3842. `</h3>`;
  3843. let temp = currentAge;
  3844. for(let i = 0 ; i < dates.length ; i++,temp++)
  3845. html+=`<label style="${dates[i].s}">${temp}=>${temp+1} | ${dates[i].v+(i+1<dates.length?`</label><br>`:'')}`;
  3846. dates = currentAge = undefined;
  3847. toolTipObj.data['youngPlayerAgeInfo_'+playerId] = html;
  3848. }
  3849. strengthColumn.attr('tooltip','youngPlayerStrengthInfo_'+playerId);
  3850. ageColumn.attr('tooltip','youngPlayerAgeInfo_'+playerId);
  3851. strengthColumn.attr('title','');
  3852. playerId = undefined;
  3853.  
  3854. strengthColumn.add(ageColumn).mouseenter(function(){
  3855. strengthColumn.html(`<label style="color:#00e7ff;">${newStrength} / ${premiumNewStrength}</label>`);
  3856. ageColumn.html(`<label style="color:#00e7ff;">${nextAge}</label>`);
  3857. });
  3858.  
  3859. strengthColumn.add(ageColumn).mouseleave(function(){
  3860. $(toolTipObj.toolTipLayer).hide();
  3861. strengthColumn.html(strengthColHtml);
  3862. ageColumn.html(ageColHtml);
  3863. });
  3864. }
  3865. function ClickOpenCard(openCard,TrainingSkills){
  3866. if(!openCard.length) return;
  3867. openCard.click(function(){
  3868. let openCard = $(this);
  3869. openCard.off();
  3870. let rowIndex = openCard.parents('tr').index()+1;
  3871. $('#players-table-overview > tbody > tr:nth-child('+rowIndex+') .open-card').off();
  3872. $('#players-table-agreements > tbody > tr:nth-child('+rowIndex+') .open-card').off();
  3873. $('#players-table-skills > tbody > tr:nth-child('+rowIndex+') .open-card').off();
  3874. rowIndex = undefined;
  3875.  
  3876. let playerId = openCard.attr('pid').split('-')[1];
  3877. if($('#info-player-'+playerId).length) return;
  3878.  
  3879. let max = 300;
  3880. Tool.intervals.create(function(){
  3881. if(!openCard.hasClass('loading')){
  3882. this.delete();
  3883.  
  3884. let infoDiv = $('#info-player-'+playerId),
  3885. lis = infoDiv.find('div.data.skills > ul:first > li'),
  3886. romanNumerals = ["I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV"];
  3887. for(let p = 0 ; p < 3 ; p++){
  3888. lis[TrainingSkills[p]].style.backgroundColor = '#00585d';
  3889. $(lis[TrainingSkills[p]]).append(
  3890. '<label style="float:left;">'+
  3891. romanNumerals[p]+
  3892. '</label>'
  3893. );
  3894. }
  3895.  
  3896. infoDiv.find('.skill:not(.maximum)').each(function(){
  3897. let skillValue = parseFloat(this.textContent);
  3898. $(this).mouseenter(function(){
  3899. let result = GetMaxSkill(skillValue,parseInt(Tool.yTrainerLevel)+0.5),
  3900. args = [result.required_trainings];
  3901. if(result.required_trainings>0){
  3902. $(this).css({
  3903. 'color':'#5eff0c',
  3904. 'font-weight':'bold'
  3905. }).attr({
  3906. 'title': GetText('AfterTrainings', {tag:0, args:args}),
  3907. 'tool_tt': `AfterTrainings_${encodeURIComponent(JSON.stringify(args))}`
  3908. }).text(result.max_value);
  3909. }
  3910. }).mouseleave(function(){
  3911. $(this).css({
  3912. 'color':'',
  3913. 'font-weight':''
  3914. }).removeAttr('title').text(skillValue);
  3915. });
  3916. });
  3917. return false;
  3918. }
  3919. if(--max<1) this.delete();
  3920. },50,'OpenCard_'+playerId);
  3921. });
  3922. openCard = undefined;
  3923. }
  3924. },null);
  3925. Tool.features.add('YoungPlayersHistory','squad',function(){
  3926. let YoungPlayers = Tool.getVal('YoungPlayers', {MessageBox:{},show:[]}); //Structure: http://prntscr.com/ucg9s3
  3927. if(!Array.isArray(YoungPlayers.show)) YoungPlayers.show = [];
  3928.  
  3929. let players = YoungPlayers.show;
  3930. if(players.length == 0) return false;
  3931.  
  3932. players.sort(function(a,b){
  3933. a = (a.date || a.date_).split('.');
  3934. b = (b.date || b.date_).split('.');
  3935. return new Date(b[2],b[1]-1,b[0]).getTime() - new Date(a[2],a[1]-1,a[0]).getTime();
  3936. });
  3937. let max = 10, //maximum number of players shown on a page
  3938. sayfaSayısı = Math.ceil(players.length/max),
  3939. acıkSayfa = 1;
  3940. $('#squad > div.squad.personal').append(
  3941. `<hr>`+
  3942. `<div id="container-youngs-history" class="table-container">`+
  3943. ` <h3>${GetText('TitleOfYoungPlayersTable')}</h3>`+
  3944. ` <table id="players-table-youngs-history" class="sortable-table sortable">`+
  3945. ` <thead>`+
  3946. ` <tr>`+
  3947. ` <th class="name-column sortcol">${GetText('Name')}</th>`+
  3948. ` <th class="position-column sortcol">${GetText('Position')}</th>`+
  3949. ` <th class="strength-column sortcol" tooltip="tt_strength">Ø</th>`+
  3950. ` <th class="age-column sortcol">${GetText('Age')}</th>`+
  3951. ` <th class="sortcol">${GetText('Date')}</th>`+
  3952. ` </tr>`+
  3953. ` </thead>`+
  3954. ` <tbody></tbody>`+
  3955. ` </table>`+
  3956. `</div>`
  3957. );
  3958. AddTableRows(players);
  3959. if(sayfaSayısı>1) CreateMenu(false,players.length);
  3960. players = undefined;
  3961.  
  3962. function AddTableRows(players){
  3963. for(let i = 0, k = (acıkSayfa-1)*max, player; i < max && i+k < players.length ; i++){
  3964. player = players[i+k];
  3965. $('#players-table-youngs-history>tbody').append(
  3966. `<tr class="${i%2?"even":"odd"}">`+
  3967. ` <td class="name-column">`+
  3968. ` <span pid="player-${player.id}" class="icon details open-card"></span>`+
  3969. ` <span class="player-name">${player.name}</span>`+
  3970. ` </td>`+
  3971. ` <td>${player.position}</td>`+
  3972. ` <td sortvalue="${player.strength}">${player.strength}</td>`+
  3973. ` <td>${player.age}</td>`+
  3974. ` <td${player.hasOwnProperty('date_')?` title="${GetText('mayNotTrue', {tag:0})}" tool_tt="mayNotTrue" style="font-style:italic;"`:''}>${player.date||player.date_}</td>`+
  3975. `</tr>`
  3976. );
  3977. }
  3978. }
  3979. function CreatePageLabel(sayfa){
  3980. return `<label class="page" style="color:white; cursor:pointer; text-decoration:underline;">${sayfa}</label> | `;
  3981. }
  3982. function CreateMenu(c,playersLength){
  3983. let text = '<div class="pager">';
  3984. if(acıkSayfa>=15){
  3985. for(let i = 1 ; i <=3 ; i++) text+=CreatePageLabel(i);
  3986. text+='... | ';
  3987. for(let i = acıkSayfa-10 ; i < acıkSayfa ; i++) text+=CreatePageLabel(i);
  3988. }
  3989. else{
  3990. for(let i = 1 ; i < acıkSayfa ; i++) text+=CreatePageLabel(i);
  3991. }
  3992. text+='<strong>'+acıkSayfa+'</strong>'+(acıkSayfa!=sayfaSayısı?' | ':'');
  3993. if(acıkSayfa<=sayfaSayısı-14){
  3994. for(let i = acıkSayfa+1 ; i<=acıkSayfa+10; i++) text+=CreatePageLabel(i);
  3995. text+='... | ';
  3996. for(let i = sayfaSayısı-2 ; i < sayfaSayısı ; i++) text+=CreatePageLabel(i);
  3997. }
  3998. else{
  3999. for(let i = acıkSayfa+1 ; i < sayfaSayısı ; i++) text+=CreatePageLabel(i);
  4000. }
  4001. if(acıkSayfa!==sayfaSayısı) text+=`<label class="page" style="color:white; cursor:pointer; text-decoration:underline;">${sayfaSayısı}</label>`;
  4002. text+=' '+GetText('total')+' : '+playersLength+'</div>';
  4003. let e = $('#players-table-youngs-history');
  4004. if(c){
  4005. e.prev().remove();
  4006. e.next().remove();
  4007. }
  4008. e.before(text);
  4009. e.after(text);
  4010. $('#container-youngs-history').find('.page').click(function(){
  4011. acıkSayfa = parseInt($(this).text());
  4012. let players = Tool.getVal('YoungPlayers',{MessageBox:{},show:[]}).show; //Structure: http://prntscr.com/ucg9s3
  4013. $('#players-table-youngs-history>tbody').html('');
  4014. AddTableRows(players);
  4015. CreateMenu(true,players.length);
  4016. });
  4017. }
  4018. },'#players-table-youngs-history',[
  4019. [
  4020. 'main',
  4021. function(){
  4022. //Yeni gelen genç oyuncuların geliş tarihlerini bulma
  4023. if(typeof Tool.news.youngPlayer=='object'){ //{"title":'Jugendspieler',"beforeName":"diesen ","afterName":" mal"}
  4024. let yData=Tool.news.youngPlayer;
  4025. GetMessagesByTitle(yData.title,(messages)=>{
  4026. let YoungPlayers = Tool.getVal('YoungPlayers',{MessageBox:{}, show:[]}); //Structure: http://prntscr.com/ucg9s3
  4027. if(typeof YoungPlayers.MessageBox != 'object') YoungPlayers.MessageBox = {};
  4028. if(!Array.isArray(YoungPlayers.show)) YoungPlayers.show = [];
  4029.  
  4030. let MessageBox = YoungPlayers.MessageBox,
  4031. show = YoungPlayers.show,
  4032. html,start,end,playerName,date,newPlayer=0;
  4033.  
  4034. messages.forEach(message=>{ //message=> element : $('#newscenter-preview-'+id)
  4035. html = message.html().trim();
  4036. start = html.indexOf(yData.beforeName)+yData.beforeName.length;
  4037. end = html.indexOf(yData.afterName,start);
  4038. playerName = html.substring(start,end);
  4039. date = message.parents('tr').first().find('.last-column').text().trim();
  4040. message.html(html.substring(0,start)+`<font style="cursor:default;" title="${yData.title}" color="#89f4ff">${playerName}</font>`+html.substring(end));
  4041. playerName=playerName.trim();
  4042. if(!MessageBox.hasOwnProperty(playerName) && //MessageBox'a kayıtlı olmamış olacak
  4043. undefined==show.find(p=>{return p.name==playerName && p.date==date;})){ //show'a aynı isim ve tarihte kaydedilmiş genç futbolcu olmayacak
  4044. MessageBox[playerName] = date; //Yeni gelen gencin hangi tarihte geldiğinin kaydı alınıyor
  4045. newPlayer++;
  4046. }
  4047. });
  4048. if(newPlayer) Tool.setVal('YoungPlayers',YoungPlayers);
  4049. });
  4050. }
  4051. }
  4052. ],
  4053. [
  4054. 'squad',
  4055. function(){
  4056. if($('#players-table-overview-club > tbody').find('.open-card').length){
  4057. let YoungPlayers = Tool.getVal('YoungPlayers',{MessageBox:{}, show:[]}); //Structure: http://prntscr.com/ucg9s3
  4058. if(typeof YoungPlayers.MessageBox != 'object') YoungPlayers.MessageBox = {};
  4059. if(!Array.isArray(YoungPlayers.show)) YoungPlayers.show = [];
  4060.  
  4061. let MessageBox = YoungPlayers.MessageBox,
  4062. show = YoungPlayers.show,
  4063. update = 0;
  4064.  
  4065. let strength;
  4066. $('#players-table-overview-club > tbody > tr').each(function(){
  4067. strength=parseInt($('td:nth-child(4)',this).attr('sortvalue'));
  4068. if(IsYoungPlayer($('>td:nth-child(12)',this)) && 90>strength){ // limited by strength: https://forum.fussballcup.de/showthread.php?t=417372&page=22#post7485413
  4069. let playerId = $('.open-card',this).attr('pid').split('-')[1],
  4070. playerName = $('.player-name',this).text().trim(), //Format: lastNames, firstNames
  4071. found = !1;
  4072. for(let i = 0 ; i < show.length ; i++){
  4073. if(playerId == show[i].id){
  4074. found = !0;
  4075. if(show[i].hasOwnProperty('date_') && MessageBox.hasOwnProperty(playerName)){
  4076. show[i].date = MessageBox[playerName];
  4077. delete MessageBox[playerName];
  4078. delete show[i].date_;
  4079. ++update;
  4080. }
  4081. break;
  4082. }
  4083. }
  4084. if(!found){
  4085. let data = {
  4086. id : playerId,
  4087. name : playerName,
  4088. position : $('td:nth-child(3)',this).text().trim(),
  4089. strength : strength,
  4090. age : parseInt($('td:nth-child(5)',this).text()),
  4091. };
  4092. if(MessageBox.hasOwnProperty(playerName)){
  4093. data.date = MessageBox[playerName];
  4094. delete MessageBox[playerName];
  4095. }
  4096. else{
  4097. let gameTime = new Date(Game.getTime());
  4098. data.date_ = Pad2(gameTime.getDate())+'.'+Pad2(gameTime.getMonth()+1)+'.'+gameTime.getFullYear();
  4099. }
  4100. show.splice(0,0,data); //Add to the top
  4101. ++update;
  4102. }
  4103. }
  4104. });
  4105. if(update) Tool.setVal('YoungPlayers',YoungPlayers);
  4106. }
  4107. }
  4108. ]
  4109. ]);
  4110. Tool.features.add('TrainingGroups','training',function(){
  4111. if(Tool.getVal("TrainingGroups")==undefined) return false;
  4112. let data = Tool.getVal("TrainingGroups");
  4113. $('#training > div.schedule > div.table-container > table > tbody > tr').each(function(i){
  4114. if($('th',this).length){
  4115. var grupId = i/4 + 1;
  4116. var th = $('th',this)[1];
  4117. th.style.textAlign = 'left';
  4118. th.style.fontSize = '11px';
  4119. toolTipObj.data.showPlayersInGroups = GetText('NoInformation')+'!';
  4120. if(data[grupId]!==undefined){
  4121. var oyuncuSayısı = data[grupId].length;
  4122. if(oyuncuSayısı!==0){
  4123. th.innerHTML = GetText('TrainingGroupInformation', {args:[`<strong grupId="${grupId}" style="color:green; font-size:12px; cursor:default;" tooltip="showPlayersInGroups">${oyuncuSayısı}</strong>`]});
  4124. $('strong',th).mouseenter(function(){
  4125. var d = Tool.getVal("TrainingGroups")[$(this).attr('grupId')];
  4126. var text = '';
  4127. for(var i = 0 ; i < d.length ; i++){
  4128. text+=`[${d[i].position}] ${d[i].name}<br>`;
  4129. }
  4130. text = text.substring(0,text.length-4);
  4131. toolTipObj.data.showPlayersInGroups = text;
  4132. });
  4133. }
  4134. else th.innerHTML = GetText('NoPlayersInTheGroup');
  4135. }
  4136. else th.innerHTML = GetText('NoRecord');
  4137. }
  4138. });
  4139. },null,[
  4140. 'training->groups',
  4141. function(){
  4142. let data = {},
  4143. groupLength = $('#players-table-skills > tbody').find('.select-box-container:first >select >option').length;
  4144. for(let i=1 ; i<=groupLength ; i++) data[i] = [];
  4145.  
  4146. $('#players-table-skills > tbody > tr').each(function(){
  4147. data[$('.select-box-container:first >select',this).val()].push({
  4148. name : $('.player-name',this).text().trim(),
  4149. position: $('td:nth-child(3)',this).text().trim()
  4150. });
  4151. });
  4152. Tool.setVal('TrainingGroups',data);
  4153. }
  4154. ]);
  4155. Tool.features.add('CampHistory','camp',function(){
  4156. let imagesPos = [-641,-962,-214,-534,-748,-321,0,-107,-427,-854],
  4157. data = Tool.getVal('CampHistory',[]);
  4158.  
  4159. $('<div id="allCamps">').html(
  4160. imagesPos.reduce((acc,i,idx)=>acc+`<div class="camp-${idx+1}"><div id="camps_${idx+1}" class="image" style="margin-right:4px; float: left; opacity: 0.2;"></div></div>`,'')
  4161. ).appendTo('#camp');
  4162.  
  4163. if(data.length){/*Show*/
  4164. //Tablo oluşturuluyor.
  4165. function dateFormat(a){
  4166. let b = a.split('.');
  4167. b = new Date(b[2],parseInt(b[1])-1,parseInt(b[0])+3);
  4168. return a+' - ' + Pad2(b.getDate())+'.'+Pad2(b.getMonth()+1)+'.'+b.getFullYear();
  4169. }
  4170.  
  4171. let text =
  4172. `<table id="lastCamps">`+
  4173. ` <thead>`+
  4174. ` <tr style="background:url();">`+
  4175. ` <th colspan="7">${GetText('PreviouslyVisitedCamps')}</th>`+
  4176. ` </tr>`+
  4177. ` <tr>`+
  4178. ` <th style="text-align:left;">${GetText('No')}</th>`+
  4179. ` <th style="text-align:left;">${GetText('Camp')}</th>`+
  4180. ` <th style="text-align:left;">${GetText('Country')}</th>`+
  4181. ` <th style="text-align:left;">${GetText('Price')}</th>`+
  4182. ` <th style="text-align:left;">${GetText('_Skills')}</th>`+
  4183. ` <th style="text-align:left;">${GetText('Definition')}</th>`+
  4184. ` <th style="text-align:left;">${GetText('Date')}</th>`+
  4185. ` </tr>`+
  4186. ` </thead>`+
  4187. ` <tbody>`;
  4188.  
  4189. for(let i = 0 ; i < data.length ;i++){
  4190. let camp = data[i];
  4191. $('#camps_'+camp.campNo).css('opacity',1)
  4192. text+=
  4193. `<tr>`+
  4194. ` <td style="color:white;font-weight: bold;text-align:center;">${i+1}</td>`+
  4195. ` <td width="160" style="text-align:left;">`+
  4196. ` <h3 style="margin:0;">${camp.campName}</h3>`+
  4197. ` <div class="image" style="display:none;margin: 1px auto 3px; background-position: 0 ${imagesPos[camp.campNo-1]}px;"></div>`+
  4198. ` </td>`+
  4199. ` <td width="100" style="text-align:left;">`+
  4200. ` <img class="flag" name="__tooltip" tooltip="tt_${camp.country.img}" src="/static/images/countries/${camp.country.img}.gif" alt=""> ${camp.country.name}`+
  4201. ` </td>`+
  4202. ` <td width="80" style="text-align:left;">${camp.price}`+
  4203. ` <span class="icon currency"></span>`+
  4204. ` </td>`+
  4205. ` <td style="text-align:left;">`;
  4206. camp.skills.forEach(skill=>{ //eslint-disable-line no-loop-func
  4207. text+=`<span style="margin-right:3px;" class="icon ${skill}" name="__tooltip" tooltip="tt_${skill}"></span>`;
  4208. });
  4209. text+=
  4210. ` </td>`+
  4211. ` <td style="white-space: pre-wrap;font-Size:10px;line-height: 1.5;text-align:left;">${camp.description}</td>`+
  4212. ` <td>`+
  4213. ` <img src="${Tool.sources.getLink('https://www.pinclipart.com/picdir/big/561-5616345_transparent-time-clock-icon-png-5-minute-timer.png')}" alt="clock" height="15px" style="margin:0 2px 1px 0;cursor:help;text-align:left;" title="${GetText('ServerDate', {tag:0})}" tool_tt="ServerDate">`+
  4214. ` ${dateFormat(camp.date)}`+
  4215. ` </td>`+
  4216. `</tr>`;
  4217. }
  4218. text+=`</tbody><tfoot><tr></tr></tfoot></table>`;
  4219. $('#allCamps').before(text);
  4220. $('#lastCamps').find('.image').each(function(){
  4221. let image = $(this);
  4222. image.parent('td').mouseenter(function(){
  4223. image.slideDown();
  4224. }).mouseleave(function(){
  4225. image.slideUp();
  4226. });
  4227. });
  4228. }
  4229.  
  4230. if(!$('#camp > div.list-container > ul > li.disabled').length && //Kamp ayarlama inaktif olmayacak.
  4231. !$('#camp > div.list-container > ul > li > p.not-available').length //Kamplar kullanılmıyor olmayacak.
  4232. ){/*Save*/
  4233. //Kamplar açık ve gidilebiliyor!
  4234. $('#camp > div.list-container > ul > li').each(function(){
  4235. let parent = this,
  4236. button = $('div.buttons > span > a',this);
  4237. button.attr('href_',button.attr('href')).removeAttr('href').click(function(){
  4238. $(this).off();
  4239. let skills = $('ul > li',parent),
  4240. _skills = [];
  4241. skills.each(function(){
  4242. _skills.push($('span',this).first().attr('class').replace('icon ',''));
  4243. });
  4244. let country = {name:'Berlin',img:'DEU'};
  4245. country.name = $('p',parent).first().text().trim();
  4246. var img = $('p > img',parent).first().attr('src');
  4247. country.img = img.substring(img.lastIndexOf('/')+1,img.lastIndexOf('.'));
  4248. //Yeni kampı en öne ekle!
  4249. data.splice(0,0,{
  4250. campName : $('h3',parent).first().text(),
  4251. campNo : $(parent).attr('class').replace('camp-',''),
  4252. date : $('span',this).first().text().trim().match(/(3[01]|[12][0-9]|0?[1-9])\.(1[012]|0?[1-9])\.((?:19|20)\d{2})/g)[0],
  4253. skills : _skills,
  4254. price : $('span.currency-number',parent).text().trim(),
  4255. country : country,
  4256. description: $('p.description',parent).text().trim(),
  4257. });
  4258. Tool.setVal('CampHistory',data);
  4259. location.href = $(this).attr('href_');
  4260. });
  4261. });
  4262. }
  4263. },null);
  4264. Tool.features.add('TransferDates','transfermarket',async function(){
  4265. let LeagueData = Tool.getVal('LeagueData'), save = true;
  4266. if(typeof LeagueData=='object' && (LeagueData.lastMatchDate+86400000)>Game.getTime()) save = false;
  4267.  
  4268. if(save){
  4269. let content = await Game.getPage('?w='+worldId+'&area=user&module=statistics&action=games','#content');
  4270. LeagueData = SaveLeagueData(content);
  4271. if(LeagueData==false) return false;
  4272. }
  4273.  
  4274. let aDay = 24*60*60*1000,
  4275. timeToMs = (t)=> ((t.h*60+t.m)*60+t.s)*1000,
  4276. fComingTime = timeToMs({h:6, m:0, s:0}),
  4277. tmChangingTime = timeToMs({h:0, m:0, s:0}),
  4278. firstMatchDate = LeagueData.firstMatchDate,
  4279. firstHalfFinalMatchDate= LeagueData.firstHalfFinalMatchDate,
  4280. lastMatchDate= LeagueData.lastMatchDate,
  4281. now = Game.getTime(),
  4282. footballerComing = null,
  4283. tmDateChanging = null;
  4284.  
  4285. if((firstMatchDate-1*aDay+fComingTime)>now)/*Alınan Oyuncu Bir Sonraki Gün Gelecek*/
  4286. footballerComing = new Date(new Date(now).getFullYear(),new Date(now).getMonth(),new Date(now).getDate()+1).getTime()+fComingTime;
  4287. else if((firstHalfFinalMatchDate+fComingTime)>now)/*Alınan Oyuncular Lig Arasında Gelecek*/
  4288. footballerComing = firstHalfFinalMatchDate+aDay+fComingTime;
  4289. else footballerComing = lastMatchDate+aDay+fComingTime; /*Alınan Oyuncu Lig Sonunda Gelecek*/
  4290.  
  4291. if((firstMatchDate-1*aDay+tmChangingTime)>now)/*Transfer Tarihinin Değişeceği Tarih*/
  4292. tmDateChanging = firstMatchDate-1*aDay+tmChangingTime;
  4293. else if((firstHalfFinalMatchDate+tmChangingTime)>now)/*Transfer Tarihinin Değişeceği Tarih*/
  4294. tmDateChanging = firstHalfFinalMatchDate+tmChangingTime;
  4295.  
  4296. let header = $('#content > h2:first'),
  4297. h_content = header.html() +
  4298. GetText('FootballersAreComing')+' : '+
  4299. `<label class="cntDwnTrnsfMrkt" style="color:#17fc17;" intervalName="footballerComing" title="${GetDateText(footballerComing)}" finish="${footballerComing}"></label>`;
  4300. if(tmDateChanging!=null){
  4301. h_content+=' '+
  4302. GetText('TransferDateWillChange')+' : '+
  4303. `<label class="cntDwnTrnsfMrkt" style="color:orange;" intervalName="tmDateChanging" title="${GetDateText(tmDateChanging)}" finish="${tmDateChanging}"></label>`;
  4304. }
  4305. header.html(h_content);
  4306. $('.cntDwnTrnsfMrkt').each(function(){
  4307. let t = $(this);
  4308. t.removeClass('cntDwnTrnsfMrkt');
  4309. Tool.intervals.create(function(){
  4310. let sec = parseInt((parseInt(t.attr('finish'))-Game.getTime())/1000);
  4311. if(sec<1){
  4312. this.delete();
  4313. t.html(GetText('ItIsOver'));
  4314. return;
  4315. }
  4316. t.html(SecToTime(sec));
  4317. },1000,t.attr('intervalName'));
  4318. t.removeAttr('intervalName');
  4319. });
  4320. },null,[
  4321. 'fixture',
  4322. function(){
  4323. if($('#content').find('.date-selector').length){
  4324. let LeagueData = Tool.getVal('LeagueData'), save = true;
  4325. if(typeof LeagueData=='object' && (LeagueData.lastMatchDate+86400000)>Game.getTime()) save = false;
  4326. if(save) SaveLeagueData($('#content'));
  4327. }
  4328. }
  4329. ]);
  4330. Tool.features.add('GoOffer','transfermarket',function(){
  4331. let data = Tool.getVal('increaseBid');//{playerName:'Criyessei',process:1}
  4332. if(typeof data != 'object') return false;
  4333. let playerName = data.playerName,
  4334. process = data.process,
  4335. find_player = !1;
  4336. if(process==1){
  4337. //Teklif tablonuzda oyuncu varsa devam edecek.
  4338. if($('#own-offers > tbody').find('.open-card').length){
  4339. $('#own-offers > tbody > tr').each(function(){
  4340. if(playerName == $(this).find('.name-column').first().text().trim()){
  4341. find_player = !0;
  4342. let clubName = $(this).find('td.name-column').last().attr('sortvalue');
  4343. if($('#club').val()==clubName){
  4344. find_player = !1;
  4345. process_2();
  4346. }
  4347. else{
  4348. $('#age_min').val(16);
  4349. $('#age_max').val(34);
  4350. $('#searchform > ul > li.strength > span:nth-child(2) > input[type="text"]').val(0);
  4351. $('#searchform > ul > li.strength > span:nth-child(3) > input[type="text"]').val(999);
  4352. $('#positions').val(0);
  4353. $('#club').val(clubName);
  4354. Tool.setVal('increaseBid', {playerName:playerName,process:2});
  4355. $('#searchform > ul > li.transfermarket-search-button > span > a > span').click();
  4356. }
  4357. return false;
  4358. }
  4359. });
  4360. }
  4361. }
  4362. else process_2();
  4363. function process_2(){
  4364. if($('#content > div.container.transfermarket > div.table-container > table > tbody').find('.open-card').length){
  4365. $('#content > div.container.transfermarket > div.table-container > table > tbody > tr').each(function(){
  4366. if(playerName == $(this).find('.name-column').first().text().trim()){
  4367. find_player = !0;
  4368. let tr = this,
  4369. pageHeight = $(window).height();
  4370. $('html, body').animate({ scrollTop: GetOffset(tr).top-pageHeight/2 }, 'fast');
  4371. setTimeout(function(){
  4372. tr.style = 'background-color:#fff2ac; background-image:linear-gradient(to right, #ffe359 0%, #fff2ac 100%);';
  4373. setTimeout(function(){
  4374. tr.style='';
  4375. },2000);
  4376. },200);
  4377. Tool.delVal('increaseBid');
  4378. return false;
  4379. }
  4380. });
  4381. }
  4382. }
  4383. if(!find_player){
  4384. Game.giveNotification(false, GetText('bidIncreasedPlayerNotFound'));
  4385. Tool.delVal('increaseBid');
  4386. }
  4387. },null,[
  4388. 'main',
  4389. function(){
  4390. //Futbolcuya verilen teklif geçilirse kolay bir şekilde bu futbolcuyu transfer pazarında görüntüleyebileceğiz.
  4391. if(typeof Tool.news.increaseBid=='object'){// {"title":"Transfermarkt","control":"überboten","beforeName":"für ","afterName":" wurde"}
  4392. let iData = Tool.news.increaseBid;
  4393. GetMessagesByTitle(iData.title,(messages)=>{
  4394. let text,message,messageP=[];
  4395. for(let i=0; i<messages.length; i++){
  4396. message = messages[i]; // $ element
  4397. text = message.text().trim();
  4398. if(text.indexOf(iData.control)!=-1)
  4399. messageP.push(message.parent());
  4400. }
  4401. for(let i = 0 ; i < messageP.length ; i++){
  4402. messageP[i].click(function(){ // eslint-disable-line no-loop-func
  4403. let messageId = this.id.split('-')[2],
  4404. intName = 'OpenMessage_'+messageId,
  4405. k,max=50;
  4406. Tool.intervals.create(function(){
  4407. k = $('#readmessage-home');
  4408. if(k.length){
  4409. let a = $('<div>'+k.html()+'</div>');
  4410. a.find('a').remove();
  4411. let playerName = a.text().trim(),
  4412. start = playerName.indexOf(iData.beforeName)+iData.beforeName.length,
  4413. end = playerName.indexOf(iData.afterName,start);
  4414. playerName = playerName.substring(start,end).trim();
  4415. k.html(k.html().replace(playerName, `<font style="cursor:default;" color="#89f4ff">${playerName}</font>`));
  4416. k.find('a:last').click(function(){
  4417. Tool.setVal('increaseBid',{playerName:playerName,process:1});
  4418. });
  4419. this.delete();
  4420. }
  4421. else{
  4422. if(!--max) this.delete();
  4423. }
  4424. },50,intName);
  4425. }); // eslint-disable-line no-loop-func
  4426. }
  4427. });
  4428. }
  4429. }
  4430. ]);
  4431. Tool.features.add('ShowBoughtPlayers','transfermarket',function(){
  4432. //Sattığımız oyunculara gelen teklifleri kabul edersek veya reddedersek PlayersData.AcceptedOffers güncellenmeli
  4433. let updated=0,
  4434. data = Tool.getVal('PlayersData',{}); //Structure: http://prntscr.com/uc2p4v
  4435. if(typeof data.AcceptedOffers != 'object') data.AcceptedOffers = {};
  4436. let AcceptedOffers = data.AcceptedOffers;
  4437.  
  4438. $('#foreigner-offers > tbody > tr').each(function(){ //Sattığımız oyunculara gelen teklifleri kontrol et
  4439. let accept_button = $(this).find('a.button[href*="do=accept"]');
  4440. if(accept_button.length){ //accept the bid
  4441. accept_button.attr('_href', $(this).find('.button:first > a')[0].href)
  4442. .removeAttr('href')
  4443. .css('cursor','pointer')
  4444. .click(function(){
  4445. $(this).off();
  4446. let data = Tool.getVal('PlayersData',{});
  4447. if(typeof data.AcceptedOffers != 'object') data.AcceptedOffers = {};
  4448. let AcceptedOffers = data.AcceptedOffers,
  4449. tr = $(this).parents('tr').first(),
  4450. playerId = tr.find('.open-card').attr('pid').split('-')[1],
  4451. a_club = $(`>td.name-column >a[clubid]:not([clubid="${Tool.clubId}"])`,tr).first(),
  4452. clubId = a_club.attr('clubid');
  4453.  
  4454. if(!AcceptedOffers.hasOwnProperty(playerId)){
  4455. AcceptedOffers[playerId] = {
  4456. playerName: tr.find('.player-name').text().trim(),
  4457. offers:{} //Accepted offers
  4458. };
  4459. }
  4460. AcceptedOffers[playerId].offers[clubId] = {
  4461. clubName: a_club.text().trim(),
  4462. price : tr.find('.currency-container').last().parent().attr('sortvalue').split('.').join(''),
  4463. date : GetDateText(Game.getTime())
  4464. };
  4465. Tool.setVal('PlayersData',data);
  4466. $(this).attr('href',$(this).attr('_href')).click();
  4467. });
  4468. }
  4469. else if($(this).find('>td.last-column a[href*="do=dismissOfferAcceptance"]').length){
  4470. //Oyuncuya gelen teklif daha önceden kabul edilmiş. Eğer verilerde kayıtlı değilse kaydedilecek.
  4471. let a_club = $(`>td.name-column >a[clubid]:not([clubid="${Tool.clubId}"])`,this).first(),
  4472. clubId = a_club.attr('clubid'),
  4473. playerId = $(this).find('.open-card').attr('pid').split('-')[1];
  4474.  
  4475. if(AcceptedOffers.hasOwnProperty(playerId)){
  4476. if(AcceptedOffers[playerId].offers.hasOwnProperty(clubId)) return; //continue
  4477. }
  4478. else{
  4479. AcceptedOffers[playerId] = {
  4480. playerName: $(this).find('.player-name').text().trim(),
  4481. offers:{}
  4482. };
  4483. }
  4484. AcceptedOffers[playerId].offers[clubId] = {
  4485. clubName : a_club.text().trim(),
  4486. price : $(this).find('.currency-container').last().parent().attr('sortvalue').split('.').join(''),
  4487. date : '-'
  4488. };
  4489. ++updated;
  4490. }
  4491. });
  4492.  
  4493. //Teklifi iptal etmek için butona basıyoruz
  4494. if(Game.link.pr.do=="dismissOfferAcceptance" && ['playerid','clubid'].every(k=>Game.link.pr.hasOwnProperty(k))){
  4495. let playerId = Game.link.pr.playerid,
  4496. clubId = Game.link.pr.clubid,
  4497. offerStillExist = undefined != $('#foreigner-offers > tbody > tr .open-card').toArray().find(e=>{
  4498. return $(e).attr('pid').split('-')[1] == playerId && $(e).parents('tr').first().find('td.name-column:last > a').attr('clubid') == clubId;
  4499. });
  4500. if(!offerStillExist){ //Teklif silindi
  4501. if(AcceptedOffers.hasOwnProperty(playerId)){
  4502. let playerData = AcceptedOffers[playerId];
  4503. if(playerData.offers.hasOwnProperty(clubId)){
  4504. delete playerData.offers[clubId];
  4505. if($.isEmptyObject(playerData.offers)) delete AcceptedOffers[playerId];
  4506. ++updated;
  4507. }
  4508. }
  4509. }
  4510. }
  4511. if(updated) Tool.setVal('PlayersData',data);
  4512.  
  4513.  
  4514. //Satın aldığımız oyuncuların listelenmesi. PlayersData.BuyPlayers verisi kullanarak
  4515. if(!Array.isArray(data.BuyPlayers)) data.BuyPlayers = [];
  4516. start(data.BuyPlayers);
  4517.  
  4518. function start(BoughtPlayers){
  4519. if(!BoughtPlayers.length){
  4520. UploadPlayersData();
  4521. return;
  4522. }
  4523.  
  4524. $('#own-offers').after(
  4525. `<h3>${GetText('ListofPurchasedFootballers')}</h3>`+
  4526. `<table id="purchased-players" class="sortable-table sortable">`+
  4527. ` <thead>`+
  4528. ` <tr class="">`+
  4529. ` <th class="nosort">${GetText('Country')}</th>`+
  4530. ` <th class="name-column sortcol">${GetText('Name')}<span class="sort-status"></span></th>`+
  4531. ` <th class="sortcol">${GetText('SortPosition')}<span class="sort-status"></span></th>`+
  4532. ` <th class="sortcol" name="__tooltip" tooltip="tt_strength"> Ø <span class="sort-status"></span></th>`+
  4533. ` <th class="sortcol">${GetText('Age')}<span class="sort-status"></span></th>`+
  4534. ` <th class="sortcol">${GetText('Salary')}<span class="sort-status"></span></th>`+
  4535. ` <th class="sortcol">${GetText('Price')}</th>`+
  4536. ` <th class="nosort">${GetText('Contract')}<span class="sort-status"></span></th>`+
  4537. ` <th class="sortcol">${GetText('Club')}<span class="sort-status"></span> </th>`+
  4538. ` <th class="sortcol">${GetText('Date')}<span class="sort-status"></span></th>`+
  4539. ` <th class="sortcol">${GetText('Delete')}</th>`+
  4540. ` </tr>`+
  4541. ` </thead>`+
  4542. ` <tbody></tbody>`+
  4543. ` <tfoot>`+
  4544. ` <tr class="even">`+
  4545. ` <td class="last-column" colspan="9"></td>`+
  4546. ` </tr>`+
  4547. ` </tfoot>`+
  4548. `</table>`
  4549. );
  4550. let h3=$('#purchased-players').prev();
  4551. $(`<img style="float:right;cursor:pointer;margin-Right:5px;" src="${Tool.sources.getLink('https://www.clipartmax.com/png/full/52-527627_animated-down-arrow-arrow-down-gif-png.png')}" alt="download" width="20px" height="20px" title="${GetText('Download', {tag:0})}" tool_tt="Download">`)
  4552. .appendTo(h3)
  4553. .click(function(){ DownloadAsTextFile(JSON.stringify(BoughtPlayers,null,'\t'), "Bought Players Datas"); });
  4554.  
  4555. $(`<img style="margin-Right:7px;float:right;cursor:pointer" src="${Tool.sources.getLink('https://www.clipartmax.com/png/full/301-3016667_red-cross-clipart-high-resolution-red-cross-emoji-gif.png')}" alt="remove2" width="15px" height="15px" title="${GetText('Delete', {tag:0})}" tool_tt="Delete">`)
  4556. .appendTo(h3)
  4557. .click(function(){
  4558. if(confirm(GetText('Warning', {tag:0}))){
  4559. let table = $('#purchased-players');
  4560. table.prev().remove();
  4561. table.remove();
  4562. let data = Tool.getVal('PlayersData');
  4563. delete data.BuyPlayers;
  4564. Tool.setVal('PlayersData',data);
  4565. UploadPlayersData();
  4566. }
  4567. });
  4568. h3=undefined;
  4569.  
  4570. let tbody = $('#purchased-players>tbody');
  4571. BoughtPlayers.forEach((a,i)=>{
  4572. tbody.append(
  4573. `<tr class="${i%2?"even":"odd"}">`+
  4574. ` <td>`+
  4575. ` <img name="__tooltip" tooltip="tt_${a.playerCountry}" src="/static/images/countries/${a.playerCountry}.gif">`+
  4576. ` </td>`+
  4577. ` <td style="white-space:pre-wrap; line-height:1.5; width:25%; max-width:30%; text-align:left;">`+
  4578. ` <span pid="player-${a.playerId}" class="icon details open-card"></span>`+
  4579. ` <span class="player-name">${a.playerName}</span>`+
  4580. ` </td>`+
  4581. ` <td>${a.position}</td>`+
  4582. ` <td>${a.strength}</td>`+
  4583. ` <td>${a.age}</td>`+
  4584. ` <td>${a.salary.toLocaleString()}<span class="icon currency"></span></td>`+
  4585. ` <td>${a.price.toLocaleString()}<span class="icon currency"></span></td>`+
  4586. ` <td>${a.season+' '+(a.season==1?GetText("Season"):GetText("Seasons"))}</td>`+
  4587. ` <td style="text-align:left; white-space:pre-wrap; line-height:1.5; width:17%; max-width:20%;" sortvalue="${a.club.name}">`+
  4588. ` <a href="#/index.php?w=${worldId}&area=user&module=profile&action=show&clubId=${a.club.id}" clubid="${a.club.id}">${a.club.name}</a>`+
  4589. ` </td>`+
  4590. ` <td>${a.date}</td>`+
  4591. ` <td class="last-column">`+
  4592. ` <img class="DeletePurchasedPlayerData" playerid="${a.playerId}" src="${Tool.sources.getLink('https://www.clipartmax.com/png/full/301-3016667_red-cross-clipart-high-resolution-red-cross-emoji-gif.png')}" alt="remove3" heigth="15px" width="15px" style="cursor:pointer">`+
  4593. ` </td>`+
  4594. `</tr>`
  4595. );
  4596. });
  4597.  
  4598. $('#purchased-players').find('.DeletePurchasedPlayerData').click(function(){
  4599. let playerId = $(this).attr('playerid'),
  4600. data = Tool.getVal('PlayersData',{});
  4601. BoughtPlayers = data.BuyPlayers; //Structure: http://prntscr.com/uc2p4v
  4602. let idx = BoughtPlayers.findIndex(p=>p.playerId==playerId);
  4603. if(idx==-1) return;
  4604. BoughtPlayers.splice(idx,1);
  4605. data.BuyPlayers = BoughtPlayers;
  4606. Tool.setVal('PlayersData',data);
  4607.  
  4608. let tr = $(this).parents('tr').first();
  4609. tr.hide(400);
  4610. setTimeout(function(){
  4611. let i = tr.index();
  4612. tr.remove();
  4613. let table = $('#purchased-players'),
  4614. players = table.find('> tbody > tr');
  4615. if(players.length){
  4616. for(; i < players.length ; i++)
  4617. players[i].className = i%2?"even":"odd";
  4618. }
  4619. else{
  4620. table.prev().remove();
  4621. table.remove();
  4622. UploadPlayersData();
  4623. }
  4624. },400);
  4625. });
  4626.  
  4627.  
  4628. //Show Profit
  4629. let elements={p:[],n:[]};
  4630. $('#foreigner-offers > tbody > tr').toArray().map(t=>{
  4631. let td=$(t).find('>td:nth-child(8)'), offer;
  4632. if(!td[0].hasAttribute('sortvalue') || isNaN(offer = parseInt(td.attr('sortvalue')))) return false;
  4633. let id = $(t).find('.open-card').attr('pid').split('-')[1],
  4634. data = BoughtPlayers.find(p=>p.playerId==id);
  4635. if(data === undefined) return false;
  4636. return {
  4637. offer: offer,
  4638. price: data.price,
  4639. e : $(t).find('>td .currency-number').last()
  4640. };
  4641. }).filter(o=>o!==false).forEach(o=>{
  4642. let price = o.price,
  4643. profit = o.offer - price,
  4644. title_key = profit<0?GetText('Loss', {tag:0}):GetText('Gain', {tag:0});
  4645. o.e.css('color',profit>0?'#20ff63':profit==0?"white":"#a10c00").after(
  4646. `<span title="${title_key} : ${profit.toLocaleString()} €" tool_tt="${title_key}_{X} : ${profit.toLocaleString()} €" style="font-weight:bold; color:#42ead4; display:none; vertical-align:top;">${price.toLocaleString()}</span>`
  4647. );
  4648. elements.p.push(o.e);
  4649. elements.n.push(...[o.e.parent(),o.e.next()]);
  4650. });
  4651.  
  4652. $(elements.p).map($.fn.toArray).mouseenter(function(){
  4653. $(this).hide().next().show();
  4654. });
  4655. $(elements.n).map($.fn.toArray).mouseleave(function(){
  4656. ($(this).hasClass('currency-container')?$('>span:nth-child(2)',this):$(this)).hide().prev().show();
  4657. });
  4658. elements=null;
  4659. }
  4660. function UploadPlayersData(){
  4661. if($('#UploadPlayerData').length) return;
  4662.  
  4663. $('#own-offers').after(
  4664. `<div align="center">`+
  4665. ` <label style="color:#a5e4c6; font-weight:bold;">${GetText('UploadPlayersData')} : </label>`+
  4666. ` <input id="UploadPlayerData" type="file" accept="text/plain">`+
  4667. `</div>`
  4668. );
  4669. $('#UploadPlayerData').change(function(e){
  4670. let that = $(this),
  4671. file = this.files[0];
  4672. if(file.type == 'text/plain'){
  4673. let reader = new FileReader();
  4674. reader.onload = function(){
  4675. let PlayersData = JSON.parse(reader.result),
  4676. data = Tool.getVal('PlayersData');
  4677. data.BuyPlayers = PlayersData;
  4678. Tool.setVal('PlayersData',data);
  4679. that.parent().remove();
  4680. start(PlayersData);
  4681. };
  4682. reader.readAsText(file);
  4683. }
  4684. else Game.giveNotification(false, GetText('ChooseNotebook'));
  4685. });
  4686. }
  4687. },null,[
  4688. 'main',
  4689. function(){
  4690. //Sattığımız oyuncudan ne kadar kazanç sağladığımızı gösterebilmek için
  4691. if(typeof Tool.news.sellPlayer=='object'){ //{"title":"Assistent: Transfermarkt","control":"ausgehandelt","beforeName":"Spieler ","afterName":" hat"}
  4692. let sData=Tool.news.sellPlayer,
  4693. PlayersData = Tool.getVal('PlayersData'); //Structure: http://prntscr.com/uc2p4v
  4694. if(PlayersData){
  4695. GetMessagesByTitle(sData.title,(messages)=>{
  4696. if(typeof PlayersData.SellPlayers != 'object') PlayersData.SellPlayers = {};
  4697. let SellPlayers = PlayersData.SellPlayers;
  4698.  
  4699. let html,message,updated=0;
  4700. for(let i=0; i<messages.length ; i++){
  4701. message = messages[i]; // $ element
  4702. html = message.html().trim();
  4703.  
  4704. if(html.indexOf(sData.control)==-1) continue;
  4705.  
  4706. let start = html.indexOf(sData.beforeName)+sData.beforeName.length,
  4707. end = html.indexOf(sData.afterName,start),
  4708. a = message.find('a');
  4709.  
  4710. if(start==-1 || end==-1 || a.length==0) continue;
  4711. a = a.first();
  4712.  
  4713. let playerName = html.substring(start,end).trim(),
  4714. club = {
  4715. id : a.attr('clubid'),
  4716. name : a.text().trim()
  4717. };
  4718.  
  4719. message.html(html.substring(0,start)+`<font style="cursor:default;" color="#89f4ff">${playerName}</font>`+html.substring(end));
  4720.  
  4721. if(SellPlayers.hasOwnProperty(playerName)){
  4722. ShowLabels(message,SellPlayers[playerName].price,SellPlayers[playerName].purchase);
  4723. continue;
  4724. }
  4725.  
  4726. let AcceptedOffers = PlayersData.AcceptedOffers,
  4727. foundPlayers = [];
  4728. for(let playerId in AcceptedOffers){
  4729. let playerData = AcceptedOffers[playerId],
  4730. playerName_ = playerData.playerName;
  4731. if(playerName_.split(',').reverse().join(' ').trim() == playerName){
  4732. let offers = playerData.offers;
  4733. for(let clubId in offers){
  4734. if(clubId == club.id){
  4735. playerData.playerId = playerId;
  4736. playerData.clubId = clubId;
  4737. foundPlayers.push(playerData);
  4738. break;
  4739. }
  4740. }
  4741. }
  4742. }
  4743.  
  4744. if(foundPlayers.length != 1) continue;
  4745.  
  4746. let playerData = foundPlayers[0],
  4747. offer = playerData.offers[playerData.clubId];
  4748.  
  4749. SellPlayers[playerName] = {
  4750. playerName : playerData.playerName,
  4751. playerId : playerData.playerId,
  4752. clubId : playerData.clubId,
  4753. clubName : offer.clubName,
  4754. price : offer.price,
  4755. date : message.parents('tr').find('td.last-column').text().trim(),
  4756. purchase : !1
  4757. };
  4758. delete AcceptedOffers[playerData.playerId];
  4759. ++updated;
  4760.  
  4761. if(!Array.isArray(PlayersData.BuyPlayers)) PlayersData.BuyPlayers = [];
  4762. let BuyPlayers = PlayersData.BuyPlayers,
  4763. purchase=!1;
  4764.  
  4765. for(let i = 0 ; i < BuyPlayers.length ; i++){
  4766. if(BuyPlayers[i].playerId == playerData.playerId){
  4767. SellPlayers[playerName].purchase = purchase = BuyPlayers[i].price;
  4768. break;
  4769. }
  4770. }
  4771. ShowLabels(message,offer.price,purchase);
  4772. }
  4773. if(updated) Tool.setVal('PlayersData',PlayersData);
  4774.  
  4775. function ShowLabels(e,sale,purchase=!1){
  4776. let text = `<p style="text-align:center; font-weight:bold; margin-top:10px;">`;
  4777. if(purchase!=!1)
  4778. text+=`<label style="color:#a11717; font-family:'comic sans'; font-size:15px;">${GetText('PurchasePrice')}: ${parseInt(purchase).toLocaleString()}<span class="icon currency"></span></label>`;
  4779. if(sale)
  4780. text+=`<label style="color:blue; font-family:'comic sans\; font-size:15px; margin:0 15px;">${GetText('SalePrice')}: ${parseInt(sale).toLocaleString()}<span class="icon currency"></span></label>`;
  4781. if(purchase!=!1){
  4782. let profit = parseInt(sale)-parseInt(purchase);
  4783. text+=`<label style="color:${profit>0?'green':(profit<0?'#9d2527; font-weight:bold':'white')}; font-family:'comic sans'; font-size: 15px;">${GetText('Profit')}: ${profit.toLocaleString()}<span class="icon currency"></span></label>`;
  4784. }
  4785. text+=`</p>`;
  4786. $(e).append(text)
  4787. .find('>p:last>label:not(:last)').css('margin-right', '10px')
  4788. }
  4789. });
  4790. }
  4791. }
  4792. }
  4793. ]);
  4794. Tool.features.add('ShowOwnOfferInMarket','transfermarket',function(){
  4795. let players = $('#content > div.container.transfermarket > div.table-container > table > tbody');
  4796. if(!players.find('.open-card').length) return false;
  4797.  
  4798. let OwnOffers = {};
  4799. if($('#own-offers> tbody').find('.open-card').length){
  4800. $('#own-offers> tbody > tr').each(function(){
  4801. let OCard = $(this).find('.open-card'),
  4802. playerId = OCard.attr('pid').split('-')[1],
  4803. price = parseInt($(this).find('td:nth-child(8)').attr('sortvalue')),
  4804. bidStatus = $(this).find('td:nth-child(7)').text().trim().toLowerCase();
  4805. OwnOffers[playerId]= {
  4806. price : price,
  4807. bidStatus : bidStatus
  4808. };
  4809. });
  4810. }
  4811.  
  4812. players = players.find('tr');
  4813. players.each(function(i){
  4814. let playerId = $(this).find('.open-card').attr('pid').split('-')[1];
  4815. if(OwnOffers[playerId]){
  4816. let club = $(this).find('td:nth-child(8) > a'),
  4817. bidStatus = OwnOffers[playerId].bidStatus,
  4818. color,
  4819. title = '';
  4820. switch(bidStatus){
  4821. case Tool.bidTexts.accept.toLowerCase():
  4822. color = '#20ff63';
  4823. title = GetText('AcceptedOwnOffer', {tag:0});
  4824. break;
  4825. case Tool.bidTexts.reject.toLowerCase():
  4826. color = '#9e0e0e';
  4827. title = GetText('RejectedOwnOffer', {tag:0});
  4828. break;
  4829. case Tool.bidTexts.read.toLowerCase():
  4830. color = '#fcbd0f';
  4831. title = GetText('ReadOwnOffer', {tag:0});
  4832. break;
  4833. default: // Tool.bidTexts.new
  4834. color = '#ffffff82';
  4835. title = GetText('NewOwnOffer', {tag:0});
  4836. break;
  4837. }
  4838. var playerName = $(this).find('.player-name:first');
  4839. if(club.length){
  4840. if(club.hasClass('self-link')){
  4841. $(this).find('.currency-number').first().css('color',color);
  4842. }
  4843. else if(bidStatus != Tool.bidTexts.reject){
  4844. //Bu oyuncuya verdiğimiz geçilmiş fakat bizim teklifimiz reddedilmemiş ise
  4845. var price = OwnOffers[playerId].price;
  4846. showMyOffer(playerName,$(this).find('.currency-number:first'),club,price,color);
  4847. title += '\u000d'+GetText('PassedOwnOffer', {tag:0});
  4848. }
  4849. }
  4850. playerName[0].style = `background-color:${color}; border-radius:7px; padding:1px 3px;`;
  4851. playerName[0].title = title;
  4852. goToMyOffer(playerName,playerId);
  4853. }
  4854. });
  4855. function goToMyOffer(playerName,playerId){
  4856. let _playerId;
  4857. playerName.click(function(){
  4858. $('#own-offers > tbody > tr').each(function(){
  4859. _playerId = $(this).find('.open-card').attr('pid').split('-')[1];
  4860. if(_playerId == playerId){
  4861. $('html, body').animate({ scrollTop: GetOffset(this).top-$(window).height()/2 }, 'fast');
  4862. this.style = `background-color:#fff2ac; background-image:linear-gradient(to right, #ffe359 0%, #fff2ac 100%);`;
  4863. let tr = this;
  4864. setTimeout(function(){
  4865. tr.style = '';
  4866. },2000);
  4867. return;
  4868. }
  4869. });
  4870. });
  4871. }
  4872. function showMyOffer(e1,e2,club,price,color){
  4873. let temp = {
  4874. price : e2.html(),
  4875. clubId : club.attr('clubid'),
  4876. clubName : club.text().trim()
  4877. };
  4878. e1.add(e2).mouseenter(function(){
  4879. e2.html(`<font color:"${color}">${price.toLocaleString()}</font>`);
  4880. club.attr('clubid',Tool.clubId);
  4881. club.addClass('self-link');
  4882. club.text(Tool.clubName);
  4883. });
  4884. e1.add(e2).mouseleave(function(){
  4885. e2.html(temp.price);
  4886. club.attr('clubid',temp.clubId);
  4887. club.removeClass('self-link');
  4888. club.text(temp.clubName);
  4889. });
  4890. }
  4891. },null);
  4892. Tool.features.add('FilterOwnOffers','transfermarket',function(){
  4893. if(!$('#own-offers > tbody').find('.open-card').length) return false;
  4894.  
  4895. $('#own-offers').parent().before(
  4896. `<div id="divFilterOwnOffers" style="text-align:center;">`+
  4897. ` <label style="color:white; font-size:13px;" title="${new Date(Game.getTime()).toLocaleDateString()}">`+
  4898. ` <input type="checkbox">`+
  4899. ` `+GetText('TodayOffers')+
  4900. ` </label>`+
  4901. ` <label style="color:white; font-size:13px;">`+
  4902. ` <input type="checkbox" style="margin-Left:20px;" checked>`+
  4903. ` `+GetText('AcceptedOffers')+
  4904. ` </label>`+
  4905. ` <label style="color:white; font-size:13px;">`+
  4906. ` <input type="checkbox" style="margin-Left:20px;" checked>`+
  4907. ` `+GetText('ReadingOffers')+
  4908. ` </label>`+
  4909. ` <label style="color:white; font-size:13px;">`+
  4910. ` <input type="checkbox" style="margin-Left:20px;" checked>`+
  4911. ` `+GetText('RejectedOffers')+
  4912. ` </label>`+
  4913. ` <label style="color:white; font-size:13px;">`+
  4914. ` <input type="checkbox" style="margin-Left:20px;" checked>`+
  4915. ` `+GetText('NewOffers')+
  4916. ` </label>`+
  4917. `</div>`
  4918. );
  4919. $('#divFilterOwnOffers > label > input').click(function(){
  4920. $('#divFilterOwnOffers > input').attr('disabled',true);
  4921. let filter = {},
  4922. today = new Date(Game.getTime()).toLocaleDateString();
  4923. $('#divFilterOwnOffers > label > input').each(function(i){
  4924. filter[$(this).next().attr('k')]=this.checked;
  4925. });
  4926. let count = 0;
  4927. $('#own-offers > tbody > tr').each(function(){
  4928. let bidStatus = $(this).find('td:nth-child(7)').text().trim().toLowerCase(),
  4929. date = $(this).find('td:nth-child(9)').text().trim(),
  4930. show =
  4931. (filter.AcceptedOffers && bidStatus==Tool.bidTexts.accept.toLowerCase()) ||
  4932. (filter.ReadingOffers && bidStatus==Tool.bidTexts.read.toLowerCase()) ||
  4933. (filter.RejectedOffers && bidStatus==Tool.bidTexts.reject.toLowerCase()) ||
  4934. (filter.NewOffers && bidStatus==Tool.bidTexts.new.toLowerCase());
  4935. show = show && filter.TodayOffers?date.indexOf(today)!=-1:show;
  4936. if(show){
  4937. $(this).attr('class',(count++)%2==0?"odd":"even");
  4938. $(this).show();
  4939. }
  4940. else $(this).hide();
  4941. });
  4942. $('#divFilterOwnOffers > input').removeAttr('disabled');
  4943. });
  4944. },null);
  4945. Tool.features.add('FilterTransferMarket','transfermarket',function(){
  4946. if(!$('#content > div.container.transfermarket > div.table-container > table > tbody').find('.open-card').length || $('#club').val()==Tool.clubName) return false;
  4947.  
  4948. if(!Tool.hasOwnProperty('transferMarket')){
  4949. Tool.transferMarket = {
  4950. clubs: {},
  4951. values: {"ligaIndex":0,"checkBox":false}
  4952. };
  4953. }
  4954.  
  4955. let players = $('#content > div.container.transfermarket > div.table-container > table > tbody > tr'),
  4956. count = 0;
  4957.  
  4958. $('#content').find('.search-container').first().after(
  4959. `<div id="transferMarktMenu" style="clear:both; margin-left:18px; position:relative;">`+
  4960. ` ${GetText('ShowOnlyOneLeague')} : `+
  4961. ` <select id="select_lig" style="-webkit-border-radius:7px; margin-Left:10px; text-align-last:center;">`+
  4962. ` <option value="0" selected="selected">${GetText('SelectLeague')}:</option>`+
  4963. ` ${Tool.leagues.reduce((acc,league,idx)=>acc+`<option value="${idx+1}">${league}</option>`,'')}`+
  4964. ` </select>`+
  4965. ` <label style="display:none; vertical-align:middle;">`+
  4966. ` <input id="only_one_lig" type="checkBox" style="margin-Left:10px;"></input>`+
  4967. ` <label for="only_one_lig">${GetText('ShowOnlyOneLeague')}</label>`+
  4968. ` </label>`+
  4969. ` <p ${$('#positions').val()==0?'':`style="display:none;"`}>`+
  4970. ` <input id="NoKeeperPlayers" type="checkBox" style="margin-left:0;">`+
  4971. ` <label for="NoKeeperPlayers">${GetText('AllExceptGoalkeeper')}</label>`+
  4972. ` </p>`+
  4973. `</div>`
  4974. );
  4975.  
  4976. let myLeague = (Tool.getVal('LeagueData',{league:false})).league;
  4977. if(myLeague){
  4978. let options = $('#select_lig > option');
  4979. options.each(function(i){
  4980. if($(this).text().toLowerCase()==myLeague.toLowerCase()){
  4981. $(this).attr({'title': GetText('ownLeague', {tag:0}), 'tool_tt':"ownLeague"}).css({
  4982. 'background-color':'#8c0505',
  4983. 'color':'white'
  4984. });
  4985. for(let j=i-3;j>0;j--) $(options[j]).attr('title', GetText('lowerLeague', {tag:0})+'. '+GetText('playerBuyInfo1', {tag:0})).css('background-color','yellow');
  4986. for(let j=i-1,c=0;j>0&&c<2;j--,c++) $(options[j]).attr({'title': GetText('lowerLeague', {tag:0}), 'tool_tt':'lowerLeague'}).css('background-color','orange');
  4987. let len = $('#select_lig > option').length;
  4988. for(let j=i+1,c=0;j<=len&&c<2;j++,c++) $(options[j]).attr({'title': GetText('upperLeague', {tag:0}), 'tool_tt':'upperLeague'}).css('background-color','#17fc17');
  4989. for(let j=i+3;j<=len;j++) $(options[j]).attr('title', GetText('upperLeague', {tag:0})+'. '+GetText('playerBuyInfo2', {tag:0})).css('color','#808080').prop('disabled',true);
  4990. return false;
  4991. }
  4992. });
  4993. }
  4994.  
  4995. $('#content > div.container.transfermarket > div.table-container > h3').after(
  4996. `<p id="filterPlayerInformation" style="background-color:black; color:white; line-height:33px; text-align:center;"></p>`
  4997. );
  4998.  
  4999. unsafeWindow.$('#positions').change(function(){
  5000. $('#NoKeeperPlayers').parent()[this.value=='0'?'slideDown':'slideUp']();
  5001. });
  5002. $('#NoKeeperPlayers').click(function(){
  5003. Tool.transferMarket.values.NoKeeperPlayers = this.checked;
  5004. if(this.checked && $('#positions').val()==0){
  5005. players.each(function(){
  5006. if($(this).css('display')!=='none'){
  5007. if(this.getElementsByTagName('td')[2].innerHTML === Tool.footballerPositions[0]){
  5008. $(this).hide();
  5009. }
  5010. }
  5011. });
  5012. }
  5013. else{
  5014. if($('#only_one_lig')[0].checked){
  5015. var lig = $('#select_lig')[0].options[$('#select_lig')[0].selectedIndex].textContent.trim();
  5016. players.each(function(){
  5017. var clubId = this.getElementsByClassName('name-column')[1].getElementsByTagName('a')[0].getAttribute('clubid');
  5018. if(Tool.transferMarket.clubs[clubId].indexOf(lig)!==-1){
  5019. $(this).show();
  5020. }
  5021. });
  5022. }
  5023. else{
  5024. players.each(function(){
  5025. $(this).show();
  5026. });
  5027. }
  5028. }
  5029. showFilterInfo();
  5030. });
  5031. $('#select_lig').change(function(){
  5032. Tool.transferMarket.values.ligaIndex= this.selectedIndex;
  5033. if(this.value==0){
  5034. $('#only_one_lig').parent().slideUp();
  5035. $('#only_one_lig')[0].checked = false;
  5036. Tool.transferMarket.values.checkBox = false;
  5037. players.each(function(i){
  5038. this.className = i%2===0?"odd":"even";
  5039. $(this).show();
  5040. });
  5041. }
  5042. else{
  5043. $('#only_one_lig').parent().slideDown();
  5044. if($('#only_one_lig')[0].checked){
  5045. tablo_oku();
  5046. }
  5047. }
  5048. });
  5049. $('#only_one_lig').click(function(){
  5050. Tool.transferMarket.values.checkBox = this.checked;
  5051. if(this.checked){
  5052. tablo_oku();
  5053. }
  5054. else{
  5055. if($('#NoKeeperPlayers')[0].checked){
  5056. var c = 0;
  5057. players.each(function(i){
  5058. if(this.getElementsByTagName('td')[2].innerHTML !== Tool.footballerPositions[0]){
  5059. this.className = c%2===0?"odd":"even";
  5060. this.style.display='';
  5061. c++;
  5062. }
  5063. });
  5064. }
  5065. else{
  5066. players.each(function(i){
  5067. this.className = i%2===0?"odd":"even";
  5068. $(this).show();
  5069. });
  5070. }
  5071. showFilterInfo();
  5072. }
  5073. });
  5074. if(Tool.transferMarket.values.NoKeeperPlayers){
  5075. if($('#positions').val()=='0')
  5076. $('#NoKeeperPlayers').click();
  5077. else{
  5078. Tool.transferMarket.values.NoKeeperPlayers = !1;
  5079. $('#NoKeeperPlayers')[0].checked = !1;
  5080. }
  5081. }
  5082. if(Tool.transferMarket.values.ligaIndex!==0){
  5083. document.getElementById('select_lig').selectedIndex = Tool.transferMarket.values.ligaIndex;
  5084. $('#only_one_lig').parent().show();
  5085. if(Tool.transferMarket.values.checkBox){
  5086. $('#only_one_lig')[0].checked=true;
  5087. tablo_oku();
  5088. }
  5089. }
  5090.  
  5091. function tablo_oku(){
  5092. $('#select_lig, #only_one_lig, #NoKeeperPlayers').prop('disabled', true);
  5093. $('#only_one_lig').parent().hide()
  5094. .parent().after(`<img id="LoadingTable" src="/designs/redesign/images/icons/loading/16x16.gif" style="margin-left:10px; vertical-align:middle;">`);
  5095. count = 0;
  5096. players.each(function(){
  5097. var clubId = this.getElementsByClassName('name-column')[1].getElementsByTagName('a')[0].getAttribute('clubid');
  5098. if(!Tool.transferMarket.clubs[clubId]){
  5099. count++;
  5100. kulüp_bilgileri_cek(clubId);
  5101. }
  5102. });
  5103. if(count==0){
  5104. tablo_göster();
  5105. }
  5106. }
  5107. function kulüp_bilgileri_cek(clubId){
  5108. $.get(`index.php?w=${worldId}&area=user&module=club&action=index&complex=0&id=${clubId}`, function(response){
  5109. var a = $('<diV>'+response+'</div>').find('ul > li:first');
  5110. a.find('strong').remove();
  5111. var leuage = a.text().trim();
  5112. Tool.transferMarket.clubs[clubId] = leuage;
  5113. count--;
  5114. if(count===0){
  5115. tablo_göster();
  5116. }
  5117. });
  5118. }
  5119. function tablo_göster(){
  5120. var kl_gösterme = Tool.transferMarket.values.NoKeeperPlayers && $('#positions').val()=="0"?true:false;
  5121. var görüntülenecek_lig = document.getElementById('select_lig').options[document.getElementById('select_lig').selectedIndex].textContent;
  5122. players.each(function(i){
  5123. var clubId = this.getElementsByClassName('name-column')[1].getElementsByTagName('a')[0].getAttribute('clubid');
  5124. var mevki = this.getElementsByTagName('td')[2].innerHTML;
  5125. if(Tool.transferMarket.clubs[clubId].indexOf(görüntülenecek_lig)!==-1 && !(kl_gösterme && mevki===Tool.footballerPositions[0])){
  5126. this.className = i%2==0?"odd":"even";
  5127. $(this).show();
  5128. }
  5129. else{
  5130. $(this).hide();
  5131. }
  5132. });
  5133. $('#select_lig, #only_one_lig, #NoKeeperPlayers').prop('disabled', false);
  5134. $('#LoadingTable').remove();
  5135. $('#only_one_lig').parent().show();
  5136. showFilterInfo();
  5137. }
  5138. function showFilterInfo(){
  5139. var show = 0;
  5140. players.each(function(){
  5141. if($(this).css('display')!=='none'){
  5142. show++;
  5143. }
  5144. });
  5145. if(players.length !== show){
  5146. $('#filterPlayerInformation').html(GetText('FilterPlayerInformation', {args:[players.length, show]}));
  5147. }
  5148. else{
  5149. $('#filterPlayerInformation').html('');
  5150. }
  5151. }
  5152. },null);
  5153. Tool.features.add('DownloadTable',['league','statistics','squadstrenght','goalgetter'],function(){
  5154. let element = {'league':'statistics-league-table' ,'statistics':'season-league-table', 'squadstrenght':'squad-strengths', 'goalgetter':'goalgetters'}[Game.currentPage.name];
  5155. if(element==null || (element=$('#'+element)).length==0) return false;
  5156.  
  5157. if(!$('#html2canvas').length)
  5158. $('head').append(`<script id="html2canvas" type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js">`);
  5159.  
  5160. $(`<img src="${Tool.sources.getLink('https://www.pinclipart.com/picdir/big/494-4943705_camera-symbol-png-video-camera-icon-gif-clipart.png')}" alt="printscreen" height="20px" style="cursor:pointer;" title="${GetText('DownloadTable', {tag:0})}" tool_tt="DownloadTable">`)
  5161. .appendTo(element.find('> tfoot > tr > td')).mouseenter(function(){
  5162. element.find('>tbody:first,>thead:first').addClass('animate-flicker');
  5163. }).mouseleave(function(){
  5164. element.find('>tbody:first,>thead:first').removeClass('animate-flicker');
  5165. }).click(function(){
  5166. $(this).hide().after(`<span class="load-icon loading" style="float:none; margin:0 auto;"></span>`);
  5167. element.css('background', '#6e9a5a url(/designs/redesign/images/layout/box_bg.gif) 0 -200px repeat-x')
  5168. .find('>tbody:first,>thead:first').removeClass('animate-flicker').css('opacity',1);
  5169. let that = $(this);
  5170. html2canvas( //eslint-disable-line no-undef
  5171. element[0],{
  5172. x: element.offset().left,
  5173. y: element.offset().top,
  5174. height: element.height()-element.find('>tfoot:first').height()
  5175. }
  5176. ).then(function(canvas) {
  5177. let fileName = {'league':'LeagueTable' ,'statistics':'MatchResultsTable', 'squadstrenght':'SquadStrengthTable', 'goalgetter':'GoalScorerTable'}[Game.currentPage.name];
  5178. if(typeof fileName=='string') fileName= GetText(fileName, {tag:0});
  5179. switch(Game.currentPage.name){
  5180. }
  5181. canvas.toBlob(function(blob){
  5182. let object_URL = URL.createObjectURL(blob);
  5183. $('<a>').attr({'href':object_URL, 'download':(fileName||'screenshot')+'.png'})[0].click();
  5184. URL.revokeObjectURL(object_URL);
  5185. },'image/png');
  5186. that.show().next().remove();
  5187. });
  5188. });
  5189. },null);
  5190. Tool.features.add('CancelFriendlyMatchInvites','friendly',function(){
  5191. if($('#away-invitations-table > tbody .no-invites').length) return false;
  5192. let invites = $('#away-invitations-table > tbody > tr');
  5193. if(invites.length>1){
  5194. $('#away-invitations-table > thead > tr > th:last').append(
  5195. `<input id="SelectAllInvites" type="checkbox" class="checkbox_1">`+
  5196. `<label for="SelectAllInvites" title="${GetText('selectAll', {tag:0})}" tool_tt="selectAll" style="line-height:20px; float:right; margin-top:2.5px;"></label>`
  5197. );
  5198. $('#SelectAllInvites').click(function(){
  5199. $('#away-invitations-table > tbody .CancelInvite'+(this.checked?':not(:checked)':':checked')).prop('checked',this.checked);
  5200. $('#CancelInvites')[this.checked?'slideDown':'slideUp']();
  5201. });
  5202. }
  5203. $('#away-invitations-table > tbody > tr').each(function(i){
  5204. let a = $('.icon.delete',$(this)).parent(),
  5205. decline = a.attr('href'),
  5206. find = decline.indexOf('&decline=')+9;
  5207. decline = decline.substring(find,decline.indexOf('&',find));
  5208. a.after(
  5209. `<input id="Cancel_invite_${i}" class="CancelInvite checkbox_2" style="vertical-align:middle; margin:0;" type="checkbox" decline="${decline}">`+
  5210. `<label for="Cancel_invite_${i}" class="disHighlight" style="cursor:pointer;"></label>`
  5211. );
  5212. a.remove();
  5213. });
  5214. let prev_index=undefined;
  5215. $('.CancelInvite').click(function(e){
  5216. let index = $(this).parents('tr').index();
  5217. if(e.shiftKey && prev_index!=undefined){
  5218. $('#away-invitations-table > tbody > tr').slice(Math.min(prev_index,index),Math.max(prev_index,index)+1).find('.CancelInvite').prop('checked',this.checked);
  5219. }
  5220. prev_index = index;
  5221. $('#CancelInvites')[$('#away-invitations-table > tbody .CancelInvite:checked').length?'slideDown':'slideUp']();
  5222. if(!this.checked && $('#SelectAllInvites').prop('checked')) $('#SelectAllInvites').prop('checked',false);
  5223. else if(
  5224. this.checked
  5225. && !$('#SelectAllInvites').prop('checked')
  5226. && !$('#away-invitations-table > tbody .CancelInvite:not(:checked)').length
  5227. ) $('#SelectAllInvites').prop('checked',true);
  5228. });
  5229. $('#away-invitations-table > tfoot > tr > td').append(CreateButton('CancelInvites', GetText('CancelSelectedInvites'), 'display:none; float:right;'));
  5230. $('#CancelInvites').click(function(){
  5231. let checked;
  5232. if(!(checked = $('#away-invitations-table > tbody .CancelInvite:checked')).length) return;
  5233. let links = [];
  5234. checked.each(function(){
  5235. links.push({tr:$(this).parents('tr'),decline:$(this).attr('decline')});
  5236. });
  5237. let invites_length=links.length,
  5238. counter=0;
  5239. for(let i=0;i<invites_length;i++){
  5240. CancelInvite(links[i]);
  5241. }
  5242. let control_time=0;
  5243. function CancelInvite(obj,err=0){
  5244. let success;
  5245. // index.php?w=3401&area=user&module=friendly&action=index&decline=668249_1550581200
  5246. $.get(`index.php?w=${worldId}&area=user&module=friendly&action=index&decline=${obj.decline}&layout=none`, function(response){
  5247. //Veri alımı başarılı oldu.
  5248. let feedback;
  5249. if(!(feedback=response.feedback).trim() //feedback yoksa
  5250. || !(feedback = $(feedback)).length //tag bulunamadıysa
  5251. || (feedback=feedback)[0].tagName!='P' //doğru tak değilse
  5252. || !feedback.hasClass('notice') //bildirim başarılı değilse
  5253. ){
  5254. console.log("feedback isn't exist || length=0 || tagname!='P'");
  5255. success=!1;
  5256. err = 3;
  5257. return;
  5258. }
  5259. else{
  5260. success=!0;
  5261. console.log("Canceling invite ["+obj.decline+"] is successfull!");
  5262. }
  5263. }).fail(function(){
  5264. //Veri alımı başarısız oldu. 3 Kere veri alımını tekrar dene. Eğer 2 kez daha başarısız olursa işlemi sonlandır.
  5265. if(++err<3) CancelInvite(obj,err);
  5266. }).always(function(){
  5267. if(success //Veri alımı başarılı
  5268. || err==3 //veya 3 kere denenmesine rağmen veri alınamadı!
  5269. ){
  5270. counter++;
  5271. let tr = obj.tr;
  5272. if(success){
  5273. tr.fadeOut(1000,()=>{
  5274. tr.remove();
  5275. });
  5276. control_time=new Date().getTime()+1000; // 1000 salise sonra satır silinecek.Eğer o esnada finish fonksiyonu çalışırsa..
  5277. }else{
  5278. tr.find('.CancelInvite').prop('checked',false);
  5279. BlinkEvent(tr,1000);
  5280. }
  5281. if(counter==invites_length)
  5282. setTimeout(finish,control_time-new Date().getTime());
  5283. }
  5284. });
  5285. }
  5286. function finish(){
  5287. if(!$('#away-invitations-table > tbody > tr').length){
  5288. $('#away-invitations-table > tbody').append(`<tr class="odd"> <td class="no-invites last-column" colspan="4"> - </td> </tr>`);
  5289. $('#SelectAllInvites').parent().find('label[for=SelectAllInvites]').remove();
  5290. $('#SelectAllInvites').remove();
  5291. $('#CancelInvites').remove();
  5292. }
  5293. }
  5294. });
  5295. },null);
  5296. Tool.features.add('QuickBet','betoffice',function(){
  5297. var t = $('#betoffice-container').find('.matches').find('tbody');
  5298. if(t.find('.club-logo-container').length){
  5299. t.find('tr').each(function(){
  5300. if($(this).find('.last-column').find('select').length){
  5301. var k = this.getElementsByClassName('bet-quote');
  5302. for(var j = 0 ; j < k.length ; j++){
  5303. var radio = k[j].getElementsByTagName('span')[0];
  5304. $(radio).click(function(){
  5305. var e = $(this).parents('tr').find('select')[0];
  5306. var q = $(this).parents('tr').find('.last-column > span > div > span')[0];
  5307. if(!$(this).hasClass('checked')){
  5308. e.selectedIndex = e.options.length-1;
  5309. q.innerHTML = e.options[e.selectedIndex].innerHTML;
  5310. }
  5311. else{
  5312. e.selectedIndex = 0;
  5313. q.innerHTML=0;
  5314. }
  5315. });
  5316. }
  5317. }
  5318. });
  5319. }
  5320. },null);
  5321. Tool.features.add('ShowAsistantLevelIncrease','assistants',function(){
  5322. var key = 'AsistanLevel';
  5323. var data = Tool.getVal(key,{});
  5324. var o = [];
  5325. $('#assistants').find('.bar-text').each(function(){
  5326. var level = this.textContent.trim();
  5327. var b = level.indexOf(' ');
  5328. level = level.substring(b,level.indexOf(' ',b+1));
  5329. var value = parseInt($(this).prev().find('div')[0].style.width.replace('%',''));
  5330. var asistant = $($(this).parents('li')[1]).index();
  5331. var asistantName = $(this).parents('ul').first().find('li:first > span').text();
  5332. if(data[asistant]!==undefined){
  5333. if(data[asistant].name == asistantName){
  5334. var difference = value - data[asistant].v;
  5335. if(difference>0){
  5336. var asistantType = $(this).parents('li').find('h3').text().trim();
  5337. o.push({asistantType:asistantType,asistantName:asistantName,difference:difference});
  5338. }
  5339. }
  5340. }
  5341. data[asistant] = {name:asistantName,v:(level*100+value)};
  5342. });
  5343. if(o.length){
  5344. var text = GetText('SeminarIsOver')+'<br>';
  5345. for(var i = 0 ; i < o.length-1 ; i++){
  5346. text += o[i].asistantName+`[${o[i].asistantType}] : +${o[i].difference}%<br>`;
  5347. }
  5348. text += o[o.length-1].asistantName+`[${o[o.length-1].asistantType}] : +${o[o.length-1].difference}`;
  5349. Game.giveNotification(true, text);
  5350. }
  5351. Tool.setVal(key,data);
  5352. },null);
  5353. Tool.features.add('QuickShopping','shop',function(){
  5354. $('#shop-content > .shop').each(function(){
  5355. let shop = this;
  5356. if($(shop).find('.shadow').length) return;
  5357.  
  5358. let e = $('div.table-container',shop)[0].getElementsByClassName('multi');
  5359. for(let i=0,len=e.length ; i<len ; i++){
  5360. let k = e[i].getElementsByTagName('tbody')[0].getElementsByTagName('tr');
  5361. for(var j = 0 ; j<k.length ; j++){
  5362. let t = k[j].getElementsByClassName('last-column order-quantity')[0];
  5363. if(t!==undefined && t.getElementsByClassName('input-container')[0]!==undefined){
  5364. let tk = t.innerHTML,
  5365. b = tk.indexOf('</span> / ')+7,
  5366. b1 = tk.indexOf('<span',b),
  5367. mi = tk.substring(b+3,b1).trim();
  5368. t.innerHTML = tk.substring(0,b)+`<span class="TrOk disHighlight" style="cursor:pointer;"> / ${mi}</span>`+tk.substring(b1);
  5369. ClickTrOk(t.getElementsByClassName('TrOk')[0]);
  5370. }
  5371. }
  5372. }
  5373. $('div.button-container > span.button.button-container-disabled.premium > a > span', shop)
  5374. .attr('k',1)
  5375. .removeAttr('class tooltip name')
  5376. .css('cursor','pointer')
  5377. .html(GetText('FillAll'))
  5378. .click(function(){
  5379. let k = shop.getElementsByClassName('TrOk');
  5380. if($(this).attr('k')==1){
  5381. for(let i = 0 ; i < k.length ; i++)
  5382. k[i].previousSibling.getElementsByTagName('input')[0].value = k[i].textContent.replace('/','').trim();
  5383. $(this).html(GetText('EmptyAll')).attr('k',0);
  5384. }
  5385. else{
  5386. for(let i = 0 ; i < k.length ; i++)
  5387. k[i].previousSibling.getElementsByTagName('input')[0].value = 0;
  5388. $(this).html(GetText('FillAll')).attr('k',0);
  5389. }
  5390. })
  5391. .parent().removeAttr('href');
  5392. $('div.button-container > span:nth-child(3) > a > span', shop).html(GetText('Ordering'));
  5393. });
  5394. function ClickTrOk(e){
  5395. $(e).click(function(){
  5396. let va = e.textContent.replace('/','').trim(),
  5397. t = e.previousSibling.getElementsByTagName('input')[0];
  5398. if(e.previousSibling.getElementsByTagName('input')[0].value!==va) t.value = va;
  5399. else t.value=0;
  5400. });
  5401. }
  5402. },null);
  5403. Tool.features.add('AddImage',['press->article','club_profile'],function(){
  5404. let elements = {
  5405. 'article': { /*press->article*/
  5406. toolbar : $('#Toolbar_designArea > ul'),
  5407. textarea: $('#designArea')[0]
  5408. },
  5409. 'club_profile' : {
  5410. toolbar : $('#Toolbar_profile-edit-club-information > ul'),
  5411. textarea: $('#profile-edit-club-information')[0]
  5412. }
  5413. }[Game.currentPage.name];
  5414. $(`<li class="" title="${GetText('AddImage', {tag:0})}" tool_tt="AddImage" style="cursor:pointer;" onmouseenter="$(this).addClass('hover')" onmouseleave="$(this).removeClass('hover')">`+
  5415. ` <img src="${Tool.sources.getLink('https://icon-library.com/images/photo-gallery-icon/photo-gallery-icon-12.jpg')}" alt="image" width="20px" height="20px">`+
  5416. `</li>`
  5417. ).appendTo(elements.toolbar).click(function(){
  5418. let txt = prompt(GetText('EnterImageLink', {tag:0}) + ' :', "");
  5419. if (!txt || !(txt=txt.trim())) return;
  5420. let intStart = elements.textarea.selectionStart,
  5421. img = new Image();
  5422. img.onload = function() {
  5423. let a = elements.textarea;
  5424. txt = `[color=rgb(255, 255, 255);background-image: url(${txt});width:${this.width}px;height:${this.height}px;display:block;overflow:visible;margin:0 auto;][/color]`;
  5425. a.value = String(a.value).substring(0, intStart) + txt + String(a.value).substring(a.selectionEnd);
  5426. a.selectionStart = intStart;
  5427. a.selectionEnd = intStart+txt.length;
  5428. a.focus();
  5429. };
  5430. img.src = txt;
  5431. });
  5432. },null);
  5433. Tool.features.add('InviteSimulationMatch','manager',function(){
  5434. if(isNaN(Game.link.pr.clubId) || Game.link.pr.clubId==Tool.clubId) return;
  5435. let matchId = (new URL(location.origin+'/'+$('#profile-show').find('.button-container-friendly-invite-button > a').attr('href').replace('#/',''))).searchParams.get('invite');
  5436. if(matchId == null) return false;
  5437. $('#profile-show').find('.profile-actions').first().append(
  5438. `<a class='button' href='#/index.php?w=${worldId}&area=user&module=simulation&action=index&squad=${matchId}'>`+
  5439. ` <span>${GetText('InviteSimulation')}</span>`+
  5440. `</a>`
  5441. );
  5442. },null);
  5443. Tool.features.add('ShowEloRating','manager',function(){
  5444. $('#profile-show > div.container.profile-trophy > div.profile > ul.profile-box-club').append(
  5445. `<li><strong>${GetText('EloRank')} : </strong> <span id="SpanEloRating" class="icon details loading"></span></li>`
  5446. );
  5447. let clubName = $('#profile-show > h2:nth-child(1)').text().replace(Tool.replaceClubName,'').trim();
  5448. Game.getPage(`index.php?club=${clubName}&_qf__form=&module=rating&action=index&area=user&league=&path=index.php&layout=none`, null, null, 0, ['content'])
  5449. .then(data=>{
  5450. let odds = $('<div>').html(data.content).find('.odd');
  5451. $('#SpanEloRating').attr('class','');
  5452. if(odds.length) $('#SpanEloRating').html(odds.first().find('>td')[0].textContent);
  5453. else $('#SpanEloRating').css('color','gray').html('-');
  5454. })
  5455. .catch(err=>{
  5456. console.error(err);
  5457. $('#SpanEloRating').html(`<font color="#751b1b">${GetText('error')}</font>`);
  5458. });
  5459. },null);
  5460. Tool.features.add('LiveMatchesTable','live->match',function(){
  5461. if(typeof currentLive!='object') return false;
  5462. if(Tool.goalTrigger!==3) return false;
  5463. if(!($('#'+currentLive.matchId).hasClass('league') && $('#match-observer').length)) return false;
  5464. //If the match is league match
  5465.  
  5466. let LiveLeagueTable = {
  5467. Initialize : async function(){
  5468. delete this.Initialize;
  5469. $('#match > div.match.ticker').css('height','765px');
  5470.  
  5471. if(!currentLive.hasOwnProperty('homeClubId')){
  5472. currentLive.homeClubId = $('#'+currentLive.matchId+' > div.home > span > h3 > a').attr('clubid');
  5473. currentLive.awayClubId = $('#'+currentLive.matchId+' > div.away > span > h3 > a').attr('clubid');
  5474. }
  5475.  
  5476. this.InsertHeaderForObserver();
  5477. this.InsertLeagueTable();
  5478. this.InsertHeaderForTable();
  5479. this.CreateAnimation();
  5480.  
  5481. let all_matches_ended = this.AllMatchesEnded(),
  5482. league_table_updated = all_matches_ended && await this.AreScoresUpdated(),
  5483. matches_not_started = !all_matches_ended && new Date(Game.getTime()).getMinutes()>29,
  5484. any_match_is_continue = !all_matches_ended && !matches_not_started;
  5485.  
  5486. console.log('%call_matches_ended: %o\n%cleague_table_updated: %o','color:red;font-weight:bold;',all_matches_ended,'color:red;font-weight:bold;',league_table_updated);
  5487. let result = await this.GetTable();
  5488. this.leagueIndex = result.leagueIndex;
  5489. this.tableRowClass = result.rowClass;
  5490.  
  5491. this.SetMatchIdForClub(result.table);
  5492. this.SetOppenentId(result.table);
  5493.  
  5494. // match hour is x
  5495. if(!league_table_updated){ // (x-1) <-> x:15
  5496. this.old_table = result.table;
  5497. if(!all_matches_ended){ //Before match time or in match hour(x): (x-1):30 <-> x:10
  5498. if(matches_not_started){ // (x-1):30 <-> x (from when matches appear until when matches start)
  5499. console.log('1.Area');
  5500. this.new_table = this.old_table;
  5501. this.UpdateLiveLeagueTable();
  5502.  
  5503. //await until matches start
  5504. await new Promise((res,rej)=>{
  5505. let d = new Date(Game.getTime()),
  5506. ms = (3600-(d.getMinutes()*60+d.getSeconds()))*1000-d.getMilliseconds();
  5507. console.log('Beklenecek milisaniye: ' + ms);
  5508. clearTimeout(unsafeWindow.timeout_1);
  5509. unsafeWindow.timeout_1=setTimeout(function(){
  5510. res();
  5511. delete unsafeWindow.timeout_1;
  5512. }, ms);
  5513. });
  5514. console.log('Mathces start now');
  5515.  
  5516. this.new_table = this.CreateTableWithScores(this.GetCurrentScores(), this.old_table);
  5517. //this.new_table.forEach(club=>{++club.played;});
  5518. }
  5519. else{ // x <-> x:10 (from when matches start until when all matches end)
  5520. this.new_table = this.CreateTableWithScores(this.GetCurrentScores(), this.old_table);
  5521. //this.new_table.forEach(club=>{++club.played;});
  5522. console.log('2.Area');
  5523. }
  5524. this.StartToCatchNewGoals();
  5525. this.StartToCatchMatchEnd();
  5526. }
  5527. else{ // x:10 <->x:15 (from when all matches end until league table updated)
  5528. this.new_table = this.CreateTableWithScores(this.GetCurrentScores(), this.old_table);
  5529. this.new_table.forEach(club=>{++club.played;});
  5530. console.log('3.Area');
  5531. }
  5532. }
  5533. else{ // x:15 <-> 24:00 (from when league table updated until when matches result disappear)
  5534. this.new_table = result.table;
  5535. this.old_table = this.CreateTableWithScores(this.GetCurrentScores(), this.new_table.slice(0), true);
  5536. this.old_table.forEach(club=>{--club.played;});
  5537. console.log('4.Area');
  5538. }
  5539.  
  5540. this.UpdateLiveLeagueTable();
  5541. },
  5542.  
  5543. InsertLeagueTable : function(){
  5544. delete this.InsertLeagueTable;
  5545.  
  5546. let table_height=450,
  5547. space_height=188;
  5548. $(`<div id="league-table" style="position:absolute; background:#6e9a5a url(images/layout/box_bg.gif) 0 -200px repeat-x; overflow:auto; box-shadow:1px 1px 5px black;">`+
  5549. ` <table class="table-league">`+
  5550. ` <thead>`+
  5551. ` <tr>`+
  5552. ` <th>${GetText('Rank')}</th>`+
  5553. ` <th>${GetText('Trend')}</th>`+
  5554. ` <th>${GetText('Club')}</th>`+
  5555. ` <th>${GetText('Played')}</th>`+
  5556. ` <th>${GetText('Won')}</th>`+
  5557. ` <th>${GetText('Drawn')}</th>`+
  5558. ` <th>${GetText('Lost')}</th>`+
  5559. ` <th title="${GetText('GoalFor', {tag:0})}" tool_tt="GoalFor">${GetText('SGoalFor')}</th>`+
  5560. ` <th title="${GetText('GoalAgainst',{tag:0})}" tool_tt="GoalAgainst">${GetText('SGoalAgainst')}</th>`+
  5561. ` <th>${GetText('Average')}</th>`+
  5562. ` <th>${GetText('Points')}</th>`+
  5563. ` </tr>`+
  5564. ` </thead>`+
  5565. ` <tbody></tbody>`+
  5566. ` </table>`+
  5567. `</div>`
  5568. ).css({
  5569. 'top' :(parseInt($('#match-observer').css('top'))+24)+'px',
  5570. 'left' :'0px',
  5571. 'width':'0',
  5572. 'height':table_height+'px'
  5573. }).insertAfter($('#match-observer')).find('table>thead th').css({position: 'sticky', top: '0','background-color':'black','border-bottom':'1px double white'});
  5574. $('#match > div.match').height($('#match > div.match').height()+table_height-space_height)
  5575. },
  5576. InsertHeaderForTable : function(){
  5577. delete this.InsertHeaderForTable;
  5578.  
  5579. $(`<p id="Toggle_league_table" class="disHighlight">${GetText('LiveLeagueTable')}</p>`).css({
  5580. "position" : "absolute",
  5581. "line-height" : "18px",
  5582. "cursor" : "pointer",
  5583. "text-align" : "center",
  5584. "color" : "black",
  5585. "font-weight" : "bold",
  5586. "font-size" : "15px",
  5587. "background-color" : "#d0cfcf",
  5588. "border-radius" : "0 10px 10px 0",
  5589. 'padding':'0 2px',
  5590. "writing-mode" : "vertical-lr",
  5591. "text-orientation" : "unset",
  5592. "top" : (parseInt($('#match-observer').css('top'))+24)+'px',
  5593. "left" : "0px",
  5594. "width" : "18px",
  5595. "height" : $('#league-table').height()+"px"
  5596. }).insertAfter($('#match-observer'));
  5597. },
  5598. InsertHeaderForObserver : function(){
  5599. delete this.InsertHeaderForObserver;
  5600.  
  5601. $(`<p id="Toggle_match_observer" k="close" animate_top="${$('#match-observer').height()}" class="disHighlight">${GetText('LiveMatchScores')}</p>`).css({
  5602. 'position' : 'absolute',
  5603. 'line-height' : '18px',
  5604. 'cursor' : 'pointer',
  5605. 'text-align' : 'center',
  5606. 'color' : 'black',
  5607. 'font-weight' : 'bold',
  5608. 'font-size' : '15px',
  5609. 'background-color' : '#d0cfcf',
  5610. 'border-radius' : '0 0 10px 10px',
  5611. 'padding':'2px 0',
  5612. 'top' : parseInt($('#match-observer').css('top'))+$('#match-observer').height(),
  5613. 'width' : $('#match-observer').width()+parseInt($('#match-observer').css('padding-right'))+parseInt($('#match-observer').css('padding-left'))-2,
  5614. 'left' : parseInt($('#match-observer').css('left'))+1
  5615. }).insertAfter($('#match-observer'));
  5616. },
  5617. CreateAnimation : function(){
  5618. delete this.CreateAnimation;
  5619.  
  5620. $('#Toggle_match_observer,#Toggle_league_table').click(function(){
  5621. let k = $('#Toggle_match_observer').attr('k'),
  5622. animate_left = $('#league-table>table').width() + ($('#league-table')[0].scrollHeight != $('#league-table')[0].offsetHeight?16.8:0),
  5623. animate_top = $('#Toggle_match_observer').attr('animate_top');
  5624. $('#Toggle_match_observer,#Toggle_league_table').css("pointer-events", "none");
  5625.  
  5626. if(k=='close'){
  5627. $('#Toggle_match_observer').animate({ "top":'-='+animate_top+"px" }, 500 );
  5628. $('#match-observer,#match-observer > ul').animate({
  5629. height : 0,
  5630. opacity: 0
  5631. }, 500);
  5632. setTimeout(function(){
  5633. $('#Toggle_match_observer').attr('k','open');
  5634. //Cookies.set('liveLeagueTable', 1, { expires: 365 });
  5635.  
  5636. $('#Toggle_league_table').animate({ "left": '+='+animate_left+"px" }, 500 );
  5637. $('#league-table').animate({
  5638. width : animate_left,
  5639. opacity: 1
  5640. }, 500);
  5641.  
  5642. setTimeout(function(){
  5643. $('#Toggle_match_observer,#Toggle_league_table').css("pointer-events", "auto");
  5644. },500);
  5645. },400);
  5646. }
  5647. else{
  5648. $('#Toggle_league_table').animate({ "left": '-='+animate_left+"px" }, 500 );
  5649. $('#league-table').animate({
  5650. width : 0,
  5651. opacity: 0
  5652. }, 500);
  5653.  
  5654. setTimeout(function(){
  5655. $('#Toggle_match_observer').attr('k','close');
  5656. //Cookies.set('liveLeagueTable', 0, { expires: 365 });
  5657. $('#match-observer,#match-observer > ul').animate({
  5658. height : animate_top,
  5659. opacity: "1"
  5660. }, 500);
  5661. $('#Toggle_match_observer').animate({ "top": '+='+animate_top+"px" }, 500 );
  5662. setTimeout(function(){
  5663. $('#Toggle_match_observer,#Toggle_league_table').css("pointer-events", "auto");
  5664. },500);
  5665. },400);
  5666. }
  5667. });
  5668.  
  5669. //if(Cookies.get('liveLeagueTable') == "1") $('#Toggle_match_observer').click();
  5670.  
  5671. unsafeWindow.jQuery('#content').off('mouseenter','#league-table > table > tbody > tr').on('mouseenter','#league-table > table > tbody > tr',function(){
  5672. let opp_idx = parseInt($(this).attr('opp_idx'));
  5673. if(isNaN(opp_idx)||opp_idx<0) return;
  5674. $('#league-table > table > tbody > tr').css('background-color','');
  5675. $(this).add($('#league-table > table > tbody > tr:nth-child('+(opp_idx+1)+')')).css('background-color','#4854a8;');
  5676. });
  5677. unsafeWindow.jQuery('#content').off('mouseleave','#league-table > table > tbody').on('mouseleave','#league-table > table > tbody',function(){
  5678. $('#league-table > table > tbody > tr').css('background-color','');
  5679. [currentLive.homeClubId,currentLive.awayClubId].forEach(id=>{$('#league-table > table > tbody > tr:has(a[clubid="'+id+'"])').css('background-color','#4854a8;');});
  5680. });
  5681. },
  5682.  
  5683. GetTable : function(tryGetPage=0){
  5684. delete this.GetTable;
  5685. return new Promise((res,rej)=>{
  5686. Game.getPage('index.php?w='+worldId+'&area=user&module=statistics&action=table&layout=none','#league-table-container').then(table_container=>{
  5687. let leagueIndex = $(table_container[0].querySelector('#leagueCatalogueForm')).find('select[group="league-selector"]').first().val(),
  5688. table = [],
  5689. rowClass = [];
  5690. $(table_container[0].querySelector('#statistics-league-table')).find('tbody > tr').each(function(i){
  5691. let tr = this,
  5692. data = {};
  5693. rowClass.push(tr.className.replace('odd','').replace('even','').trim());
  5694. //data.rank = i+1;
  5695. //data.trend = parseInt($(tr).find('> td:nth-child(2)').attr('sortvalue'));
  5696. data.clubId = $(tr).find('a[clubid]').attr('clubid');
  5697. data.clubName = $(tr).find('a[clubid]').text().trim();
  5698. data.played = parseInt($(tr).find('td:nth-child(4)').text());
  5699. data.won = parseInt($(tr).find('td:nth-child(5)').text());
  5700. data.drawn = parseInt($(tr).find('td:nth-child(6)').text());
  5701. data.lost = parseInt($(tr).find('td:nth-child(7)').text());
  5702. data.gf = parseInt($(tr).find('td:nth-child(8)').text().split(':')[0]);
  5703. data.ga = parseInt($(tr).find('td:nth-child(8)').text().split(':')[1]);
  5704. data.average = parseInt($(tr).find('td:nth-child(9)').text());
  5705. data.points = parseInt($(tr).find('td:nth-child(10)').text());
  5706. table.push(data);
  5707. });
  5708. res({leagueIndex:leagueIndex,table:table,rowClass:rowClass});
  5709. }).catch(err=>{rej(err);});
  5710. });
  5711. },
  5712. AllMatchesEnded : function(){ //In live->match page
  5713. let match_length = 1 + $('#match-observer > ul > li').length,
  5714. end_match_length = ($('#'+currentLive.matchId).hasClass('ended')?1:0) + $('#match-observer > ul > li.ended').length;
  5715. return match_length == end_match_length;
  5716. },
  5717. AreScoresUpdated : function(tryGetPage=0){
  5718. delete this.AreScoresUpdated;
  5719. return new Promise((res,rej)=>{
  5720. Game.getPage('index.php?w='+worldId+'&area=user&module=main&action=home&layout=none','#matches').then(matches=>{
  5721. let last_matches = $(matches).find('ul.matches.last'),
  5722. scores_updated = !1
  5723. if(!last_matches.find('li.no-entry').length){
  5724. last_matches = last_matches.find('>li');
  5725. let match_day = new Date(parseInt(currentLive.matchId.split('_')[2])*1000).toLocaleDateString();
  5726. last_matches.each(function(){
  5727. let match = $(this);
  5728. if(match.find('li.type > span.match.league').length){
  5729. let match_dates = match.find('li.date').text().trim().split(/\s+/g); // return ["23.02.2019", "18:00:00"] or ["Bugün, "18:00:00"] || ["Today, "18:00:00"]
  5730. if(match_dates[0].length != 10 || match_dates[0] == match_day)
  5731. scores_updated = !0;
  5732. return false;
  5733. }
  5734. });
  5735. }
  5736. res(scores_updated);
  5737. }).catch(err=>{rej(err);});
  5738. });
  5739. },
  5740. SetMatchIdForClub : function(table){
  5741. delete this.SetMatchIdForClub;
  5742. $('#match-observer>ul>li a[clubid]').each(function(){
  5743. let a = $(this);
  5744. table.find(c=>c.clubId==a.attr('clubid')).matchId = a.parents('li').first().attr('id').split('_')[a.parent().hasClass('squad-home')?0:1];
  5745. });
  5746. table.find(c=>c.clubId==currentLive.homeClubId).matchId = currentLive.homeId;
  5747. table.find(c=>c.clubId==currentLive.awayClubId).matchId = currentLive.awayId;
  5748. },
  5749. SetOppenentId : function(table){
  5750. table.forEach(c=>{
  5751. let clubId = c.clubId,
  5752. oppenent_id = null;
  5753. if(currentLive.homeClubId == clubId) oppenent_id = currentLive.awayClubId;
  5754. else if(currentLive.awayClubId == clubId) oppenent_id = currentLive.homeClubId
  5755. else{
  5756. $('#match-observer > ul > li').toArray().forEach(li=>{
  5757. li = $(li);
  5758. let a = li.find('a[clubid]');
  5759. if(a.toArray().find(a=>$(a).attr('clubid')==clubId)==undefined) return;
  5760. if(a.first().attr('clubid')==clubId) oppenent_id = a.last().attr('clubid')
  5761. else oppenent_id = a.first().attr('clubid');
  5762. });
  5763. }
  5764. if(oppenent_id!=null);
  5765. c.oppenent_id = oppenent_id;
  5766. });
  5767. },
  5768.  
  5769. GetCurrentScores : function(){
  5770. delete this.GetCurrentScores;
  5771.  
  5772. let scores = [];
  5773. //Add current matches scores
  5774. scores.push({
  5775. home: {
  5776. id: currentLive.homeClubId
  5777. },
  5778. away: {
  5779. id: currentLive.awayClubId
  5780. }
  5781. });
  5782.  
  5783. if($('#'+currentLive.matchId).hasClass('ended') && currentLive.timeElement.html()==1){ //Hükmen galibiyet
  5784. let home_goals = $('#match-messages > li.info').first().find('span.away,span.home').first().attr('class')=="away"?3:0,
  5785. away_goals = home_goals==3?0:3;
  5786. scores[0].home.goals = home_goals;
  5787. scores[0].away.goals = away_goals;
  5788. }
  5789. else{
  5790. scores[0].home.goals = parseInt($('#'+currentLive.matchId + '> span.score > div:first > span.score-home').text());
  5791. scores[0].away.goals = parseInt($('#'+currentLive.matchId + '> span.score > div:first > span.score-away').text());
  5792. }
  5793.  
  5794. scores.push(...$('#match-observer > ul > li').toArray().map(li=>{
  5795. return {
  5796. home: {
  5797. id: $('span.squad-home > a',li).attr('clubid'),
  5798. goals : parseInt($('> span.score > span.score-home',li).text())
  5799. },
  5800. away: {
  5801. id: $('span.squad-away > a',li).attr('clubid'),
  5802. goals : parseInt($('> span.score > span.score-away',li).text())
  5803. }
  5804. };
  5805. }));
  5806.  
  5807. //Add other matches scores
  5808. return scores;
  5809. },
  5810. CreateTableWithScores: function(scores, table, updated_table=false, fill_items=table){
  5811. let factor = updated_table?-1:1,
  5812. len = table.length,
  5813. new_table = new Array(len);
  5814. scores.forEach(score=>{
  5815. let diffGoals = score.home.goals - score.away.goals,
  5816. points = diffGoals!=0?3:1,
  5817. idx1 = table.findIndex(c=>c.clubId==score.home.id),
  5818. idx2 = table.findIndex(c=>c.clubId==score.away.id),
  5819. home_= table[idx1],
  5820. away_= table[idx2],
  5821. home,away;
  5822.  
  5823. new_table[idx1] = home = Object.create(home_);
  5824. new_table[idx2] = away = Object.create(away_);
  5825.  
  5826. home.points = home_.points + factor*points*(diffGoals>-1?1:0);
  5827. away.points = away_.points + factor*points*(diffGoals<1?1:0);
  5828. if(diffGoals!=0){
  5829. let key = diffGoals>0?'won':'lost';
  5830. home[key] = home_[key] + factor;
  5831. away[key = key=="lost"?'won':'lost'] = away_[key] + factor;
  5832. }
  5833. else{
  5834. home.drawn = home_.drawn + factor;
  5835. away.drawn = away_.drawn + factor;
  5836. }
  5837. home.gf = home_.gf + factor*score.home.goals;
  5838. away.gf = away_.gf + factor*score.away.goals;
  5839. home.ga = home_.ga + factor*score.away.goals;
  5840. away.ga = away_.ga + factor*score.home.goals;
  5841. home.average = home_.average + factor*diffGoals;
  5842. away.average = away_.average + factor*diffGoals*-1;
  5843. });
  5844.  
  5845. for(let i=0; i<len ;i++){
  5846. if(new_table[i]!==undefined) continue;
  5847. new_table[i] = fill_items.find(c=>c.clubId==table[i].clubId);
  5848. }
  5849.  
  5850. return this.SortTable(new_table);
  5851. },
  5852. SortTable : function(table){
  5853. return table.sort(function(a,b){
  5854. let compare;
  5855. if(compare = b.points - a.points) return compare; //En yüksek puana göre sırala
  5856. else if(compare = b.average - a.average) return compare; //Averajı yüksek olan
  5857. else if(compare = b.gf - a.ga) return compare; //Daha fazla gol atan
  5858. return a.clubId - b.clubId; //Daha önce takım açan
  5859. });
  5860. },
  5861. UpdateLiveLeagueTable : function(){
  5862. $('#league-table > table > tbody').html('')
  5863. function showChanged(diff){
  5864. return diff!=0?`<span class="changed-property" style="margin-left:2px;">(${(diff>0?'+':'')+diff})</span>`:'';
  5865. }
  5866. console.log('old: %o\n,new: %o',this.old_table,this.new_table);
  5867. this.new_table.forEach((club,i)=>{ //Add Row to Live League Table
  5868. let club_old_index = this.old_table.findIndex(c=>c.clubId==club.clubId),
  5869. club_old = this.old_table[club_old_index],
  5870. rank_dif = club_old_index-i,
  5871. diff = ['played','won','drawn','lost','gf','ga','average','points'].reduce((acc,key)=>{
  5872. acc[key] = club[key]-club_old[key];
  5873. return acc;
  5874. },{}),
  5875. opp_idx = null;
  5876. if(!isNaN(club.oppenent_id)) opp_idx = this.new_table.findIndex(c=>c.clubId==club.oppenent_id);
  5877. $('#league-table > table > tbody').append(
  5878. `<tr class="${this.tableRowClass[i]} ${i%2?'even':'odd'}" ${[currentLive.homeId, currentLive.awayId].includes(club.matchId)?`style="background-color:#4854a8;"`:''} ${!isNaN(opp_idx) && opp_idx>-1?`opp_idx="${opp_idx}"`:''}>`+
  5879. ` <td>${i+1}</td>`+
  5880. ` <td>`+
  5881. ` <div class="icon ${rank_dif>0?'advancement':rank_dif<0?'relegation':'remain'}" ${rank_dif!=0?` title="${(rank_dif>0?'+':'')+rank_dif}"`:""}></div>`+
  5882. ` </td>`+
  5883. ` <td class="name-column">`+
  5884. ` <a href="#/index.php?w=${worldId}&area=user&module=profile&action=show&clubId=${club.clubId}" clubid="${club.clubId}" ${club.clubId==Tool.clubId?'class="self-link"':''}>${club.clubName}</a>`+
  5885. ` </td>`+
  5886. ` <td style="color:black;">${club.played+showChanged(diff.played)}</td>`+
  5887. ` <td style="color:black;">${club.won+showChanged(diff.won)}</td>`+
  5888. ` <td style="color:black;">${club.drawn+showChanged(diff.drawn)}</td>`+
  5889. ` <td style="color:black;">${club.lost+showChanged(diff.lost)}</td>`+
  5890. ` <td style="color:black;">${club.gf+showChanged(diff.gf)}</td>`+
  5891. ` <td style="color:black;">${club.ga+showChanged(diff.ga)}</td>`+
  5892. ` <td style="color:black;">${club.average+showChanged(diff.average)}</td>`+
  5893. ` <td class="last-column" style="color: black;"><b>${club.points}</b>${showChanged(diff.points)}</td>`+
  5894. `</tr>`
  5895. );
  5896. });
  5897. },
  5898. StartToCatchNewGoals : function(){
  5899. delete this.StartToCatchNewGoals;
  5900. unsafeWindow.jQuery('<span id="NewGoalCatcher">').hide().appendTo('#content').click(function(_, matches_status){
  5901. // matches_status: { "668262_667855_1550761200_league": { "status": "ended", "home_goals": 0, "away_goals": 3, "min": 1 }, "669559_669389_1550761200_league": { "status": "ended", "home_goals": 0, "away_goals": 1, "min": 93 }, "669599_106135_1550761200_league": { "status": "ended", "home_goals": 5, "away_goals": 0, "min": 92 } }
  5902. if(!matches_status) return;
  5903. let new_scores = [];
  5904. console.log('New Goal Catcher: %o',matches_status);
  5905. for(let matchId in matches_status){
  5906. if(matchId.split('_')[3]!='league') continue;
  5907. let match = matches_status[matchId];
  5908. new_scores.push({
  5909. home : {
  5910. id : LiveLeagueTable.new_table.find(c=>c.matchId==matchId.split('_')[0]).clubId,
  5911. goals: match.home_goals
  5912. },
  5913. away : {
  5914. id : LiveLeagueTable.new_table.find(c=>c.matchId==matchId.split('_')[1]).clubId,
  5915. goals: match.away_goals
  5916. },
  5917. });
  5918. }
  5919.  
  5920. LiveLeagueTable.new_table = LiveLeagueTable.CreateTableWithScores(
  5921. new_scores, //updated scores
  5922. LiveLeagueTable.old_table, //old scores in old table and new scores use to create a table
  5923. false, //create next table
  5924. LiveLeagueTable.new_table //old scores will not be updated
  5925. );
  5926.  
  5927. LiveLeagueTable.UpdateLiveLeagueTable();
  5928. });
  5929. },
  5930. StartToCatchMatchEnd : function(){
  5931. delete this.StartToCatchMatchEnd;
  5932. unsafeWindow.jQuery('<span id="MatchEndCatcher">').hide().appendTo('#content').click(function(_, matchId){
  5933. console.log("Match ended: "+matchId);
  5934. });
  5935. }
  5936. };
  5937. LiveLeagueTable.Initialize();
  5938. },null);
  5939. Tool.features.add('SortTournaments','tournament',function(){
  5940. let upcoming_table = $('#tournaments > div.container.upcoming > div > table');
  5941. if(upcoming_table.find('>tbody>tr').length==0) return false;
  5942.  
  5943. let getDateNum = (date) => parseInt(((date=new Date((date=date.split('.'))[2],parseInt(date[1])-1,date[0]))-date.getTimezoneOffset()*60*1000)/86400000);
  5944. if(!Tool.hasOwnProperty('tournaments_data')){
  5945. $(CreateButton('BtnSortTournaments', GetText('SortTournaments'),'top:55px;')).insertAfter('#button-container-create-own-tournament').click(function(){
  5946. $(this).off().remove();
  5947. $('#tournaments-handle-container > li.handle').off();
  5948. let total_tournaments = 0,
  5949. tournaments = [], //except credits tournament
  5950. other_pages = upcoming_table.find('> tfoot > tr > td > a'),
  5951. page_count = 1 + other_pages.length;
  5952. if(page_count == 1) saveTournament(upcoming_table.find('>tbody'), true, toolTipObj.data);/*save current page*/
  5953. else{
  5954. let cur_page_num=-1,
  5955. e = upcoming_table.find('> tfoot > tr > td > strong');
  5956. if(e.length){
  5957. cur_page_num = parseInt(e.first().text());
  5958. saveTournament(upcoming_table.find('> tbody'), false, toolTipObj.data);/*save current page*/
  5959. }
  5960. let get_page_count = 0,
  5961. success_count = 0,
  5962. fail_count = 0;
  5963. $('#button-container-create-own-tournament').after(
  5964. `<span style="position: absolute;top: 55px;right: 52px;">`+
  5965. ` <img src="/designs/redesign/images/icons/loading/16x16.gif" style="vertical-align:middle;margin-right: 3px;">`+
  5966. ` ${GetText('gettingPage')}: <span id="get_page_count">0</span>/${page_count-1} | ${GetText('success')}: <span id="success_count">0</span> | ${GetText('fail')}: <span id="fail_count">0</span>`+
  5967. `</span>`
  5968. );
  5969. let always=(data=null)=>{
  5970. let finish = get_page_count == page_count-1;
  5971. if(finish) $('#get_page_count').parent().find('img').first().remove();
  5972. if(data==null) return;
  5973. saveTournament(data.content, finish, data.tooltip);
  5974. };
  5975. Array.from({length: page_count}, (_, i) => i + 1).forEach(n=>{
  5976. if(n==cur_page_num) return;
  5977. Game.getPage(
  5978. `?area=user&module=tournament&action=index&section=upcoming&posupcoming=${(n-1)*20}&layout=none`,
  5979. '#tournaments> div.container.upcoming> div> table> tbody:first',
  5980. null, //callback
  5981. 0, //fail counter
  5982. ['content','tooltip']
  5983. ).then(data=>{
  5984. data.tooltip = JSON.parse(data.tooltip);
  5985. if(!data.content.length || typeof data.tooltip != 'object') throw new Error("There is an error in the requested data.");
  5986. $('#get_page_count,#success_count').toArray().forEach(e=>{$(e).html(eval("++"+e.id))})
  5987. always(data)
  5988. }).catch(err=>{
  5989. $('#get_page_count,#fail_count').toArray().forEach(e=>{$(e).html(eval("++"+e.id))})
  5990. console.error(err);
  5991. always();
  5992. });
  5993. });
  5994. }
  5995.  
  5996. function saveTournament(tbody, finish, tooltip){
  5997. total_tournaments += tbody.find('tr').length;
  5998. tbody.find('tr').each(function(i){
  5999. if($(this).find('.first-column > .credits').length) return;
  6000. let tournament_id = $(this).find(' td.info-column > a > img').attr('tooltip').replace('tt_',''),
  6001. tournament = {
  6002. has_psw : $(this).find('.first-column > .password').length?true:false,
  6003. name : $(this).find('.name-column:first>a').text().trim(),
  6004. id : tournament_id,
  6005. tt : tooltip['tt_'+tournament_id]
  6006. },
  6007. totalPrice = 0, koo = false;
  6008. $(tournament.tt).find('div.tournament-tooltip-table> table> tbody> tr').each(function(j){
  6009. if($(this).find('.last-column').length)
  6010. totalPrice += parseInt($(this).find('td.last-column > span > span.currency-number').text().split('.').join(''));
  6011. else{
  6012. koo = true;
  6013. return;
  6014. }
  6015. });
  6016. if(!koo){
  6017. let a = $(this).find('td:nth-child(4) > a').first(),
  6018. start = $(this).find('td:nth-child(5)').text().trim(),
  6019. end = $(this).find('td:nth-child(6)').text().trim();
  6020. tournaments.push(Object.assign({
  6021. totalPrice: totalPrice,
  6022. type: $(this).find('td:nth-child(3) > span')[0].className.replace('icon','').trim(),
  6023. club: {
  6024. id : a.attr('clubid'),
  6025. name: a.text().trim()
  6026. },
  6027. start : start,
  6028. startK: getDateNum(start),
  6029. end : end,
  6030. endK: getDateNum(end),
  6031. },tournament));
  6032. }
  6033. else{
  6034. console.info(`The tournament named ${tournament.name}[id=${tournament.id}] is not included in the ranking]`);
  6035. }
  6036. });
  6037. if(finish){
  6038. console.info(`Total tournaments: ${total_tournaments}. Maximum ${tournaments.length} of them will be sorted and shown!`);
  6039. Tool.tournaments_data = {
  6040. tournaments: tournaments,
  6041. total: total_tournaments,
  6042. except: total_tournaments-tournaments.length //Credit tournaments size
  6043. };
  6044. if($('#get_page_count').length){
  6045. Tool.tournaments_data = Object.assign({
  6046. page_count: page_count-1,
  6047. get_page_count: parseInt($('#get_page_count').html()),
  6048. success_count: parseInt($('#success_count').html()),
  6049. fail_count: parseInt($('#fail_count').html())
  6050. },Tool.tournaments_data);
  6051. }
  6052. sortTournaments('money', 'DESC');
  6053. showTournaments();
  6054. }
  6055. }
  6056. })[$('#tournaments-handle-container > li[target=".container.upcoming"]').hasClass('active')?'show':'hide']();
  6057.  
  6058. $('#tournaments-handle-container > li.handle').click(function(){
  6059. $('#BtnSortTournaments')[$(this).attr('target')==".container.upcoming"?'show':'hide']();
  6060. });
  6061. }
  6062. else{
  6063. if(Tool.tournaments_data.hasOwnProperty('page_count')){
  6064. $('#button-container-create-own-tournament').after(
  6065. '<span style="position: absolute;top: 55px;right: 52px;">'+
  6066. ` ${GetText('gettingPage')}: ${Tool.tournaments_data.get_page_count}/${Tool.tournaments_data.page_count} | ${GetText('success')}: ${Tool.tournaments_data.success_count} | ${GetText('fail')}: ${Tool.tournaments_data.fail_count}`+
  6067. '</span>'
  6068. );
  6069. }
  6070. showTournaments(); /*Show saved tournaments*/
  6071. }
  6072.  
  6073. function showTournaments(){
  6074. let thead_row = $('>thead>tr',upcoming_table).first();
  6075. thead_row.before(
  6076. `<tr style="background:none;">`+
  6077. ` <th colspan="8" style="background-color: #075971;border-radius: 7px 7px 0 0;padding:5px;"><span id="sorted_tournaments_length" style="line-height: 1.4; white-space: break-spaces;">...</span></th>`+
  6078. `</tr>`
  6079. );
  6080.  
  6081. $('>th:nth-child(5),>th:nth-child(6)',thead_row)
  6082. .addClass('sort_tournaments')
  6083. .attr({'sort_type':'date','order_by':'DESC'})
  6084. .css('cursor','pointer');
  6085. $('th:nth-child(6)',thead_row).after(`<th class="sort_tournaments" sort_type="money" order_by="ASC" style="cursor:pointer;">${GetText('totalprice')}</th>`);
  6086. $('.sort_tournaments').click(function(){
  6087. let order_by = $(this).attr('order_by');
  6088. sortTournaments($(this).attr('sort_type'), order_by);
  6089. updateTbody();
  6090. $(this).attr('order_by',order_by=='ASC'?'DESC':'ASC');
  6091. });
  6092.  
  6093. $('>tfoot',upcoming_table).html('');
  6094.  
  6095. let ownTournaments = [],
  6096. own_tbody = $('#tournaments > div.container.own > div > table > tbody');
  6097. if(own_tbody.find('.info-column').length){
  6098. own_tbody.find('tr').each(function(){
  6099. let icon = $(this).find('>td.first-column> span.icon'),
  6100. tournament = {
  6101. id: $(this).find('>td.info-column>a>img[tooltip]').attr('tooltip').replace('tt_',''),
  6102. type:'normal'
  6103. };
  6104. if(icon.length){
  6105. if(icon.hasClass('password')) tournament.has_psw = true;
  6106. if(icon.hasClass('credits')) tournament.type='credits';
  6107. else if(icon.hasClass('tournament')) tournament.type='special';
  6108. }
  6109. ownTournaments.push(Object.assign({
  6110. start: getDateNum($(this).find('td:nth-child(4)').text().trim()),
  6111. end : getDateNum($(this).find('td:nth-child(5)').text().trim())
  6112. },tournament));
  6113. });
  6114. }
  6115.  
  6116. let isTournamentIntersect = t1=>{
  6117. let s1=t1.startK, e1=t1.endK;
  6118. return undefined !== ownTournaments.filter(t2=>t2.type!='special').find(t2=>{
  6119. let s2=t2.start, e2=t2.end;
  6120. return (e1>=s2 && e1<=e2) || (s1<=e2 && s1>=s2);
  6121. });
  6122. }, tbody = $('>tbody',upcoming_table);
  6123. updateTbody()
  6124.  
  6125. function updateTbody(){
  6126. tbody.html('');
  6127. let intersect=0,
  6128. i=0;
  6129. Tool.tournaments_data.tournaments.forEach((t)=>{
  6130. if(isTournamentIntersect(t)){ ++intersect; return;} // or set background-color:#00000099
  6131. tbody.append(
  6132. `<tr class="${i++%2?"even":"odd"}">`+
  6133. ` <td class="first-column">${t.has_psw?`<span class="icon password"></span>`:``}</td>`+
  6134. ` <td class="name-column">`+
  6135. ` <a href="#/index.php?w=${worldId}&area=user&module=tournament&action=tournament&tournament=${t.id}">${t.name}</a>`+
  6136. ` </td>`+
  6137. ` <td>`+
  6138. ` <span class="icon ${t.type}" tooltip="tt_tournament_type_${t.type}"></span>`+
  6139. ` </td>`+
  6140. ` <td class="name-column">`+
  6141. ` <div class="club-logo-container"></div>`+
  6142. ` <a href="#/index.php?w=${worldId}&area=user&module=profile&action=show&clubId=${t.club.id}" clubid="${t.club.id}">${t.club.name}</a>`+
  6143. ` </td>`+
  6144. ` <td class="date-column" sortvalue="${t.startK}">${t.start}</td>`+
  6145. ` <td class="date-column" sortvalue="${t.endK}">${t.end}</td>`+
  6146. ` <td>${t.totalPrice.toLocaleString()}</td>`+
  6147. ` <td class="last-column info-column">`+
  6148. ` <a href="#/index.php?w=${worldId}&area=user&module=tournament&action=tournament&tournament=${t.id}">`+
  6149. ` <img src="/designs/redesign/images/icons/tooltip.gif" name="__tooltip" tooltip="tt_${t.id}">`+
  6150. ` </a>`+
  6151. ` </td>`+
  6152. `</tr>`
  6153. );
  6154. if(!toolTipObj.data.hasOwnProperty('tt_'+t.id)) toolTipObj.data['tt_'+t.id] = t.tt;
  6155. });
  6156. let total = Tool.tournaments_data.total,
  6157. except = Tool.tournaments_data.except,
  6158. attended = ownTournaments.length,
  6159. shown = tbody.find('>tr').length,
  6160. lines=[GetText('Tournament_total', {args:[`<font color="chartreuse">${total}</font>`]})],
  6161. missing=0;
  6162.  
  6163. if(except){
  6164. lines.push(GetText('Tournament_except', {args:[`<font color="crimson">${except}</font>`]}));
  6165. missing+=except;
  6166. }
  6167. if(intersect){
  6168. if(missing==0){
  6169. lines.push(GetText('Tournament_intersect_1', {args:[`<font color="crimson">${intersect}</font>`, `<font color="chartreuse">${total}</font>`, `<font color="darkturquoise">${attended}</font>`]}));
  6170. }
  6171. else{
  6172. lines.push(GetText('Tournament_intersect_2', {args:[`<font color="crimson">${intersect}</font>`, `<font color="chocolate">${total-except}</font>`, `<font color="darkturquoise">${attended}</font>`]}));
  6173. }
  6174. missing+=intersect;
  6175. }
  6176. if(shown<total-missing){
  6177. lines.push(GetText('Tournament_unknown', {args:[`<font color="crimson">${(total-missing)-shown}</font>`]}));
  6178. missing+=(total-missing)-shown;
  6179. }
  6180. if(missing==0) lines[0]+=" "+GetText('Tournament_end_1', {args:[]});
  6181. else{
  6182. lines.push(GetText('Tournament_end_2', {args:[`<font color="mediumspringgreen" style="font-size: 15px;">${shown}</font>`]}));
  6183. }
  6184. $('#sorted_tournaments_length').html(lines.join('<br>'));
  6185. }
  6186. }
  6187. function sortTournaments(type, order_by='DESC'){
  6188. order_by=order_by=='DESC'?1:-1;
  6189. switch(type){
  6190. case "money":
  6191. Tool.tournaments_data.tournaments.sort((a,b)=>order_by*(b.totalPrice-a.totalPrice));
  6192. break;
  6193. case "date":
  6194. Tool.tournaments_data.tournaments.sort((a,b)=>order_by*(a.startK-b.startK));
  6195. break;
  6196. }
  6197. }
  6198. },null);
  6199.  
  6200. (async ()=>{
  6201. await new Promise(res=>{
  6202. //updateLayout function is will declerate asap in body script tag.
  6203. //When it is exist it will be updated to start detecting page changing
  6204. Tool.intervals.create(function(){
  6205. if(typeof unsafeWindow.updateLayout != 'function') return;
  6206. this.delete();
  6207. Game.startDetectingPageChanging();
  6208. res();
  6209. },20);
  6210. });
  6211. Tool.start();
  6212. })();
  6213.  
  6214. //FUNCTIONS
  6215. function CatchError(e,where){
  6216. console.log('%c[FCUP-SCRİPT] %cERROR%c | '+ e + '%c\tIn'+where,'color:blue;font-weight:bold;','color:red;','','float:right;color:green;');
  6217. }
  6218.  
  6219. function SecToTime(s){
  6220. //Converts seconds to [d [day|days]] hh:mm:ss
  6221. if(s<0) return '-';
  6222. let m = 0,h = 0,t='';
  6223. if(s>59)
  6224. if((m = parseInt(s/60))>59)
  6225. if((h = parseInt(m/60))>23)
  6226. t = parseInt(h/24)+' '+(h<48?GetText('aDay'):GetText('Days'))+' ';
  6227. return t + Pad2(h%24)+':'+Pad2(m%60)+':'+Pad2(s%60);
  6228. }
  6229. function GetDateText(ms){
  6230. // Converts milliseconds to d.m.Y H:i:s date format
  6231. let d = new Date(ms);
  6232. return Pad2(d.getDate())+"."+
  6233. Pad2(d.getMonth()+1)+"."+
  6234. d.getFullYear()+' '+
  6235. Pad2(d.getHours())+":"+
  6236. Pad2(d.getMinutes())+":"+
  6237. Pad2(d.getSeconds());
  6238. }
  6239.  
  6240. function Pad2(a){
  6241. return (a<10?"0":"")+a;
  6242. }
  6243. function GetOffset(el){
  6244. let _x = 0,_y = 0;
  6245. while(el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
  6246. _x += el.offsetLeft - el.scrollLeft;
  6247. _y += el.offsetTop - el.scrollTop;
  6248. el = el.offsetParent;
  6249. }
  6250. return {top: _y, left: _x};
  6251. }
  6252. function GetFuncContent(func){
  6253. return (func=func.toString()).substring(func.indexOf('{')+1, func.lastIndexOf('}'));
  6254. }
  6255.  
  6256. function DownloadAsTextFile(text,filename){
  6257. let object_URL = URL.createObjectURL(new Blob([text], {type: "text/plain"}));
  6258. $('<a>').attr({'href':object_URL,'download':(filename||'Fcup Script Datas')+'.txt'})[0].click();
  6259. URL.revokeObjectURL(object_URL);
  6260. }
  6261. function ReadTextFile(func){
  6262. $('<input type="file" accept="text/plain">').change(function(e){
  6263. let file = this.files[0];
  6264. if(file.type == 'text/plain') {
  6265. let reader = new FileReader();
  6266. reader.onload = function() {
  6267. func(reader.result);
  6268. };
  6269. reader.readAsText(file);
  6270. }
  6271. }).click();
  6272. }
  6273.  
  6274. function ShowDialog(div,header=undefined,setMid=true){
  6275. $('html, body').animate({ scrollTop: 0 }, 'fast');
  6276. $('#container > .shadow').show();
  6277.  
  6278. let focus = $('<div>').attr('id',div.id || null).css({
  6279. 'padding' : '15px',
  6280. 'width' : '580px',
  6281. 'wordWrap' : 'break-word',
  6282. 'textAlign' : 'center!important',
  6283. 'box-sizing': 'border-box'
  6284. }).css(div.css || {}).addClass('focus visible').addClass(div.class || null).html(div.content || '');
  6285.  
  6286. if(typeof header == 'object'){
  6287. let h2 = $('<h2>').css(header.css || {}).html(header.content || '').css({
  6288. width : '100%',
  6289. paddingLeft : '0px',
  6290. paddingRight : '0px',
  6291. top : '0px',
  6292. transform : 'translateY(-100%)'
  6293. });
  6294. focus.prepend(h2);
  6295. }
  6296.  
  6297. if(div.footer) focus.append('<div class="footer"></div>');
  6298.  
  6299. if(div.close) focus.append('<div class="close" style="position:absolute;top:-46px"></div>');
  6300.  
  6301. $('#container').append(focus);
  6302.  
  6303. let topOffset = 190;
  6304. if(setMid){
  6305. //Set In The Midst
  6306. topOffset = 0/*$(window).scrollTop()*/ + ($(window).innerHeight() - focus.height()) / 2;
  6307. if (topOffset < 190) topOffset = 190;
  6308. }
  6309. focus.css({
  6310. 'position': 'absolute',
  6311. 'top' : topOffset + 'px',
  6312. 'left' : ($(window).scrollLeft() + ($(window).innerWidth() / 2) - (focus.width() / 2 + focus.parent().offset().left)) + 'px'
  6313. });
  6314. }
  6315. function CreateButton(id,value,buttonStyle='',spanStyle=''){
  6316. return `<span class="button disHighlight" id="${id}" style="cursor:pointer; ${buttonStyle}">`+
  6317. ` <a class="button" style="text-decoration:none;">`+
  6318. ` <span style="${spanStyle}">${value}</span>`+
  6319. ` </a>`+
  6320. `</span>`;
  6321. }
  6322. function BlinkEvent(e,duration,duration2=2500,times=5){
  6323. times = Math.max(times,1);
  6324. if(e.attr('BlinkEvent')!=undefined){
  6325. if(e.attr('BlinkEvent')!=0){
  6326. e.attr('BlinkEvent',times);
  6327. return;
  6328. }
  6329. else e.attr('BlinkEvent',times);
  6330. }
  6331. e.attr('BlinkEvent',times);
  6332. e.css('background-color','#910e0ea8');
  6333. f();
  6334. let blink = setInterval(f, duration);
  6335. function f(){
  6336. e.fadeOut(duration/2);
  6337. e.fadeIn(duration/2);
  6338. let times = parseInt(e.attr('BlinkEvent'))||1;
  6339. e.attr('BlinkEvent',--times);
  6340. if(times<1){
  6341. clearInterval(blink);
  6342. setTimeout(()=>{
  6343. if(e.attr('BlinkEvent')==0){
  6344. e.css('transition','background-color 1s').css('background-color','');
  6345. setTimeout(()=>{
  6346. if(e.attr('BlinkEvent')==0){
  6347. e.css('transition','');
  6348. e.removeAttr('BlinkEvent');
  6349. }
  6350. },1000);
  6351. }
  6352. },duration2);
  6353. }
  6354. }
  6355. }
  6356.  
  6357. function SaveLeagueData(cntnt){
  6358. if(cntnt.find('.date-selector').length==0) return false;
  6359. if(cntnt.find('div.table-container table > tbody a[clubid][class*="self-link"]').length==0) return false;
  6360.  
  6361. let match_weeks = cntnt.find('.date-selector > ul >li.day').length,
  6362. date = $('div > div.table-container > h3',cntnt)[0].textContent, // "Spieltag: 2 - 13.09.2020 18:00:00"
  6363. idx1 = date.indexOf(':');
  6364. if(idx1==-1) return false;
  6365. idx1++;
  6366. let idx2 = date.indexOf('-',idx1+1);
  6367. if(idx2==-1) return false;
  6368. let match_day_number = parseInt(date.substring(idx1,idx2)); //Exp: Return 2
  6369. idx2++;
  6370. let lastMatchDate = date.substring(idx2,date.indexOf(' ',date.indexOf('.',idx2+1)+1)).trim().split('.'),
  6371. addDay = match_weeks-match_day_number,
  6372. aDay = 24*60*60*1000; // ms
  6373. if(match_day_number<match_weeks/2) addDay+=3; //League break days
  6374. lastMatchDate = new Date(lastMatchDate[2],parseInt(lastMatchDate[1])-1,parseInt(lastMatchDate[0])+addDay).getTime();
  6375.  
  6376. if(lastMatchDate+aDay<=Game.getTime()) return false;
  6377.  
  6378. let firstMatchDate = lastMatchDate-(match_weeks-1+3)*aDay,
  6379. firstHalfFinalMatchDate = firstMatchDate+(match_weeks/2-1)*aDay,
  6380. clubs = {};
  6381. cntnt.find('div.table-container table >tbody .name-column').each(function(){
  6382. let a = $(this).find('a:first'),
  6383. clubId = a.attr('clubid');
  6384. if(clubId==Tool.clubId) return;
  6385. clubs[clubId] = a.text().trim();
  6386. });
  6387.  
  6388. let LeagueData = {
  6389. league : cntnt.find('select:first > option:selected').text().trim(),
  6390. firstMatchDate : firstMatchDate,
  6391. firstHalfFinalMatchDate: firstHalfFinalMatchDate,
  6392. lastMatchDate : lastMatchDate,
  6393. clubs : clubs
  6394. };
  6395. Tool.setVal('LeagueData',LeagueData);
  6396. return LeagueData;
  6397. }
  6398. function IsYoungPlayer(td){
  6399. return $(td).find('[tooltip="tt_extendNotPossibleJunior"]').length;
  6400. }
  6401. function GetRealStrength(skills,position){
  6402. // skills: Float Array(14), positions: String
  6403. let strengthFactors = Tool.strengthFactors[position];
  6404. if(!Array.isArray(strengthFactors)) return "-";
  6405. return strengthFactors.reduce((acc,i)=>acc+skills[i[0]]/28*i[1],0);
  6406. }
  6407. function FindNumberOfTraining(start,end){
  6408. // start and end are dates ms
  6409. if(end <= start) return 0;
  6410.  
  6411. let normalTrainingsTimeCycle = [
  6412. [36000, 54000],
  6413. [36000, 54000],
  6414. [25200, 36000, 54000],
  6415. [36000, 54000]
  6416. ], premiumTrainingsTimeCycle = [[25200],[],[],[]],
  6417. normalTrainingsInACycle = normalTrainingsTimeCycle.reduce((acc,v)=>acc+v.length,0),
  6418. premiumTrainingsInACycle = premiumTrainingsTimeCycle.reduce((acc,v)=>acc+v.length,0),
  6419. startDate = new Date(start),
  6420. endDate = new Date(end),
  6421. getDaySeconds = (date)=>date.getHours()*3600+ date.getMinutes()*60+ date.getSeconds(), //Return [0,86400]
  6422. getDayIndex = (date)=>parseInt((date.getTime()-date.getTimezoneOffset()*60*1000)/86400000)%4,
  6423. normalTrainings = 0,
  6424. premiumTrainings = 0,
  6425. addDayTrainings = (date,dayIndex,after=true)=>{
  6426. let daySeconds = getDaySeconds(date);
  6427. let a,b;
  6428. normalTrainings += a = normalTrainingsTimeCycle[dayIndex].filter(time=>after?time>daySeconds:daySeconds>time).length;
  6429. premiumTrainings += b = premiumTrainingsTimeCycle[dayIndex].filter(time=>after?time>daySeconds:daySeconds>time).length;
  6430. return dayIndex;
  6431. },
  6432. getDaysBetweenDates = (s,e)=> (new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime() - new Date(s.getFullYear(),s.getMonth(),s.getDate()).getTime())/86400000-1;
  6433.  
  6434. // 1- Calculate the day index using the start date and add trainings in the starting day.
  6435. let dayIndex = getDayIndex(startDate);
  6436. addDayTrainings(startDate,dayIndex);
  6437.  
  6438. // 2- Başlangıç ve bitiş günleri arasındaki gün sayısını bul. Gün sayısını kullanarak döngü sayısını bul. Döngü kadar antrenman ekle
  6439. let days = getDaysBetweenDates(startDate,endDate),
  6440. cycle_count = parseInt(days/4);
  6441. normalTrainings += cycle_count*normalTrainingsInACycle;
  6442. premiumTrainings += cycle_count*premiumTrainingsInACycle;
  6443.  
  6444. // 3- Döngüsü tamamlanmamış günleri tek tek ekle
  6445. for(let i=0,len=days%4; i<len; i++){
  6446. dayIndex = (dayIndex+1)%4;
  6447. normalTrainings += normalTrainingsTimeCycle[dayIndex].length;
  6448. premiumTrainings += premiumTrainingsTimeCycle[dayIndex].length;
  6449. }
  6450.  
  6451. // 4- Bitiş günündeki anrenman sayısını ekle
  6452. dayIndex = (dayIndex+1)%4;
  6453. addDayTrainings(endDate,dayIndex,false);
  6454.  
  6455. return {normal: normalTrainings, premium: premiumTrainings};
  6456. }
  6457. function CalculateFutureStrength(start, end, skills, position, young, limit=990){
  6458. let trainings = FindNumberOfTraining(start,end),
  6459. training_score = young==true?parseInt(Tool.yTrainerLevel)+0.5: parseInt(Tool.trainerLevel)*0.25+0.5,
  6460. next_skills = {
  6461. normal : skills.slice(0),
  6462. premium: skills.slice(0)
  6463. },
  6464. trainingRankingOfSkills = Tool.trainingPlan[position];
  6465.  
  6466. for(let i=0, remaining_trainings=trainings.normal ; i < trainingRankingOfSkills.length && remaining_trainings>0 ; i++){
  6467. let skillIndex = trainingRankingOfSkills[i],
  6468. cur_value = skills[skillIndex];
  6469. if(cur_value>=limit) continue;
  6470. let apply_trainings = Math.min(
  6471. remaining_trainings,
  6472. GetMaxSkill(cur_value, training_score, limit).required_trainings
  6473. );
  6474. next_skills.premium[skillIndex] = next_skills.normal[skillIndex] = cur_value + (apply_trainings*training_score);
  6475. remaining_trainings-=apply_trainings;
  6476. }
  6477.  
  6478. for(let i=0, remaining_trainings=trainings.premium ; i < trainingRankingOfSkills.length && remaining_trainings>0 ; i++){
  6479. let skillIndex = trainingRankingOfSkills[i],
  6480. cur_value = next_skills.premium[skillIndex];
  6481. if(cur_value>=limit) continue;
  6482. let apply_trainings = Math.min(
  6483. remaining_trainings,
  6484. GetMaxSkill(cur_value, training_score, limit).required_trainings
  6485. );
  6486. next_skills.premium[skillIndex] += apply_trainings*training_score;
  6487. remaining_trainings-=apply_trainings;
  6488. }
  6489.  
  6490. return {
  6491. current_strength: GetRealStrength(skills, position),
  6492. future : {
  6493. normal : {
  6494. strength : GetRealStrength(next_skills.normal, position),
  6495. skills : next_skills.normal,
  6496. trainings: trainings.normal
  6497. },
  6498. premium:{
  6499. strength : GetRealStrength(next_skills.premium, position),
  6500. skills : next_skills.premium,
  6501. trainings: trainings.normal + trainings.premium
  6502. }
  6503. }
  6504. };
  6505.  
  6506. }
  6507. function GetMaxSkill(curVal,trainingScore,limit=990){
  6508. let diff = limit-curVal,
  6509. numberOfTrainings = 0;
  6510. if(diff>0){
  6511. numberOfTrainings = Math.ceil(diff/trainingScore);
  6512. curVal = Math.min(1000,curVal+numberOfTrainings*trainingScore);
  6513. }
  6514. return {max_value:curVal, required_trainings:numberOfTrainings};
  6515. }
  6516.  
  6517. function GetMessagesByTitle(title,func){
  6518. let id,messages=[],message,_title;
  6519. $('#deleteForm > table > tbody').find('.odd,.even').each(function(){
  6520. id = $(this).attr('id').split('-')[1];
  6521. message = $('#newscenter-preview-'+id);
  6522. _title = message.find('h2').first().text().replace(/\s\s+/g, ' ').trim();
  6523. if(_title == title) messages.push(message);
  6524. });
  6525. if(messages.length) func(messages);
  6526. }