CSGOLoungeLive

A csgolounge.com betting tool and enhancer.

当前为 2015-04-08 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name CSGOLoungeLive
  3. // @namespace CSGOLoungeLive
  4. // @author soma
  5. // @description A csgolounge.com betting tool and enhancer.
  6. // @include http://csgolounge.com/
  7. // @include http://csgolounge.com/#
  8. // @exclude http://*.csgolounge.com/
  9. // @include http://dota2lounge.com/
  10. // @include http://dota2lounge.com/#
  11. // @exclude http://*.dota2lounge.com/
  12. // @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
  13. // @version 0.2.3.3
  14. // @icon http://cloud-4.steamusercontent.com/ugc/594764304137589098/69F7EBE2735C366C65C0B33DAE00E12DC40EDBE4/
  15. // @grant GM_addStyle
  16. // @grant GM_getValue
  17. // @grant GM_setValue
  18. // @grant GM_xmlhttpRequest
  19. // @grant GM_getResourceText
  20. // ==/UserScript==
  21.  
  22. /* Note: You are ALLOWED to edit and/or modify this script if belonging credits are given and you have informed the author BEFORE publishing the modified version.
  23. * You are NOT ALLOWED to sell whole or any parts of this script.
  24. * (cl) 2015 - soma.
  25. * For further information contact soma @steam id: "somq" or on reddit.
  26. * */
  27. GM_addStyle(' \
  28. body {background-image: none;}\
  29. .shownotav-btn:active { text-shadow: 0 1px 0 rgba(255, 255, 255, 0.3); text-decoration: none; background-color: #eeeeee; border-color: #cfcfcf; color: #d4d4d4; } \
  30. .shownotav-btn:hover, .button:focus, #switchmainviewa:hover, #switchmainviewa:hover { background-color: #f6f6f6; color:#999;} \
  31. .shownotav-btn { letter-spacing: 5px; font-size: 16px; height: 50px; line-height: 40px; border-radius: 4px; background-color: #eeeeee; border: medium none; box-sizing: border-box; color: #666666; cursor: pointer; transition-duration: 0.3s; transition-property: all;; float: left; height: 40px; text-align: center; } \
  32. .shownotav { width: 100%; padding: 0 50px; } \
  33. main section.box {width: 68%;};\
  34. .smallfont {font-size: 12px;} a.smallfont:hover {color:#666;}.teamadetails {width: 45%; float: left; text-align: center} .teambdetails{width: 45%; float: left; text-align: center} \
  35. .vsdetails{width: 10%; float: left; text-align: center;font-size: 16px;} .detailsbox {float: left; margin: 16px 2%; width: 78%;font-size: 14px;}.teamtext {font-size:16px} \
  36. .c-loading {background-image: url("http://img4.hostingpics.net/pics/5276773011.gif"); height: 100px; position: absolute; width: 100px;}\
  37. .matchleft {min-height: 70px;box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.5) inset, 0 1px 1px 0 rgba(255, 255, 255, 0.5); border-radius: 8px; padding: 5px 0;max-width:1555px; width:63%;} section.box {width:98%; max-width:1430px;} .matchctn{float:left;width: 98%;} \
  38. #c-overlay { background-color: rgba(0, 0, 0, 0.5); height: 100%; left: 0; position: absolute; top: 0; width: 100%; z-index: 10; }\
  39. #switchmainview {float: right; display:none;}\
  40. #mainloadingbar li {margin-left: auto; margin-right: auto; width: 260px;}\
  41. .progress { box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.5) inset, 0 1px 1px 0 rgba(255, 255, 255, 0.5); margin: 0 auto; width:200px; background: none repeat scroll 0 0 #ebebeb; border-left: 1px solid transparent; border-radius: 10px; border-right: 1px solid transparent; height: 20px;}\
  42. .progress > span {background: linear-gradient(to bottom, #f0f0f0, #dbdbdb 70%, #cccccc) repeat scroll 0 0 #cccccc; border-color: #bfbfbf #b3b3b3 #9e9e9e; border-image: none; border-radius: 10px; border-style: solid; border-width: 1px; box-shadow: 0 1px rgba(255, 255, 255, 0.3) inset, 0 1px 2px rgba(0, 0, 0, 0.2); float: left; height: 18px;line-height: 4px; margin: 0 -1px; min-width: 30px; position: relative;text-align: right;} \
  43. .progress > span > span { line-height: 17px; color: rgba(0, 0, 0, 0.7); font-size: 11px; font-weight: bold; padding: 0 8px; text-shadow: 0 1px rgba(255, 255, 255, 0.4);} \
  44. .mb-loading { height: 25px;text-align: center; background: url("http://img11.hostingpics.net/pics/279433ajaxloader3.gif") no-repeat scroll center center rgba(0, 0, 0, 0);} \
  45. .rounded-btn1{ display: block;width:40px; height:40px; border-top:2px solid #fff; border-radius:50%; background-color:#EEEEEE; background: linear-gradient(#EDEAE1,#CDC8B5); text-align:center; box-shadow: 0 5px 2px 3px rgba(158, 158, 158, 0.4), 0 3px 5px #B7B6B6, 0 0 0 2px #BBB7AE, inset 0 -3px 1px 2px rgba(186, 178, 165, 0.5), inset 0 3px 1px 2px rgba(246, 245, 241, 0.3); cursor:pointer; } .rounded-btn1:active{border-radius:50%; border-top:none; border:1px solid #BAB7AE; background-color:#EEEEEE; text-align:center; color:#BAB7AE; text-shadow: 0 1px 1px white, 0 1px 1px #BAB7AE; box-shadow: 0 0 0 0 #BBB7AE; } .rounded-btn1 span { font-size:30px; color:#666; text-shadow:2px 2px 0 rgba(255, 255, 255, 0.9);}\
  46. .feeds {text-shadow: 1px 1px 0 #e5e5e5;margin: 16px 1%; font-size:14px;}\
  47. #feedsbox { width:30%; display: block; float: left; margin: 10px 0.5%;}\
  48. .feeds-header {background: url("http://img11.hostingpics.net/pics/396420iconrssgrey.png") no-repeat scroll 0 0 / 33px auto rgba(0, 0, 0, 0)}\
  49. .feedbox-title-inner { float:left; padding: 0 40px;}\
  50. .feedstitle { height: 46px; opacity: 0.7; padding: 1%; text-align: center; text-decoration: underline; }\
  51. #hltvfeed .feedstitle {background: url("http://img15.hostingpics.net/pics/49901496Zhddu.jpg") no-repeat scroll 50% center rgba(0, 0, 0, 0);}\
  52. #redditfeed .feedstitle {background: url("http://img15.hostingpics.net/pics/464286reddit.png") no-repeat scroll 50% center rgba(0, 0, 0, 0);}\
  53. #gosugamersfeed .feedstitle {background: url("http://img15.hostingpics.net/pics/241137gglogo.png") no-repeat scroll 50% center rgba(0, 0, 0, 0);}\
  54. .feeds li { box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.5) inset, 0 1px 1px 0 rgba(255, 255, 255, 0.5); padding: 1%; } \
  55. .feedslinks-box {margin: 0 2% 16px;padding-top: 5px;}\
  56. .feedlink a {display: block;}\
  57. .feedlink a:hover {border-radius: 2px; box-shadow: 1px 0px 0px 1px #999; display: block; opacity: 0.8; transition: 0.5s;}\
  58. .main-feedbox { background-color: #bbb;border-radius: 5px;float: left;box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.5) inset, 0 1px 1px 0 rgba(255, 255, 255, 0.5);width: 100%;}\
  59. .line2a { padding-left: 10px; text-align: center;font-size: 14px;}\
  60. .line2b { padding-right: 10px; text-align: center;font-size: 14px;}\
  61. .matchbox-summary { float: left; font-size: 12px; margin: 16px 0; width: 15%;}\
  62. .expandmatch-btn { color: #ddd; position:absolute; height: 20px; padding-left: 7px; font-size:20px;}\
  63. .expmatchbtn-ctn { float: right; height: 25px; width: 25px;}\
  64. .infosbelow-lr {width: 35%; float: left;}\
  65. .infosbelow-center { float: left; font-size: 14px; text-align: center; width: 30%; } \
  66. .sumbox {text-align: center; background: #bababa; border-radius: 4px; float: left; margin: 2px 0; opacity: 0.9; padding: 4px 4px 4px 20px; border: 1px solid #9b9b9b;}\
  67. .suminfo {}\
  68. .suminfo-info{background: url("http://img11.hostingpics.net/pics/344354iconinfov3.png") no-repeat scroll 2px center / 14px auto #ababab}\
  69. .suminfo-bet{background: url("http://img15.hostingpics.net/pics/666500Dice.png") no-repeat scroll 2px center / 16px auto #ababab}\
  70. a .suminfo-info:hover { background: url("http://img11.hostingpics.net/pics/344354iconinfov3.png") no-repeat scroll 2px center / 14px auto #D7D7D7; transition: 0.5s; opacity: 0.9;}\
  71. a .suminfo-bet:hover { background: url("http://img15.hostingpics.net/pics/666500Dice.png") no-repeat scroll 2px center / 16px auto #D7D7D7; transition: 0.5s; opacity: 0.9;}\
  72. .feedloading {background: url("http://img4.hostingpics.net/pics/356667712.gif") no-repeat scroll 3px center transparent; height: 30px; width: 30px; display: block; position: absolute; margin-left: 23%; margin-top: 1%;}\
  73. aside#submenu {float:left;opacity: 0.9;border-radius: 0 0 10px;}\
  74. main {padding-right:0;}\
  75. #submenutoggle { background: none repeat scroll 0 0 #252525; float: right; font-size: 30px; height: 40px; opacity: 1; text-align: center; width: 200px; }\
  76. aside#submenu > nav {margin:0}\
  77. #shortsmb { background: none repeat scroll 0 0 #252525; border-radius: 0 0 6px; float: left; font-size: 20px; opacity: 0.7; padding: 5px 10px 10px 5px; text-align: center;}\
  78. #shortsmblink { color: #ff8a00;}\
  79. .matchloading { background: url("http://img4.hostingpics.net/pics/5276773011.gif") no-repeat scroll 0 0 / 40px auto #cbcbcb; border-radius: 20px; height: 40px; left: 2%; margin: 5px; opacity: 0.6; width: 40px; }\
  80. .matchloading-ctn { float: left; height: 50px; margin: 5px; position: absolute; width: 50px; }\
  81. #infobox-wrapper { background: none repeat scroll 0 0 #eee; border-radius: 5px 5px 0 0; bottom: 0; opacity: 0.9; padding: 15px 15px 10px; position: fixed; right: 50px; width: 430px; }\
  82. .infobox-ctn { background: none repeat scroll 0 0 #fff; border: 1px solid #ccc; border-radius: 3px; padding: 10px; text-align: center; }\
  83. #settings-aliases {padding:5px 0;}\
  84. label { margin-left: 5px; float:right; font-size: 8px;background: none repeat scroll 0 0 rgb(138, 138, 138); border-radius: 14px; box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1) inset, 0 -1px 0 0 rgba(0, 0, 0, 0.1) inset; color: #fff; cursor: pointer; display: inline-block; font-style: normal; font-weight: bold; height: 20px; line-height: 20px; position: relative; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1); transition: all 1s ease-in 0s; width: 50px; } \
  85. label i { background: none repeat scroll 0 0 rgb(255, 255, 255); border-radius: 20px; box-shadow: 0 -3px 3px 0 rgba(0, 0, 0, 0.1) inset, 0 -1px 1px 0 rgba(255, 255, 255, 0.4) inset, 0 2px 0 0 rgba(0, 0, 0, 0.2); display: block; height: 20px; position: absolute; right: 30px; top: 0px; transition: all 100ms ease 0s; width: 20px;} \
  86. label i:before { background: none repeat scroll 0 0 rgb(239, 239, 239); border-radius: 12px; box-shadow: 0 1px 0 0 rgba(0, 0, 0, 0.1) inset; content: ""; display: block; height: 8px; left: 50%; margin: -4px 0 0 -4px; position: absolute; top: 50%; width: 8px;} \
  87. label:active i:before { box-shadow: inset 0 1px 0 0 rgba(0, 0, 0, 0.3); } \
  88. label:before { content: "off"; margin-left: 20px; text-transform: uppercase; transition: all 200ms ease; } \
  89. input[type=checkbox]:checked ~ label:before { content: "on"; text-transform: uppercase; margin-right: 30px; margin-left: 5px; } \
  90. input[type=checkbox]:checked ~ label{ background: rgb(141,173,51); background: radial-gradient(center, ellipse cover, rgba(141,173,51,1) 0%, rgba(146,178,55,1) 24%, rgba(157,187,64,1) 55%, rgba(166,194,78,1) 100%); } \
  91. input[type=checkbox]:checked ~ label i { right: 0px; } \
  92. input[type=checkbox] { display:none; }\
  93. .matchmain { text-shadow: 0 1px 1px #ffffff; }\
  94. .match {box-shadow:1px 2px 2px 2px #888;}\
  95. .title { color: #999; float: left; position: relative; width: 98%;padding: 1% 1% 0;margin-left:0;text-transform: none;} \
  96. .title:hover a {color: #999; text-shadow: none;}\
  97. .title a{ color: #999; text-shadow: none;} \
  98. #mainheader a:hover{ color: #777; text-shadow: none;} \
  99. #mainheader { font-weight: 300; line-height: 16px;min-height: 40px;float:left; color: #777;font-size: 12px;width: 100%;border: 1px solid #ccc;}\
  100. #mainheader .nomatchesfound {text-align:center;}\
  101. #mainheader li { margin: 3px; padding: 2px;}\
  102. .mainheader-c {}\
  103. .bets-header {background:url("http://cdn.csgolounge.com/img/bets.png") no-repeat;}\
  104. .mh-boxes {}\
  105. .mh-left {width:20%;float:left;padding:2px;}\
  106. .mh-center {width:50%;padding: 0 2px; margin:0 auto; text-align:center;max-height: 90px;}\
  107. .mh-right {width:175px;float:right;padding: 0 2px;}\
  108. #matchescount li {margin: 3px 0 0;}\
  109. #current-matchescount {font-weight:bold;}\
  110. li.sticker { background: none repeat scroll 0 0 #e0e0e0; border-radius: 3px; box-shadow: 1px 1px 1px 1px #ccc; text-shadow: 0 1px 0px #fff;} \
  111. .austatus { font-weight: bold; text-align: center;}\
  112. .austatus-inner { font-weight: normal; text-align:left; margin-top: 5px;}\
  113. .numofm {font-weight:bold;}\
  114. .au-lasttime { float:right; font-weight:bold;color: #8a8a8a;}\
  115. .au-timeleft { float:right; font-weight:bold;color: #8a8a8a;}\
  116. .scriptinfo-header {}\
  117. #scriptinfo-box {font-size:12px;opacity:0.9;overflow-y:auto; max-height:80px}\
  118. #scriptinfo-box .linfo {background: url("http://img15.hostingpics.net/pics/169315info16x16.png") no-repeat 2px center scroll rgba(0, 0, 0, 0);}\
  119. #scriptinfo-box .lwarning {background: url("http://img15.hostingpics.net/pics/701001warning16x16.png") no-repeat 2px center scroll rgba(0, 0, 0, 0);}\
  120. #scriptinfo-box .lerror {background: url("http://img15.hostingpics.net/pics/477689error16x16.png") no-repeat scroll 2px center rgba(0, 0, 0, 0);}\
  121. .timenow {float: left; margin-left: 20px;}\
  122. .matchheader { background: #ccc; border-radius: 10px; border-top: 1px solid #ccc; float: left; font-size: 12px; line-height: 12px; margin-bottom: 4px; text-shadow: 1px 1px 0 #e5e5e5; color: #555;}\
  123. .timeleft { color: #666; font-size: 13px; font-weight:bold}\
  124. .timeRaw {font-size: 10px;}\
  125. .eventm { color: #333; float: right; font-size: 12px; }\
  126. .matchheader-spacer:after { content: "|"; }\
  127. .matchheader span { float: left;} \
  128. .matchheader-spacer { color: #777; font-size: 6px; margin: 0 10px; }\
  129. .matchstatus .matchislive {color: #72A326; text-shadow: 1px 1px 0px #4A7010; font-weight: bold;font-size: 12px;}\
  130. .matchstatus .matchisclosed {font-weight: bold; color: #D12121;font-size: 12px;}\
  131. #force-refresh-ctn {float:right;}\
  132. #force-refresh-ctn .fr-loading{ background-image: url("http://img15.hostingpics.net/pics/932558refreshanim.gif"); background-size: 16px auto; display: block; height: 16px; width: 16px; }\
  133. #force-refresh-ctn .fr-notloading{ background-image: url("http://img15.hostingpics.net/pics/707861refreshfixed.png"); background-size: 16px auto; display: block; height: 16px; width: 16px;}\
  134. ');
  135. // Grey scheme: Foreground color = #333333 // Background color = #bbbbbb
  136.  
  137. var scriptVersion = GM_info.script.version;
  138. //console.log(version);
  139. var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
  140. console.log('@Greasemonkey/@Tampermonkey settings:', GM_info);
  141. console.log('@JQuery: ', $.fn.jquery);
  142. console.log('@CSGLounge Live version:', scriptVersion);
  143.  
  144. // Global settings
  145. var settings = {
  146. "debug": {
  147. "global": false, // activates _log
  148. "feeds": "0",
  149. "autoUpdate": true // activate detailed autoupdate logging
  150. },
  151. "matchBoxStatus": "0", // Main view, boxes open, closed. feature disabled.
  152. "mainMenuStatus": "0", // 1 Show, 0 Hide main menu
  153. "updateDelay": "300000", // 5 mins = 300 seconds (*1000)
  154. "defaultTimeout": "10000", // 10 seconds
  155. "switches": {
  156. "completeinit": true,
  157. "feeds": true,
  158. "autoupdate": true
  159. },
  160. "isNewVersion": {
  161. "oldVersion": "",
  162. "newVersion": "",
  163. "status": false
  164. }
  165. };
  166. // debug (forces settings rewrite)
  167. //localStorage.setItem("csglLiveSettings", JSON.stringify(settings));
  168.  
  169. /* Check for a newer version not elegant at all, will do that in a proper way later*/
  170. var scriptVersionChecker = (localStorage.getItem('csgllive_lastversion') != scriptVersion);
  171. if (scriptVersionChecker) {
  172. var currentVersion = localStorage.getItem('csgllive_lastversion');
  173. localStorage.setItem("csgllive_lastversion", scriptVersion);
  174. settings.isNewVersion.oldVersion = currentVersion;
  175. settings.isNewVersion.newVersion = scriptVersion;
  176. settings.isNewVersion.status = true;
  177. localStorage.removeItem("csglLiveSettings");
  178. localStorage.setItem("csglLiveSettings", JSON.stringify(settings));
  179. }
  180.  
  181. var globalJobStatus = []; // global status for job to track if they are finished or not.
  182. var globalData = {};
  183. if (localStorage.getItem("csglLiveSettings") !== null) {
  184. settings = JSON.parse(localStorage.getItem("csglLiveSettings"));
  185. console.log('@CSGLounge Live settings:', localStorage.getItem('csglLiveSettings'));
  186. }
  187.  
  188.  
  189. // get base url in ff.
  190. if (!is_chrome) {
  191. var baseUrl = window.location.href;
  192. var regexp = /.*\/(.*?)$/;
  193. var match = regexp.exec(baseUrl);
  194. if (match[1] === '#') {
  195. var baseUrl = baseUrl.replace('#', '');
  196. }
  197. } else {
  198. var baseUrl = "http://csgolounge.com/";
  199. }
  200.  
  201. /*********************/
  202. /* DEBUG AND HELPERS */
  203. /*********************/
  204. // debug log if activated
  205. if (!is_chrome) {
  206. _log = (function (undefined) { // if firefox
  207. var Log = Error; // proper inheritance...?
  208. Log.prototype.write = function (args) {
  209.  
  210. var lineNum = extractLineNumberFromStack(this.stack);
  211. var lineNumberStr = [[lineNum]];
  212. args = args.concat(lineNumberStr);
  213. args = sortArray(args);
  214. // console.log(args);
  215. if (console && console.log) {
  216. if (console.log.apply) {
  217. console.log.apply(console, args);
  218. } else {
  219. console.log(args);
  220. } // nicer display in some browsers
  221. }
  222. };
  223. var extractLineNumberFromStack = function (stack) {
  224.  
  225. var lineNum = stack.split('\n')[1];
  226. var lineNum = lineNum.split(' (')[0].substring(0, lineNum.length - 1);
  227. var lineNum = lineNum.split(':')[3].substring(0, lineNum.length - 1);
  228. return lineNum;
  229. };
  230. var sortArray = function (arrayTosort) { // swap 1st and last value.
  231. argsNew = [];
  232. for (var i = 0; i < arrayTosort.length; i++) {
  233. var j = i + 1;
  234. argsNew[j] = arrayTosort[i];
  235. }
  236.  
  237. var lastItem = argsNew.pop();
  238. argsNew[0] = lastItem;
  239. return argsNew;
  240. };
  241. return function (params) {
  242.  
  243. if (typeof settings.debug.global !== undefined || settings.debug.global)
  244. return;
  245. Log().write(Array.prototype.slice.call(arguments, 0));
  246. };
  247. })();
  248. } else {
  249. _log = function (args) {
  250. console.log(args);
  251. };
  252. }
  253. pLog = _log;
  254. auLog = function (args) {
  255. // console.log(['AU:'],' ', args);
  256. console.log(['AU:'], ' ', Array.prototype.slice.call(arguments, 0));
  257. };
  258. /* log tool */
  259. window.log = function () {
  260. log.history = log.history || []; // store logs to an array for reference
  261. log.history.push(arguments);
  262. if (this.console && settings.debug.global) {
  263. console.log(Array.prototype.slice.call(arguments));
  264. }
  265. };
  266. l = function (args) {
  267. console.log(args);
  268. };
  269. _l = function (args) {
  270. console.log(args);
  271. };
  272.  
  273. /****************/
  274. /* SCRIPT START */
  275. /****************/
  276. /* Global Class - wrap basically every workers jobs - process detailled below... */
  277. function globalClass(worker) {
  278. var self = this;
  279. this.worker = worker;
  280. this.job = {};
  281. this.job.init = true;
  282. this.job.done = false;
  283. this.job.update = false;
  284. this.job.retrieveMissing = false;
  285. this[this.worker] = {"data": []};
  286. console.log("Initializing INSTANCE for worker", this.worker, '', this[this.worker]);
  287. // matches ajax req errors & loading
  288. this.loading = {};
  289. this.loading.matchdiv = '<div class="matchloading-ctn"><div class="matchloading"></div></div>';
  290. // If error on retrieve is returned by matches ajax request: // errors.JOB.STRING
  291. this.errors = {};
  292. this.errors.match = {};
  293. this.errors.feeds = {};
  294. this.errors.match.toAppendFirstPart = '<div class="detailsbox error">There was an error retrieving the data (';
  295. this.errors.match.toAppendLastPart = ')...<a href="#" class="maindata-retrieve">Retrieve manually</a></div>';
  296. this.errors.match.aborted = this.errors.match.toAppendFirstPart + 'Aborted' + this.errors.match.toAppendLastPart;
  297. this.errors.match.timedOut = this.errors.match.toAppendFirstPart + 'Timed out' + this.errors.match.toAppendLastPart;
  298. this.errors.match.error = this.errors.match.toAppendFirstPart + 'Error' + this.errors.match.toAppendLastPart;
  299. this.errors.match.RetrieveFailedMatches = " item(s) failed to load. <a href='#' class='retrieve-failedmatches'>Retrieve missing item(s)</a> ";
  300. this.errors.feeds.timeout = "Feeds api didn't respond in time, please try again in one minute...";
  301. this.errors.feeds.abort = "Abort error, please try again later...";
  302. this.errors.feeds.errors = "There was an error, feeds api might be empty at the moment, please try again later...";
  303. this.liveNow = '<span class="matchislive">&nbsp; Live !</span>';
  304. this.feeds = {
  305. "data": [
  306. "reddit", "hltv"
  307. ],
  308. "feedsDatas": {
  309. "reddit": {
  310. "url": "https://vast-harbor-8484.herokuapp.com/api?feed=reddit",
  311. "datas": ""
  312. },
  313. "hltv": {
  314. "url": "https://vast-harbor-8484.herokuapp.com/api?feed=hltv",
  315. "datas": ""
  316. }
  317. }
  318. };
  319. this.feedbox = '<section id="feedsbox"><div class="title"><div id="secondheader" class="feeds-header mainheader-c">&nbsp;<div class="feedbox-title-inner"><strong>Feeds</strong> </div></div></div></section>';
  320. this.propsContainers = {
  321. "bestOf": ".infosbelow-center",
  322. "dateRaw": ".dateRaw",
  323. "ipstatus": "",
  324. "itemplaced": "",
  325. "mainstream": "",
  326. "matchNameA": ".teamtext:eq(0) b",
  327. "matchNameB": ".teamtext:eq(1) b",
  328. "msstatus": "",
  329. "peopleItemsNum": ".peopleItemsNum",
  330. "teamAReward": ".infosbelow-lr span:eq(0)",
  331. "teamAperc": ".teamtext:eq(0) i",
  332. "teamBReward": ".infosbelow-lr span:eq(1)",
  333. "teamBet": "",
  334. "teamBperc": ".teamtext:eq(1) i",
  335. "timeLeft": ".timeleft",
  336. "timeRaw": ".timeRaw",
  337. "valueBetA": "",
  338. "valueBetB": ""
  339. };
  340. // build an array containing all properties.
  341. var buildPropList = function (propsContainers) {
  342. var propsList = [];
  343. for (var properties in propsContainers) {
  344. propsList.push(properties);
  345. }
  346. return propsList;
  347. };
  348. this.propList = buildPropList(this.propsContainers);
  349. this.arrow = {};
  350. this.arrow.up = '<span style="color: green;">&#8593;</span>';
  351. this.arrow.down = '<span style="color: red;">&#8595;</span>';
  352. this.arrow.equal = '&nbsp;';
  353. this.arrow.err = '&nbsp;';
  354. } /* ! globalClass(worker)*/
  355.  
  356.  
  357. globalClass.prototype.initGlobalProcess = function () {
  358. _log('*** Global INIT for worker ' + this.worker + ' ***');
  359. var dfd = new jQuery.Deferred();
  360. return dfd.resolve(this);
  361. }; // !initGlobalProcess
  362.  
  363. /*
  364. * monitorWorker method
  365. * @param {type} jobStatus = error || success
  366. * @param {type} container
  367. * @param {type} jobType = view || request
  368. * @param {type} id
  369. * @param {type} errorType = error details - eq. timeout, abort etc...
  370. * @feedsObj :
  371. loadingStatus.
  372. "index": 0,
  373. "totalItemsToLoad": dataLength,
  374. "globalMonitor": {
  375. "error": {"view" : 0, "request" : 0, "IDs" : [], "ctn" : []},
  376. "success": {"view" : 0, "request" : 0, "IDs" : [], "ctn" : []},
  377. "mustRetry": []
  378. }
  379. */
  380. globalClass.prototype.monitorWorker = function (jobStatus, jobType, container, id, errorType) { // jobStatus = error || success, jobType = view || request, errorType = error details - eq. timeout, abort etc...
  381. _log('... currently monitoring "' + this.worker + '" worker ...');
  382. // monitor global responses status to count how many succeed and failed.
  383. var globalMonitor = this[this.worker].loadingStatus.globalMonitor; // example. this.initialization.loadingStatus.globalMonitor
  384. // console.log('MONITOR', globalMonitor[jobStatus][jobType], jobType)
  385.  
  386. globalMonitor[jobStatus].IDs.push(id);
  387. globalMonitor[jobStatus].ctn.push(container);
  388. globalMonitor[jobStatus][jobType]++; // example. currentObj.success.view = 6.
  389.  
  390. if (jobType === "view") { // update loading status when append are done.
  391. this[this.worker].loadingStatus.index = (++this[this.worker].loadingStatus.index);
  392. }
  393. // if(jobStatus === "error") { // send error to errorHandling method
  394. // this.errorHandling(jobStatus, jobType, container, id, "global");
  395. // }
  396.  
  397. };
  398. globalClass.prototype.errorHandling = function (jobStatus, jobType, container, id, errorType) {
  399. var globalMonitor = this[this.worker].loadingStatus.globalMonitor; // example. this.initialization.loadingStatus.globalMonitor
  400.  
  401. if (this.worker === "initialization" && jobType === "request") { // error
  402. $('#scriptinfo-box').prepend('<li class="lerror sticker"><span class="timenow">' + this.tools() + '</span>An error occured (' + errorType + ') while requesting match #' + id + '.</li>');
  403. container.find('.matchloading-ctn').remove();
  404. container.append(this.errors.match[errorType]);
  405. }
  406.  
  407. if (errorType === "done") {
  408. $('#scriptinfo-box').prepend('<li class="lerror sticker"><span class="timenow">' + this.tools() + '</span>' + globalMonitor.error.request + this.errors.match.RetrieveFailedMatches);
  409. }
  410.  
  411. };
  412. globalClass.prototype.done = function () {
  413. console.log('ALLDONE: worker ', this.worker, ' has finished his jobs. obj:', this);
  414. var globalMonitor = this[this.worker].loadingStatus.globalMonitor; // example. this.initialization.loadingStatus.globalMonitor
  415.  
  416. // init is done
  417. if (this.worker === "initialization" && this.job.init && !this.job.retrieveMissing) {
  418. // store data in globalData obj
  419. globalData.currentData = {};
  420. globalData.currentData = this[this.worker].data;
  421. // check for errors
  422. if (globalMonitor.error.request > 0) {
  423. this.errorHandling("error", "", "", "", "done");
  424. }
  425. if (globalMonitor.error.request === 0) {
  426. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + this.tools() + '</span> ' + this.worker + ' done successfully.');
  427. }
  428. if (settings.isNewVersion.status) {
  429. if (currentVersion === null) {
  430. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + this.tools() + '</span> Welcome to CSGL Live version ' + scriptVersion + ', everything loaded successfully. Enjoy !</li>');
  431. } else {
  432. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + this.tools() + '</span> CSGL Live has updated from version ' + currentVersion + ' to ' + scriptVersion + ' successfully.</li>');
  433. settings.isNewVersion.status = false;
  434. localStorage.setItem("csglLiveSettings", JSON.stringify(settings));
  435. }
  436.  
  437. }
  438. }
  439. var dfd = new jQuery.Deferred();
  440. return dfd.resolve(this);
  441. };
  442. globalClass.prototype.initPageView = function () {
  443. _log('*** init Page View ***');
  444. var self = this;
  445. /* MAIN STYLE*/
  446. var mainStyle = $('head link[type="text/css"]').attr('href');
  447. if (typeof mainStyle != "undefined") {
  448. var mainStyle = mainStyle.replace(/\d+$/, '');
  449. if (mainStyle != '//cdn.csgolounge.com/css/gray.min.css?') {
  450. $.ajax({
  451. method: 'GET',
  452. url: 'ajax/setSkin?skin=1',
  453. success: function (response) {
  454. console.log(response);
  455. }
  456. });
  457. $('head link[type="text/css"]').attr('href', "//cdn.csgolounge.com/css/gray.min.css?");
  458. }
  459. }
  460. // logo
  461. $('body').find('header a:eq(0)').html('<img id="logo" alt="CS:GO Marketplace" src="http://img11.hostingpics.net/pics/797445csgllivelogo4.png">');
  462. /*
  463. * http://img11.hostingpics.net/pics/797445csgllivelogo4.png
  464. * http://img11.hostingpics.net/pics/501830csgllivelogo.png
  465. * http://img11.hostingpics.net/pics/926464csgllivelogo2.png
  466. * http://img11.hostingpics.net/pics/357697csgllivelogo3.png
  467. */
  468.  
  469. // Main view, boxes open, closed.
  470. if (settings.matchBoxStatus === '0') {
  471. // localStorage.setItem('matchBoxStatus', settings.matchBoxStatus);
  472. initialization.matchBoxStatus = ' style="display:none;"';
  473. var btnMatchBoxStatus = '+';
  474. } else if (settings.matchBoxStatus === '1') {
  475. // localStorage.setItem('matchBoxStatus', settings.matchBoxStatus);
  476. initialization.matchBoxStatus = ' style="display:block;"';
  477. initialization.btnMatchBoxStatus = '-';
  478. } else {
  479. initialization.matchBoxStatus = ' style="display:block;"';
  480. }
  481.  
  482. // hide main trade box
  483. $('#tradelist').parent().hide();
  484. $('#tradelist').hide();
  485. // Hide not available, add button
  486. var firstna = $('.matchmain .notavailable:first').parent();
  487. firstna.nextAll().andSelf().wrapAll("<div id='sh-na' style='display:none;'></div>")
  488. .parent().before('<a href="#" class ="shownotav-btn shownotav"><span>Show closed matches</span></a>');
  489. $("body").on("click", "a.shownotav-btn", function (e) {
  490. $('a.shownotav-btn').remove();
  491. $('#sh-na').slideDown('slow');
  492. e.preventDefault();
  493. });
  494. // Page Header
  495. $('.title, #bets').removeAttr('style');
  496. //matchheader
  497. $('.title:eq(1)').html('<div id="mainheader" class="bets-header mainheader-c"></div>');
  498. $('#mainheader').append('<div class="mh-boxes mh-left"><ul></ul> </div>');
  499. $('#mainheader').append('<div class="mh-boxes mh-right"><ul></ul></div></div>');
  500. $('#mainheader').append('<div class="mh-boxes mh-center"><ul id="scriptinfo-box"></ul></div>');
  501. $('.mh-left ul').append('<li class="sticker matchesav"></li>');
  502. if (settings.switches.autoupdate) {
  503. $('.mh-left ul').append('<li class="sticker austatus"><ul class="austatus-title"><li>Auto-Update Status<span id="force-refresh-ctn"><a id="force-refresh" class="fr-notloading" title="Force a page refresh"href="#"></a></span></li></ul><span class="austatus-inner"><ul><li>Last update: <span class="au-lasttime">-</span></li><li>Next update in: <span class="au-timeleft">-</span></li></ul></span>');
  504. }
  505. $('.mh-center').prepend('<span class="scriptinfo-header">CS:GL Live version: ' + scriptVersion + ' <a href="#">reddit</a> - <a target="_blank" href="https://steamcommunity.com/tradeoffer/new/?partner=81839980&token=VqSHKQT0" title="support the cause !">steam donation</a></span>');
  506. //matchheader
  507. $('.mh-right ul').append('<li>Matches Infos: <input type="checkbox" id="completeinit-switch" /> <label for="completeinit-switch" > <i></i> </label></li>');
  508. $('.mh-right ul').append('<li>Feeds: <input type="checkbox" id="feeds-switch" /> <label for="feeds-switch" > <i></i> </label></li>');
  509. $('.mh-right ul').append('<li>Auto Update: <input type="checkbox" id="autoupdate-switch" /> <label for="autoupdate-switch"> <i></i> </label></li>');
  510. // Switches status
  511. $('#completeinit-switch').attr('checked', settings.switches.completeinit);
  512. $('#feeds-switch').attr('checked', settings.switches.feeds);
  513. $('#autoupdate-switch').attr('checked', settings.switches.autoupdate);
  514. $("#mainheader").on("click", "input#completeinit-switch", function (e) {
  515. if ($('input#completeinit-switch').is(":checked")) {
  516. settings.switches.completeinit = true;
  517. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Matches infos have been activated.</li>');
  518. } else {
  519. if (settings.switches.autoupdate) {
  520. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Auto update disable have been forced.</li>');
  521. }
  522. settings.switches.completeinit = false;
  523. settings.switches.autoupdate = false;
  524. $('#autoupdate-switch').attr('checked', settings.switches.autoupdate);
  525. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Matches infos have been disabled.</li>');
  526. }
  527. localStorage.setItem("csglLiveSettings", JSON.stringify(settings));
  528. });
  529. $("#mainheader").on("click", "input#feeds-switch", function (e) {
  530. settings.switches.feeds = $('input#feeds-switch').is(":checked") ? true : false;
  531. localStorage.setItem("csglLiveSettings", JSON.stringify(settings));
  532. if (!settings.switches.feeds) {
  533. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Feeds have been disabled.</li>');
  534. }
  535. if (settings.switches.feeds) {
  536. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Feeds have been activated.</li>');
  537. }
  538. });
  539. $("#mainheader").on("click", "input#autoupdate-switch", function (e) {
  540. if ($('input#completeinit-switch').is(":checked") === false) {
  541. $('#autoupdate-switch').attr('checked', false);
  542. alert('Turn on "matches infos" first.');
  543. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Please turn on matches infos first if you want to enable auto-update.</li>');
  544. } else {
  545. settings.switches.autoupdate = $('input#autoupdate-switch').is(":checked") ? true : false;
  546. localStorage.setItem("csglLiveSettings", JSON.stringify(settings));
  547. if (!settings.switches.autoupdate) {
  548. clearInterval(window.autoUpdate);
  549. clearInterval(window.autoUpdateTimer);
  550. $('.au-timeleft').html('-');
  551. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Auto update has just been stopped and disabled.</li>');
  552. }
  553. if (settings.switches.autoupdate) {
  554. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Auto update has been activated, please refresh the page to initialize it.</li>');
  555. }
  556. }
  557.  
  558.  
  559. });
  560. // Big Main Switch Button
  561. //$('#mainheader').append('<div id="switchmainview"><a href="#" id="switchmainviewa" class="rounded-btn1"><span>' + btnMatchBoxStatus + '</span></a></div>')
  562.  
  563. $("#switchmainview").on("click", "a#switchmainviewa", function (e) {
  564. $(".detailsbox").slideToggle("fast", function () {
  565. $("#switchmainviewa span").text($('.detailsbox').is(':visible') ? "-" : "+");
  566. });
  567. e.preventDefault();
  568. });
  569. // Boxes expander
  570. $("#bets").on("click", "a.expandmatch-btn-a", function (e) {
  571. var $alinktext = $(e.target);
  572. var $detailsbox = $(e.target).parents().eq(2).find('.detailsbox');
  573. $detailsbox.slideToggle("fast", function () {
  574. $alinktext.text($detailsbox.is(':visible') ? "-" : "+");
  575. });
  576. e.preventDefault();
  577. });
  578. // SubMenu
  579. $('aside#submenu').prepend('<a id="submenutoggle"><span href="#" id="submenutogglelink">&#8592;</span></a>');
  580. $("#submenu").after('<a id="shortsmb" style="display:none;"><span id="shortsmblink" href="#">&#8600;</span></a>');
  581. if (settings.mainMenuStatus == '0') {
  582. $('aside#submenu').hide();
  583. $('#shortsmb').show();
  584. }
  585.  
  586. $("body").on("click", "a#shortsmb", function (e) {
  587. $('#shortsmb').hide('fast');
  588. $("aside#submenu").show("slide");
  589. settings.mainMenuStatus = '1';
  590. localStorage.setItem("csglLiveSettings", JSON.stringify(settings));
  591. });
  592. $("#submenu").on("click", "a#submenutoggle", function (e) {
  593. $("aside#submenu").hide("slide", function () {
  594. $('#shortsmb').show();
  595. settings.mainMenuStatus = '0';
  596. localStorage.setItem("csglLiveSettings", JSON.stringify(settings));
  597. });
  598. });
  599. // Error link when a matchbox has failed to retrieve matchInfos
  600. // NOTE: USE initialization worker FOR THIS
  601. $(".match").on("click", "a.maindata-retrieve", function (e) {
  602. self.job.retrieveMissing = true;
  603. self.job.init = false;
  604. var selector = $(this).closest('.matchmain');
  605. selector.find('.error').remove();
  606. CompleteInitialization.call(self, self.worker, selector);
  607. e.preventDefault();
  608. });
  609. $("#error-matchesload").on("click", "a.retrieve-failedmatches", function (e) {
  610. var selector = self[self.worker].loadingStatus.globalMonitor.error.ctn;
  611. $('#error-matchesload').empty();
  612. $(selector).each(function (index, value) {
  613. value.find('.error').remove();
  614. });
  615. CompleteInitialization.call(self, this.worker, selector);
  616. e.preventDefault();
  617. });
  618. $("#force-refresh-ctn").on("click", "a#force-refresh", function (e) {
  619. console.log('refreshing auto update..');
  620. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Forcing a page refresh...</li>');
  621. $('#force-refresh').removeClass('fr-notloading').addClass('fr-loading');
  622. // clearInterval(window.autoUpdate);
  623. // clearInterval(window.autoUpdateTimer);
  624. // self.autoUpdateTimers();
  625. // UpdateInitialization();
  626. // window.autoUpdate = setInterval(function () {
  627. // self.autoUpdateTimers();
  628. UpdateInitialization();
  629. // }, settings.updateDelay);
  630. e.preventDefault();
  631. });
  632. // infobox
  633. $('main').append('<div id="infobox-wrapper" style="display: none;"><div class="infobox-ctn"></div></div>');
  634. // show trades
  635. $('#menu').append('<a href="#" class="showtrades"><img alt="Show trades" src="//cdn.csgolounge.com/img/my_trades.png">Show trades</a>');
  636. $("#menu").on("click", "a.showtrades", function (e) {
  637. $('.box:eq(1)').toggle(); // matchbox
  638. $('.box:eq(0)').fadeToggle('slow'); // trade box
  639. $('.box:eq(0) #tradelist').toggle(); // tradebox inner
  640. e.preventDefault();
  641. });
  642. // arrows containers
  643. var matchmainCtn = $('body').find('.matchmain .match').not('.notavailable').parent();
  644. $.each(matchmainCtn, function (i, v) {
  645.  
  646. var teamTextA = $(v).find('.teamtext').eq('0');
  647. var teamTextB = $(v).find('.teamtext').eq('1').find('i');
  648. teamTextA.append('<span class="arrow-teama"></span>');
  649. teamTextB.before('<span class="arrow-teamb"></span>');
  650. });
  651. _log('-init page view done.');
  652. var dfd = new jQuery.Deferred();
  653. return dfd.resolve(this);
  654. };
  655. /* Loop through dom .matchmain and retrieve infos */
  656. globalClass.prototype.parseMainPage = function (selector, rawData) {
  657. _log('*** parse Main Page ***');
  658. var data = (typeof rawData !== "undefined") ? rawData : 'body';
  659. if (typeof selector !== 'undefined' && selector !== "") {
  660. var matchesCtn = selector;
  661. } // If user has clicked to manually retrieve infos of a specific match
  662. else {
  663. var matchesCtn = $(data).find('.matchmain .match').not('.notavailable').parent();
  664. } //if not, selector is every match available on the page
  665. var csgl = {"data": []}; // global object, containing basically every data for every match.
  666.  
  667. if (matchesCtn.length >= 1) { // iterate through every matchmain box, find data, store it in csgl obj.
  668. $(matchesCtn).each(function (index, value) {
  669.  
  670. var matchUrlDest = $(this).find('a').attr('href');
  671. var matchId = matchUrlDest.replace('match?m=', '').replace("predict?m=", "");
  672. var matchUrl = baseUrl + matchUrlDest;
  673. var matchCtn = $(this).find('a[href="match?m=' + matchId + '"]').closest('.match');
  674. var matchPercA = $(this).find('a[href="match?m=' + matchId + '"] div.teamtext:eq(0) i').text();
  675. var matchPercB = $(this).find('a[href="match?m=' + matchId + '"] div.teamtext:eq(1) i').text();
  676. var matchNameA = $(this).find('a[href="match?m=' + matchId + '"] div.teamtext:eq(0) b').text();
  677. var matchNameB = $(this).find('a[href="match?m=' + matchId + '"] div.teamtext:eq(1) b').text();
  678. matchCtn.append('<div class="matchloading-ctn"><div class="matchloading"></div></div>'); // init loading display
  679.  
  680. var csglMatchData = {
  681. matchUrl: matchUrl,
  682. matchId: matchId,
  683. matchCtn: matchCtn,
  684. teamAperc: matchPercA,
  685. teamBperc: matchPercB,
  686. matchNameA: matchNameA,
  687. matchNameB: matchNameB
  688. };
  689. csgl.data.push(csglMatchData);
  690. }); // matches basic data retrieving has finished.
  691.  
  692. this[this.worker].data = csgl.data; // Obj = this.worker.data[matches]
  693.  
  694. // success
  695. _log('-parseMainPage success', this[this.worker].data);
  696. var dfd = new jQuery.Deferred();
  697. return dfd.resolve(this);
  698. } else {
  699. // escaped
  700. _log('parseMainPage escaped, no matches found'); // No matches has been found, append a message and retrieve the feed
  701. // updateLoading('', '1'); // Set progress bar to 100%
  702. $('#mainheader').append('<div class="nomatchesfound"><br />There are currently no matches to bet on ! ;( <br /> Try checking later...</div>');
  703. }
  704.  
  705. };
  706. // gather and append global infos
  707. globalClass.prototype.globalInfos = function () {
  708. _log('*** global infos ***');
  709. var numberOfMatchesS = $('body').find('.matchmain .match').not('.notavailable').parent().length; // ??!
  710.  
  711. var dfd = new jQuery.Deferred();
  712. return dfd.resolve(this);
  713. };
  714. globalClass.prototype.initLoading = function () { // init loading
  715. _log('... Init Loading ...');
  716. console.log("obj this[this.worker]:", this.worker, this[this.worker]);
  717. var data = this[this.worker].data;
  718. if (data === "undefined" || data === 0) {
  719. dataLength = 1;
  720. }
  721.  
  722. if (typeof data === "object") {
  723. var dataLength = (Object.getOwnPropertyNames(data).length) - 1;
  724. } // USEFUL 'TILL I FIX THE WORKER OBJ FORMAT ?
  725. else {
  726. var dataLength = data.length;
  727. }
  728.  
  729. this[this.worker].loadingStatus = {// loading vars
  730. "index": 0,
  731. "totalItemsToLoad": dataLength,
  732. "globalMonitor": {
  733. "error": {"view": 0, "request": 0, "IDs": [], "ctn": []},
  734. "success": {"view": 0, "request": 0, "IDs": [], "ctn": []},
  735. "mustRetry": []
  736. } // index to monitor how many ajax requests succeed
  737. };
  738. // VIEW
  739. if (this.worker === "feeds") { // append feeds container and init loading gif
  740. $('main').append(this.feedbox);
  741. $.each(data, function (index, value) {
  742. $('main #feedsbox').append('<article id="' + value + 'feed-ctn" class="feeds standard"> <div class="main-feedbox" id="' + value + 'feed"><span id="' + value + '-loading" class="feedloading" style="display:none;"></span><div class="feedstitle"> </div> <div class="feedslinks-box"><ul></ul></div> </div> </article>');
  743. });
  744. $('.feedloading').fadeIn('fast');
  745. } else if (this.worker === "initialization" || this.worker === "basicInit") { // matches count and loading bar
  746. if ($('#matchescount').length === 0) {
  747. $('#mainheader .mh-center ul').append('<li id="matchescount">loading: <span id="current-matchescount">0</span> / <span id="total-matchescount"></span></li>');
  748. $('#mainheader .mh-center ul').append('<li id="mainloadingbar"><div class="progress"><span style="width: 0%;"><span>0%</span></span></div></li>');
  749. }
  750. // matchescount
  751. var numberOfMatchesS = $('body').find('.matchmain .match').not('.notavailable').parent().length;
  752. $('.matchesav').html('<span class="numofm"> ' + numberOfMatchesS + '</span> matches available.'); // dot = &#149;
  753. $('#mainheader #matchescount #total-matchescount').html(numberOfMatchesS);
  754. } else { // any worker VIEW
  755.  
  756. }
  757. console.log("initloadingEND", this[this.worker].loadingStatus);
  758. var dfd = new jQuery.Deferred();
  759. return dfd.resolve(this);
  760. };
  761. // Ajax requests prototype, do the worker requests, parse the data, return whatever needed
  762. globalClass.prototype.ajaxCalls = function (worker, job, url, id, container, timeout) {
  763. _log('... ajaxCalls ...');
  764. _log("Request sent for worker:", worker, " url: ", url, " id: ", id, " container: ", container);
  765. if (typeof timeout === "undefined") {
  766. timeout = settings.defaultTimeout;
  767. }
  768.  
  769. this.genericCall = function () {
  770. var self = this;
  771. _log('ajax req for: ', worker, ' @: ', url, container);
  772. return $.ajax({
  773. method: 'GET',
  774. url: url,
  775. timeout: timeout,
  776. success: function (data) { // Request complete, parse data
  777. // _log('request complete for: url:', url, ' id: ', id,' container:', container, 'RESULT=', data);
  778. _log("response received for worker:", worker, "url;", url);
  779. },
  780. onabort: function (data) {
  781. _log('onabort error throwed for request=> url:', url, ' id: ', id, ' container:', container, 'RESULT=', data);
  782. },
  783. ontimeout: function (data) {
  784. _log('ontimeout error throwed for request=> url:', url, ' id: ', id, ' container:', container, 'RESULT=', data);
  785. },
  786. onerror: function (data) {
  787. _log('onerror error throwed for request=> url:', url, ' id: ', id, ' container:', container, 'RESULT=', data);
  788. }
  789. });
  790. };
  791. // if (worker === 'initialization' || worker === 'feeds') { // if there are other requests type to add, keep this worker in a condition statement...
  792. return this.genericCall();
  793. // }
  794.  
  795. };
  796. // Global INIT Parse each match page request
  797. globalClass.prototype.parseMatchPageData = function (worker, job, url, id, container, data) {
  798. console.log('*!* parsing... ', id);
  799. _log('... parseMatchPageData ...');
  800. _log('parsing data for url:', url, ' id: ', id, ' container:', container);
  801. var self = this;
  802. var $d = $(data);
  803. var tar = '.box-shiny-alt:eq(0) .full .half:eq(0)';
  804. var tar = $d.find(tar);
  805. var teamAReward = tar.length > 0 ? tar.html().split("<br>")[1] : '';
  806. var tbr = '.box-shiny-alt:eq(0) .full .half:eq(1)';
  807. var tbr = $d.find(tbr);
  808. var teamBReward = tbr.length > 0 ? tbr.html().split("<br>")[1] : '';
  809. var vba = '.box-shiny-alt:eq(0) .full .half:eq(0)';
  810. var vba = $d.find(vba);
  811. var valueBetA = vba.length > 0 ? vba.html().split("<br>")[2] : '';
  812. var vbb = '.box-shiny-alt:eq(0) .full .half:eq(1)';
  813. var vbb = $d.find(vbb);
  814. var valueBetB = vbb.length > 0 ? vbb.html().split("<br>")[2] : '';
  815. var tl = '.box-shiny-alt:eq(0) .half:eq(0)';
  816. var tl = $d.find(tl);
  817. var timeLeft = tl.length > 0 ? tl.text() : '';
  818. var bo = '.box-shiny-alt:eq(0) .half:eq(1)';
  819. var bo = $d.find(bo);
  820. var bestOf = bo.length > 0 ? bo.text() : '';
  821. var t = '.box-shiny-alt:eq(0) .half:eq(2)';
  822. var t = $d.find(t);
  823. var time = t.length > 0 ? t.text() : '';
  824. var d = 'section.box:eq(0) .box-shiny-alt .half:eq(2)';
  825. var d = $d.find(d);
  826. var date = d.length > 0 ? d.attr("title") : '';
  827. var pin = 'section.box:eq(1) div.box-shiny-alt .full:eq(0)';
  828. var pin = $d.find(pin);
  829. var peopleItemsNum = pin.length > 0 ? pin.text() : '';
  830. // var matchDateFull = convertCsglDate(date, time);
  831. // var matchDateHuman = matchDateFull[1];
  832. // var matchDateRobot = matchDateFull[0];
  833.  
  834. // Optional (itemplaced, mainstream)
  835. var ip = '.box-shiny-alt .full:eq(2)';
  836. var tb = '.box-shiny-alt a.active';
  837. if ($d.find(ip).length) {
  838. var itemplaced = $d.find(ip).html();
  839. var teamBet = $d.find(tb).index();
  840. if (teamBet == '1') {
  841. teamBet = 'a';
  842. }
  843. if (teamBet == '3') {
  844. teamBet = 'b';
  845. }
  846. var ipstatus = '1';
  847. } else {
  848. var itemplaced = 'No bet placed.';
  849. var ipstatus = '0';
  850. var teamBet = '0';
  851. }
  852. var ms = '#stream #mainstream';
  853. if ($d.find(ms).length) {
  854. var mainstream = $d.find(ms).html();
  855. var msstatus = '1';
  856. } else {
  857. var mainstream = 'No stream available';
  858. var msstatus = '0';
  859. }
  860.  
  861. $(self[self.worker].data).each(function (index, value) {
  862. if (value.matchId === id) {
  863. value.teamAReward = teamAReward;
  864. value.teamBReward = teamBReward;
  865. value.valueBetA = teamAReward;
  866. value.valueBetB = teamBReward;
  867. value.peopleItemsNum = $.trim(peopleItemsNum);
  868. value.timeLeft = timeLeft;
  869. value.bestOf = bestOf;
  870. value.timeRaw = $.trim(time);
  871. value.dateRaw = date;
  872. // value.matchDateRobot = matchDateRobot;
  873. // value.matchDateHuman = matchDateHuman;
  874. value.ipstatus = ipstatus;
  875. value.itemplaced = itemplaced;
  876. value.teamBet = teamBet;
  877. value.msstatus = msstatus;
  878. value.mainstream = mainstream;
  879. }
  880.  
  881. });
  882. _log(self.worker + ' OBJ: ', self[self.worker]);
  883. // retrieve the object with data for the current "id"
  884. var result = $.grep(self[self.worker].data, function (e) {
  885. return e.matchId == id;
  886. });
  887. var data = result[0];
  888. _log('parseMatchPageData worker', worker, 'done for', url);
  889. var dfd = new jQuery.Deferred();
  890. return dfd.resolve(self, data, this);
  891. // dfd.resolve()
  892. // return dfd.promise(self, data, this);
  893. };
  894. globalClass.prototype.dothestuff = function (a) {
  895. console.log('*#*#* parseData ***');
  896. var xxxx = $.Deferred();
  897. console.log('*#*#* called processItem ***');
  898. xxxx.resolve();
  899. return xxxx.promise();
  900. };
  901. globalClass.prototype.ended = function (a) {
  902. console.log('*#*#* finito! ***');
  903. };
  904. globalClass.prototype.appendEachMatch = function (worker, job, url, id, container, data) {
  905. _log('*** appendEachMatch ***');
  906. // console.log("Appending match #",id, 'data:', data, this);
  907.  
  908. if (typeof (data.teamAReward) !== "undefined" && (data.teamAReward).length > 0) { // todo: und && length var checker
  909. //GATHER INFOS TO APPEND
  910. var nobetplaced = data.ipstatus === '0' ? data.itemplaced : '&nbsp;';
  911. var placedbet = data.ipstatus === '1' ? data.itemplaced : '&nbsp;';
  912. // infos Below TeamA vs TeamB
  913. var infosbelow = '<div class="infosbelow-lr infosbelow-tb"> <div class="line2a"><span title="csgolounge bet reward value">' + data.teamAReward + '</span></div> </div> <div class="infosbelow-center">' + data.bestOf + '</div> <div class="infosbelow-lr infosbelow-tb"> <div class="line2b"> <span title="csgolounge bet reward value">' + data.teamBReward + '</span> </div>';
  914. // Match box header (eg. time left, date cup etc...)
  915. // var mDataHeaderSpacer = '<div class="matchheader-spacer">-</div>';
  916. // var matchDataheader1 = ('<div class="whenm"> - <span class="dateRaw">' + data.dateRaw + '</span> - <span class="timeRaw">' + data.timeRaw + '</span></div>');
  917. // var matchDataheader2 = ('<div class="whenm"><span class="peopleItemsNum">' + data.peopleItemsNum + '</span></div>');
  918.  
  919. var mDataHeaderSpacer = '<span class="matchheader-spacer"></span>';
  920. var headerDTimeLeft = '<span class="timeleft">' + data.timeLeft + '</span>';
  921. var headerDMatchStatus = '<span class="matchstatus"></span>';
  922. var headerDTimeRaw = '<span class="timeRaw">&nbsp;&nbsp;(' + data.timeRaw + ')</span>';
  923. var headerDDateRaw = '<span class="dateRaw">' + data.dateRaw + '</span>';
  924. var headerDPItemNum = '<span class="peopleItemsNum">' + data.peopleItemsNum + '</span>';
  925. var headerDEvent = '<span class="eventm">CCS</span>';
  926. $('.matchheader .whenm').remove();
  927. // matchheader (time left, date, additionnal info, cup)
  928. var $w = $('body').find('a[href="match?m=' + id + '"]').parents().eq(2).find('.matchheader .whenm');
  929. var $w2 = $('body').find('a[href="match?m=' + id + '"]').parents().eq(2).find('.matchheader');
  930. // APPEND
  931. // matchheader
  932. // $w2.append(matchDataheader1 + mDataHeaderSpacer + matchDataheader2);
  933. $w2.append(headerDTimeLeft + headerDMatchStatus + headerDTimeRaw + mDataHeaderSpacer + headerDDateRaw + mDataHeaderSpacer + headerDPItemNum);
  934. if ((data.timeLeft).indexOf('ago') > -1) {
  935. var msCtn = $('body').find('.matchstatus');
  936. msCtn.html(this.liveNow);
  937. }
  938. // Infos below the TeamA vs TeamB part
  939. data.matchCtn.find('a:first').append(infosbelow);
  940. // SummaryBox (labels eg. "No bet placed" "hltv link" "reddit link" etc..."
  941. data.matchCtn.append('<div class="matchbox-summary"></div>');
  942. if (data.ipstatus == '0') {
  943. data.matchCtn.find('.matchbox-summary').append('<span class="sumbox suminfo-bet">No bet placed.</span>');
  944. } else {
  945. data.matchCtn.find('.matchbox-summary').append('<span class="sumbox suminfo-bet">A bet has been placed.</span>');
  946. }
  947. // Expand button
  948. data.matchCtn.append('<div class="expmatchbtn-ctn"><a class="expandmatch-btn-a"><span class="expandmatch-btn">+</span></a></div>');
  949. // DetailsBox (box to expand)
  950. data.matchCtn.append('<div class="detailsbox"' + initialization.matchBoxStatus + '>' + placedbet + '</div>');
  951. // MAINSTREAM
  952. // if (data.msstatus == '1') {
  953. // data.matchCtn.append('<div class="detailsbox"><div class="mainstream-btn"><a href="#" > class="sh-stream">SHOW HIDE STREAM</a></div><div class="mainstream" style="display: none;">'+data.mainstream+'</div>')
  954. // }
  955. // $('.sh-stream').click(function(){
  956. // var $t = $(this).parents().eq(2);
  957. // alert($t.find('.mainstream'))
  958. // return false;
  959. // });
  960.  
  961. console.log('append done for id:', id);
  962. }
  963. // loading display
  964. data.matchCtn.find('.matchloading-ctn').remove();
  965. var dfd = new jQuery.Deferred();
  966. return dfd.resolve(this, container, id);
  967. };
  968. globalClass.prototype.updateLoading = function (loadingStatus) {
  969. var loadingStatus = this[this.worker].loadingStatus;
  970. if (this.worker === "feeds") {
  971. if (loadingStatus.index + 1 === loadingStatus.totalItemsToLoad) { // feeds have finished loading
  972. $('.feedloading').fadeOut('fast');
  973. }
  974. } else if (this.worker === "initialization") { // status bar render for worker initialization
  975. var status = loadingStatus.index;
  976. var total = loadingStatus.totalItemsToLoad;
  977. var part = (100 / total);
  978. var currentPart = part * status;
  979. var newPart = part + currentPart;
  980. var newPartShow = Math.round(newPart);
  981. $('.progress > span').css('width', newPart + '%');
  982. $('.progress > span > span').text(newPartShow + '%');
  983. if (status + 1 === total) {
  984. $('.progress > span').css('width', '100%');
  985. $('.progress > span > span').text('100%');
  986. $('#mainloadingbar').fadeOut('slow');
  987. $('#matchescount').fadeOut('slow');
  988. }
  989. $('#mainheader #matchescount #current-matchescount').html(loadingStatus.index); // loading counter "X"/y
  990. } else { // any worker
  991. }
  992. };
  993. /* *********** Feed Jobs *********** */
  994.  
  995. globalClass.prototype.appendEachFeed = function (worker, job, url, id, container, data) {
  996. _log('*** appendEachFeed ***');
  997. var self = this;
  998. // var data = JSON.parse(data.response);
  999. var data = data.datas.feedProperties;
  1000. $.each(data, function (index, value) {
  1001. var feedUrl = typeof value.feedUrls !== "undefined" ? value.feedUrls.reddit : value.feedUrl;
  1002. container.append('<li><a href="' + feedUrl + '" target="_blank" title="' + value.feedCup + '">' + value.feedMatchname + ' - ' + value.feedDate + '</li>');
  1003. });
  1004. var dfd = new jQuery.Deferred();
  1005. return dfd.resolve(this, this[this.worker].loadingStatus);
  1006. };
  1007. /* *********** Update Page *********** */
  1008.  
  1009. globalClass.prototype.getMainPageDistant = function () {
  1010. _l('*** Initialization of Update Page Data ***');
  1011. // globalData.currentData = globalClass.initialization.data; // store local infos retrieved with initialization worker
  1012. console.log("getMainPageDistant", "this", this, this.worker);
  1013. var dfd = new jQuery.Deferred();
  1014. return dfd.resolve(this);
  1015. };
  1016. globalClass.prototype.compareData = function () {
  1017. /* CurrentData = data on the page before the update
  1018. * NewData = data on the DISTANT page
  1019. * DiffData = currentData (+ add - rem from newData)
  1020. * result of currentData and newData comparison (add&rem) => will use it to compare current props (diffData[]) with new props (newData[])
  1021. */
  1022. _log('*** Compare Page Data ***');
  1023. console.log('*** Compare Page Data ***');
  1024. //COMPARE
  1025. var currentData = globalData.currentData;
  1026. var newData = this[this.worker].data;
  1027. console.log(this.tools(), 'globalData.currentData - compareData START', globalData.currentData);
  1028. console.log(this.tools(), 'newData - compareData START', newData);
  1029. // console.log(JSON.stringify(currentData))
  1030. // console.log(JSON.stringify(newData))
  1031.  
  1032. var globalMonitor = this[this.worker].loadingStatus.globalMonitor;
  1033. if (globalMonitor.error.request > 0) { // if there was at least 1 req error in match pages requests.
  1034. for (var i = 0; i < globalMonitor.error.IDs; i++) {
  1035.  
  1036. }
  1037. }
  1038.  
  1039. /* DEBUG */
  1040. // rem
  1041. // newData.splice(1, 1) // completely removes item 1 of array until next item (1 item for 1 time)
  1042. // add
  1043. // var editThat = [];
  1044. // newData.forEach(function (obj) { // cloning diffData with currentData
  1045. // var clonedObj = {};
  1046. // var clonedObj = jQuery.extend(true, {}, obj);
  1047. // editThat.push(clonedObj);
  1048. // });
  1049. // editThat[1].matchId = "9999";
  1050. // editThat[1].matchUrl = "http://csgolounge.com/match?m=9999";
  1051. // var last = newData.length;
  1052. // newData[last] = editThat[1];
  1053. /* DEBUG */
  1054.  
  1055. var propsToUpdate = []; // we are building this array a bit below, containing all properties to update.
  1056.  
  1057. var diffData = []; // result of currentData and newData comparison (add&rem) => will use it to compare current props (diffData[]) with new props (newData[])
  1058.  
  1059. // WRONG WAY TO CLONE.
  1060. // currentData.forEach(function (obj) { // cloning diffData with currentData
  1061. // diffData.push(obj);
  1062. // });
  1063. currentData.forEach(function (obj) { // cloning diffData with currentData
  1064. var clonedObj = {};
  1065. var clonedObj = jQuery.extend(true, {}, obj); // deep dopy
  1066. diffData.push(clonedObj);
  1067. });
  1068. // matches to add & to remove.
  1069. function dataDifferenceADD(currentData, newData) {
  1070. var x = {};
  1071. currentData.forEach(function (obj) {
  1072. x[obj.matchId] = obj;
  1073. });
  1074. return newData.filter(function (obj) {
  1075. return !(obj.matchId in x);
  1076. });
  1077. }
  1078. function dataDifferenceREM(currentData, newData) {
  1079. var x = {};
  1080. newData.forEach(function (obj) {
  1081. x[obj.matchId] = obj;
  1082. });
  1083. return currentData.filter(function (obj) {
  1084. return !(obj.matchId in x);
  1085. });
  1086. }
  1087. var toAdd = dataDifferenceADD(currentData, newData);
  1088. console.log('add', toAdd);
  1089. var toRem = dataDifferenceREM(currentData, newData);
  1090. console.log('rem', toRem);
  1091. // console.log("toAdd", JSON.stringify(toAdd))
  1092. // console.log("newData", JSON.stringify(newData))
  1093. toAdd.forEach(function (obj) { //add
  1094. diffData.push(obj); // push toAdd to diffData OBJ
  1095. propsToUpdate.push(obj);
  1096. });
  1097. toRem.forEach(function (obj) { //rem
  1098. var index = diffData.map(function (x) {
  1099. return x.matchId;
  1100. }).indexOf(obj.matchId); // grep index of toRem matchId in currentData
  1101. if (index > -1) {
  1102. diffData.splice(index, 1); // remove toRem element(s) in diffData
  1103. }
  1104. });
  1105. this.remAndAdd = {};
  1106. this.remAndAdd.rem = toRem;
  1107. this.remAndAdd.add = toAdd;
  1108. // console.log("diffData", JSON.stringify(diffData))
  1109. // console.log("newData", JSON.stringify(newData))
  1110.  
  1111. /*
  1112. #1 props checks
  1113. - loop through each prop of newData
  1114. => check if current prop is in diffData
  1115. - if yes => compare values => if diff => update dom & obj
  1116. - if no => update dom & obj
  1117. */
  1118.  
  1119. for (var i = 0; i < newData.length; i++) {
  1120. var newValuesObj = newData[i];
  1121. var matchId = newValuesObj.matchId; // GET MATCHID
  1122. var currentValues = $.grep(diffData, function (element, index) { // Grep matchId in diffData
  1123. return element.matchId === matchId;
  1124. });
  1125. console.log('@compareData: --------- Checking matchID: ', matchId, ' ---------');
  1126. if (typeof currentValues !== "undefined" && currentValues.length !== 0) {
  1127. var currentValuesObj = currentValues[0]; // item of diffData array with current/old values (eg. {matchId: 2185, matchCtn: "div"...})
  1128.  
  1129. //console.log('currentValuesObj', currentValuesObj)
  1130.  
  1131. // build a list of properties for each array of values
  1132. var currentArrayOfProps = Object.getOwnPropertyNames(currentValuesObj);
  1133. var newArrayOfProps = Object.getOwnPropertyNames(newValuesObj);
  1134. // console.log('allvars', newValuesObj, matchId, currentValuesObj, currentArrayOfProps, newArrayOfProps)
  1135.  
  1136. percStatus = {}; // percentage status: up, down, equal, err status
  1137. for (var j = 0; j < newArrayOfProps.length; j++) { // iterate over the props array from newData
  1138.  
  1139. /* Results */
  1140. // newValuesObj = obj from newData (eg. Object { matchUrl="http://csgolounge.com/match?m=3022", matchId="3022", matchCtn={...}, plus...})
  1141. // currentValuesObj = obj from diffData (eg. Object { matchUrl="http://csgolounge.com/match?m=3022", matchId="3022", matchCtn={...}, plus...})
  1142. // propNameToCheck / newArrayOfProps[j] = teamBReward
  1143. // newValuesPropValue / newValuesObj[propNameToCheck] = 5.4 for 1
  1144. /* !Results */
  1145.  
  1146. var propNameToCheck = newArrayOfProps[j];
  1147. var newValuesPropValue = newValuesObj[propNameToCheck];
  1148. var currentValuesPropValue = currentValuesObj[propNameToCheck];
  1149. if (settings.debug.autoUpdate) {
  1150. console.log('propNameToCheck', propNameToCheck);
  1151. console.log('newValuesObj', newValuesObj);
  1152. console.log('currentValuesObj', currentValuesObj);
  1153. console.log('newValuesPropValue', newValuesPropValue);
  1154. console.log('currentValuesPropValue', currentValuesPropValue);
  1155. console.log('newArrayOfProps', newArrayOfProps);
  1156. console.log('currentArrayOfProps', currentArrayOfProps);
  1157. console.log('newValuesPropValue', newValuesPropValue);
  1158. console.log('currentValuesPropValue', currentValuesPropValue);
  1159. }
  1160. if ((currentValuesPropValue !== newValuesPropValue) && typeof newValuesPropValue != "undefined") { // prop is different in newDatas & currentData, newData prop is defined.
  1161. if (settings.debug.autoUpdate) {
  1162. console.log('#' + matchId, 'currentValuesPropValue', currentValuesPropValue, 'newValuesPropValue', newValuesPropValue);
  1163. }
  1164. // we populate an array (propsToUpdate) containing objects with props to update. We set obj at the array id it was in newData.
  1165. // eg. newData[2] = { "matchId": "2789", "prop" : "value" ... } => propToUpdate[2] = { "matchId": "2789", "propXToUpdate" : "valueXToUpdate" ...}
  1166.  
  1167. if (propNameToCheck === "teamBperc" || propNameToCheck === "teamAperc") { // percentage status. Let's check if percentage goes up, down, stays equal or is in err. Access example: propsToUpdate[index].percStatus.teamAperc
  1168. percStatus[propNameToCheck] = currentValuesPropValue < newValuesPropValue ? "up" : currentValuesPropValue > newValuesPropValue ? "down" : currentValuesPropValue == newValuesPropValue ? "equal" : "err";
  1169. }
  1170.  
  1171. var elementPos = propsToUpdate.map(function (x) { // Checking if we have already an obj for this matchId in propsToUpdate
  1172. return x.matchId;
  1173. }).indexOf(newValuesObj.matchId); // id in array
  1174.  
  1175. if (elementPos === -1) { // we've no obj, creating it.
  1176. var objToPush = {// basic obj containing matchId.
  1177. "matchId": newValuesObj.matchId
  1178. };
  1179. }
  1180. // setting objToPush properties
  1181. objToPush[propNameToCheck] = newValuesPropValue; // populating current prop in our obj
  1182. if (typeof percStatus[propNameToCheck] !== "undefined" && percStatus[propNameToCheck].length > 0) { // add percStatus if we've it.
  1183. objToPush.percStatus = percStatus;
  1184. }
  1185. // pushing obj or updating propsToUpdate array.
  1186. if (elementPos === -1) {
  1187. propsToUpdate.push(objToPush); // pushing obj containing prop, or prop + matchId.
  1188. } else {
  1189. propsToUpdate[elementPos] = objToPush; // pushing obj containing prop, or prop + matchId.
  1190. }
  1191. }
  1192.  
  1193. } // !for loop (newArrayOfProps, properties list from newData)
  1194. }
  1195. } // !for loop (newData)
  1196.  
  1197. console.log(this.tools(), 'newData - compareData END', newData);
  1198. console.log(this.tools(), 'diffData - compareData END', diffData);
  1199. console.log(this.tools(), 'propsToUpdate - compareData END', propsToUpdate);
  1200. globalData.currentData = newData; // update globalData Object
  1201. this.propsToUpdate = propsToUpdate; // public prop, will be used by updateData to generate the VIEW
  1202. // console.log(JSON.stringify(propsToUpdate))
  1203.  
  1204. var dfd = new jQuery.Deferred();
  1205. return dfd.resolve(this);
  1206. };
  1207. globalClass.prototype.updateData = function () {
  1208. // _l('*** Update Page Data ***');
  1209. console.log('*** Update Page Data ***', this.propsToUpdate);
  1210. var self = this;
  1211. // UPDATE
  1212. /* 1) grep matchId
  1213. * 2) find container in dom
  1214. * 3) find props containers in matchmain container
  1215. * 4) update containers
  1216. */
  1217. // var propsToUpdate = [{"matchId": "2904", "peopleItemsNum": "\n 20026 people placed 57614 items.\n "}, {"matchId": "2907", "teamBReward": "1.3 for 1", "valueBetB": "1.3 for 1", "peopleItemsNum": "\n 15373 people placed 44126 items.\n "}, {"matchId": "2905", "teamAReward": "3.24 for 1", "valueBetA": "3.24 for 1", "peopleItemsNum": "\n 11275 people placed 31350 items.\n "}, {"matchId": "2908", "teamBReward": "3.54 for 1", "valueBetB": "3.54 for 1", "peopleItemsNum": "\n 1279 people placed 3564 items.\n "}, {"matchId": "2911", "teamBReward": "3.71 for 1", "valueBetB": "3.71 for 1", "peopleItemsNum": "\n 722 people placed 1842 items.\n "}, {"matchId": "2910", "peopleItemsNum": "\n 894 people placed 2420 items.\n "}, {"matchId": "2909", "teamAReward": "1.91 for 1", "valueBetA": "1.91 for 1", "peopleItemsNum": "\n 567 people placed 1472 items.\n "}]
  1218. // console.log(propsToUpdate.length)
  1219.  
  1220. // ADD && REM TO DOM
  1221. // REMOVES
  1222. var addedMatchesCtn = []; // container to pass as selector to CompleteInitialization.call(that, worker, selector) for props loading
  1223. var toAdd = this.remAndAdd.add;
  1224. var toRem = this.remAndAdd.rem;
  1225. // TO ADD DEBUG
  1226. // var m = [];
  1227. // $.each($('body').find('.matchmain .match').not('.notavailable').parent(), function (i, v) {
  1228. // m.push(v)
  1229. // });
  1230. // console.log('v', m)
  1231. // var toAdd = [m[1], m[3]]
  1232.  
  1233. // TO REM DEBUG
  1234. // var toRem = [{"matchUrl": "http://csgolounge.com/match?m=3058", "matchId": "3058", "matchCtn": {"0": {}, "length": 1, "prevObject": {"0": {}, "length": 1, "prevObject": {"0": {}, "context": {}, "length": 1}, "context": {}, "selector": "a[href=\"match?m=2957\"]"}, "context": {}}, "teamAperc": "84%", "teamBperc": "16%", "matchNameA": "A51", "matchNameB": "Incursion", "teamAReward": "0.05 to 0.19 for 1", "teamBReward": "5.14 for 1", "valueBetA": "0.05 to 0.19 for 1", "valueBetB": "5.14 for 1", "peopleItemsNum": "\n 37891 people placed 109923 items.\n ", "timeLeft": "1 hour from now", "bestOf": "Best of 3", "timeRaw": "\n 04:30 CEST ", "dateRaw": "Thursday 2nd April 2015", "ipstatus": "0", "itemplaced": "No bet placed.", "teamBet": "0", "msstatus": "0", "mainstream": "No stream available"}];
  1235. // var matchCtnx = $('body').find('a[href="match?m=3058"]').closest('.match').parent(); // debug
  1236. // console.log(matchCtnx);
  1237. // console.log(toRem);
  1238. // toRem[0].matchCtn = matchCtnx; // debug
  1239. if (toRem.length > 0) {
  1240. $('.numofm').html((globalData.currentData).length).delay(50).fadeOut().fadeIn('slow');
  1241. }
  1242. if (toAdd.length > 0) {
  1243. // detach all containers
  1244. var matchmainCtn = $('body').find('.matchmain .match').not('.notavailable').parent();
  1245. var detachedMM = [];
  1246. $.each(matchmainCtn, function (i, v) { // detach all matches containers in detachedMM array
  1247. var matchUrlDest = $(v).find('a').attr('href');
  1248. var matchId = matchUrlDest.replace('match?m=', '').replace('predict?m=', '');
  1249. //detached.push($(v).detach())
  1250. var detachedMatches = {
  1251. };
  1252. detachedMatches.matchCtn = $(v).detach();
  1253. detachedMatches.matchId = matchId;
  1254. detachedMM.push(detachedMatches);
  1255. });
  1256. console.log('detachedMM', detachedMM);
  1257. // rebuld the page with reattached matches containers and added match containers
  1258. $.each(globalData.currentData, function (i, v) { // loop through newData (updated in the prev. step globaData.currentData object), for each entry, check if ctn is in DOM or in newData obj
  1259. // check if v.matchId is in a 'toAdd' match, if yes, grep matchCtn in newData, else attach current matchCtn
  1260. var matchToAdd = $.grep(toAdd, function (element, index) { // check if match is in toAdd
  1261. return element.matchId === v.matchId;
  1262. });
  1263. //var matchToAdd = matchToAdd[0];
  1264.  
  1265. // matchIsNew so toAdd: yes, no.
  1266. var matchIsNew = (matchToAdd.length > 0) ? true : false;
  1267. if (matchIsNew) { // current matchId is also in toAdd.
  1268. console.log('matchIsNew TRUE', matchToAdd[0].matchCtn);
  1269. if (typeof matchToAdd[0].matchCtn !== 'undefined') {
  1270. $(matchToAdd[0].matchCtn).parent().insertBefore('.shownotav').delay(50).fadeOut().fadeIn('slow');
  1271. console.log('added new match:', v.matchCtn, v);
  1272. addedMatchesCtn.push($(matchToAdd[0].matchCtn).parent());
  1273. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>A new match has been added (#' + v.matchId + ') !</li>');
  1274. $('.numofm').html((globalData.currentData).length).delay(50).fadeOut().fadeIn('slow');
  1275. }
  1276. }
  1277. if (!matchIsNew) { // matchCtn is in detachedMatches
  1278. var matchToReAppend = $.grep(detachedMM, function (element, index) {
  1279. // console.log('matchIsNOTNew', detachedMM, element, v.matchId);
  1280. //return element.matchId === v.matchId;
  1281. return element.matchId === v.matchId;
  1282. });
  1283. var matchToReAppend = matchToReAppend[0];
  1284. // console.log('matchToReAppend, matchIsNOTNew ', matchToReAppend)
  1285. if (typeof matchToReAppend.matchCtn !== 'undefined') {
  1286. $(matchToReAppend.matchCtn).insertBefore('.shownotav');
  1287. }
  1288. }
  1289. });
  1290. }
  1291. // Properties update
  1292. var propsToUpdate = this.propsToUpdate;
  1293. function getPropValue(obj, prop) {
  1294. var toRet;
  1295. $.each(obj, function (propl, val) {
  1296. if (propl === prop) {
  1297. toRet = val;
  1298. return false;
  1299. }
  1300. });
  1301. return toRet;
  1302. }
  1303. var debugAU = false;
  1304. for (var x = 0; x < propsToUpdate.length; x++) { // loop through propsToUpdate
  1305. var obj = propsToUpdate[x]; // obj in propsToUpdate array
  1306. var matchId = obj.matchId;
  1307. // if (matchId === "9999") {
  1308. // var matchId = "3051"
  1309. // var a = $('body').find('a[href="match?m=3051"]').closest('.match').parent();
  1310. // var container = a['1'];
  1311. // var container = $(container);
  1312. // } else {
  1313. var subContainer = $('body').find('a[href="match?m=' + matchId + '"]').closest('.match'); // .match ctn
  1314. var container = subContainer.parent(); // .matchmain ctn
  1315. // }
  1316. if (debugAU) {
  1317. console.log(['AU:'], ' ', '-------- check matchId:', matchId, ' ------');
  1318. console.log(['AU:'], ' ', 'var x in propsToUpdate', 'container', container, 'obj', obj, 'prop', prop, 'dest', destCtn, 'destSel', destCtnSel);
  1319. }
  1320. for (var prop in obj) { // browse each prop of the obj
  1321. if (debugAU) {
  1322. console.log(['AU:'], ' ', '(var prop in obj)', 'prop', prop);
  1323. }
  1324. if (prop !== "matchId" || prop !== "teamBperc" || prop !== "teamAperc" || prop !== "percStatus" || prop !== "matchCtn") {
  1325. var destCtnSel = getPropValue(this.propsContainers, prop); // where to append the prop
  1326. var destCtn = container.find(destCtnSel);
  1327. if (destCtn.length > 0) {
  1328. var newValue = obj[prop];
  1329. destCtn.html(newValue).delay(100).fadeOut().fadeIn('slow');
  1330. console.log('Updated matchId:', matchId, ' prop:', prop, ' with value:', newValue, 'in container:', destCtn);
  1331. }
  1332. }
  1333. if (prop === "timeLeft") { // Live !, Postponed, Closed etc...
  1334. console.log("PROPTIMELEFT:", prop, obj[prop], this, container, msCtn, this.liveNow, obj[prop].indexOf('ago'));
  1335. if (obj[prop].indexOf('ago') > -1) {
  1336. var msCtn = container.find('.matchstatus');
  1337. msCtn.html(this.liveNow);
  1338. }
  1339. }
  1340.  
  1341. if (prop === "percStatus") { // arrows
  1342. if (typeof obj.percStatus.teamAperc !== "undefined") {
  1343. var destCtn = container.find('.arrow-teama');
  1344. if (typeof destCtn !== "undefined" && destCtn.length > 0) {
  1345. destCtn.html(this.arrow[obj.percStatus.teamAperc]).delay(100).fadeOut().fadeIn('slow');
  1346. }
  1347. }
  1348. if (typeof obj.percStatus.teamBperc !== "undefined") {
  1349. var destCtn = container.find('.arrow-teamb');
  1350. if (typeof destCtn !== "undefined" && destCtn.length > 0) {
  1351. destCtn.html(this.arrow[obj.percStatus.teamBperc]).delay(100).fadeOut().fadeIn('slow');
  1352. }
  1353. }
  1354. }
  1355. if (prop === "teamBperc" || prop === "teamAperc") {
  1356. var destCtnSel = getPropValue(this.propsContainers, prop); // where to append the prop
  1357. var destCtn = container.find(destCtnSel);
  1358. if (destCtn.length > 0) {
  1359. if (debugAU) {
  1360. console.log(['AU:'], ' ', 'prop', prop, 'dest', destCtn, 'destSel', destCtnSel);
  1361. }
  1362. var newValue = obj[prop];
  1363. destCtn.html(newValue).delay(100).fadeOut().fadeIn('slow');
  1364. }
  1365. }
  1366.  
  1367. } // for (var prop in obj)
  1368. } // for (var x in propsToUpdate)
  1369.  
  1370.  
  1371.  
  1372. var dfd = new jQuery.Deferred();
  1373. return dfd.resolve(this, toAdd, toRem);
  1374. };
  1375. globalClass.prototype.autoUpdateTimers = function () {
  1376. var today = new Date();
  1377. var hh = today.getHours();
  1378. var mm = today.getMinutes();
  1379. var ss = today.getSeconds();
  1380. if (ss <= 9)
  1381. ss = "0" + ss;
  1382. if (mm <= 9)
  1383. mm = "0" + mm;
  1384. var timeNow = hh + ':' + mm + ':' + ss;
  1385. $('.au-lasttime').html(timeNow);
  1386. // var mins = settings.updateDelay;
  1387. var secs = settings.updateDelay / 1000;
  1388. var currentSeconds = 0;
  1389. var currentMinutes = 0;
  1390. if (typeof window.autoUpdateTimer != "undefined") {
  1391. clearInterval(window.autoUpdateTimer);
  1392. }
  1393.  
  1394. window.autoUpdateTimer = setInterval(function () {
  1395. auCountDown();
  1396. }, 1000);
  1397. function auCountDown() {
  1398. currentMinutes = Math.floor(secs / 60);
  1399. currentSeconds = secs % 60;
  1400. if (currentSeconds <= 9)
  1401. currentSeconds = "0" + currentSeconds;
  1402. secs--;
  1403. $('.au-timeleft').html(currentMinutes + "m " + currentSeconds + "s");
  1404. if (secs === -1) {
  1405. clearInterval(window.autoUpdateTimer);
  1406. $('.au-timeleft').html('updating...');
  1407. }
  1408. }
  1409.  
  1410.  
  1411. };
  1412. /* *********** join Matches And Feed *********** */
  1413. globalClass.prototype.compareMatchesWithFeed = function () {
  1414. _log('*** Compare Matches With Feeds ***');
  1415. };
  1416. globalClass.prototype.appendFeedToMatches = function () {
  1417. _log('*** Append Feed to Matches ***');
  1418. };
  1419. globalClass.prototype.tools = function () {
  1420. _log('*** tools ***');
  1421. var today = new Date();
  1422. var hh = today.getHours();
  1423. var mm = today.getMinutes();
  1424. var ss = today.getSeconds();
  1425. if (ss <= 9)
  1426. ss = "0" + ss;
  1427. if (mm <= 9)
  1428. mm = "0" + mm;
  1429. var timeNow = hh + ':' + mm + ':' + ss;
  1430. return timeNow;
  1431. };
  1432. function CompleteInitialization(worker, selector) {
  1433. // var initGlobal = new globalClass('initialization'); // wrap init + get each match infos + appends
  1434. var selector = (typeof selector === "undefined") ? "" : selector;
  1435. this.job.retrieveMissing = (typeof selector != "undefined" && selector.length > 0) ? true : false;
  1436. console.log('this (CompleteInitialization)', this, worker, selector, this.job.retrieveMissing);
  1437. $.when(this.parseMainPage(selector)).then(function (that) {
  1438. pLog('DONE:', 'parseMainPage', that);
  1439. return that.globalInfos();
  1440. }).then(function (that) {
  1441. pLog('DONE:', 'globalInfos', that);
  1442. return that.initLoading();
  1443. }).then(function (that) { // Get Match Infos LOOP
  1444. var promisesCompleteInit = [];
  1445. var data = that[that.worker].data;
  1446. $.each(data, function (index, matchUrl) {
  1447. var matchUrl = data[index].matchUrl;
  1448. var matchId = data[index].matchId;
  1449. var matchCtn = data[index].matchCtn;
  1450. _log('curr =', matchUrl, that);
  1451. var p = that.ajaxCalls(that.worker, that.job, matchUrl, matchId, matchCtn, settings.defaultTimeout); //
  1452. promisesCompleteInit.push(p);
  1453. p.done(function (data, textStatus, jqXHR) {
  1454. var responseData = jqXHR.responseText;
  1455. that.monitorWorker("success", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1456.  
  1457. // when request is done, process the data.
  1458. $.when(that.parseMatchPageData(that.worker, that.job, matchUrl, matchId, matchCtn, responseData)).then(function (that, data) {
  1459. return that.appendEachMatch(that.worker, that.job, matchUrl, matchId, matchCtn, data);
  1460. }).then(function (that, matchCtn, matchId) {
  1461. pLog('DONE: CompleteInitialization, appendEachMatch', that);
  1462. that.monitorWorker("success", "view", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1463. return that.updateLoading(that[that.worker].loadingStatus); // send each request status individually to updateLoading
  1464. });
  1465. });
  1466. p.fail(function (jqXHR, stringStatus, exceptionObj) { // exceptionObj: "abort", "timeout", "No Transport".
  1467. if (exceptionObj) {
  1468. switch (exceptionObj) {
  1469. case 'abort':
  1470. var errorType = 'abort';
  1471. that.errorHandling("error", "request", matchCtn, matchId, errorType);
  1472. that.monitorWorker("error", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1473. break;
  1474. case 'timeout':
  1475. var errorType = 'timeout';
  1476. that.errorHandling("error", "request", matchCtn, matchId, errorType);
  1477. that.monitorWorker("error", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1478. break;
  1479. case 'No Transport':
  1480. var errorType = 'No Transport';
  1481. that.errorHandling("error", "request", matchCtn, matchId, errorType);
  1482. that.monitorWorker("error", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1483. break;
  1484. }
  1485. } else {
  1486. var errorType = 'error';
  1487. that.errorHandling("error", "request", matchCtn, matchId, errorType);
  1488. that.monitorWorker("error", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1489. }
  1490. pLog('Failed to retrieve a match in CompleteInitialization', errorType, matchUrl);
  1491. });
  1492. }); // each ended.
  1493.  
  1494. $.when.apply($, promisesCompleteInit)
  1495. .always(function () {
  1496. that.done();
  1497. pLog('DONE: CompleteInitialization ajax req and appends have just finished.');
  1498. if (settings.switches.autoupdate) {
  1499. console.log('Initializing Update in ' + settings.updateDelay / 1000 / 60 + ' minutes');
  1500. // console.log('GLOBALOBJ',that.initialization.data)
  1501. // console.log('GLOBALOBJ',globalData.currentData )
  1502. that.autoUpdateTimers();
  1503. window.autoUpdate = setInterval(function () {
  1504. console.log('UpdateInitialization');
  1505. that.autoUpdateTimers();
  1506. UpdateInitialization();
  1507. }, settings.updateDelay);
  1508. }
  1509. })
  1510. .done(function () {
  1511. console.log('Fired all methods for worker init were done without errors.');
  1512. })
  1513. .fail(function () {
  1514. console.log('Fired all methods for worker init were done WITH ERRORS.');
  1515. });
  1516. });
  1517. }
  1518. /*
  1519. * @CompleteInitialization()
  1520. "parseMainPage",
  1521. "globalInfos",
  1522. "initLoading",
  1523. "getMatchInfos", // WRAPPED THIS DIRECTLY IN CompleteInitialization function.
  1524. "ajaxCalls",
  1525. "parseMatchPageData",
  1526. "appendEachMatch",
  1527. "updateLoading"
  1528. */
  1529.  
  1530. function UpdateInitialization() { // (AU = Auto Update)
  1531. pLog('UpdateInitialization fired !');
  1532. var initUpdate = new globalClass('updatePage'); // init page view only
  1533. $.when(initUpdate.getMainPageDistant())
  1534. .then(function (that) {
  1535. var AUmainpage = initUpdate.ajaxCalls(initUpdate.worker, "updatePage", baseUrl, "", "", settings.defaultTimeout);
  1536. AUmainpage.done(function (data, textStatus, jqXHR) {
  1537. pLog('req ', baseUrl, ' done.');
  1538. $.when(that.parseMainPage("", data))
  1539. .then(function (that) {
  1540. pLog('DONE:', 'globalInfos', that);
  1541. return that.initLoading();
  1542. })
  1543. /* ---------------- */
  1544. .then(function (that, data) { // Get Match Infos LOOP
  1545. _log('parseMainPage DONE', that[that.worker]);
  1546. var promisesUpdateInit = [];
  1547. var promisesUpdateParsing = [];
  1548. var dataG = that[that.worker].data;
  1549. $.each(dataG, function (index, matchUrl) {
  1550. var matchUrl = dataG[index].matchUrl;
  1551. var matchId = dataG[index].matchId;
  1552. var matchCtn = dataG[index].matchCtn;
  1553. //console.log('curr =', matchUrl, that);
  1554. var px = that.ajaxCalls(that.worker, that.job, matchUrl, matchId, matchCtn, settings.defaultTimeout); //
  1555. promisesUpdateInit.push(px);
  1556. px.done(function (data, textStatus, jqXHR) { // ajax request is complete and has success status.
  1557. var responseData = jqXHR.responseText;
  1558. pLog('DONE', that.worker, that.job, matchUrl, matchId, matchCtn);
  1559. that.monitorWorker("success", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1560. promisesUpdateParsing.push(that.parseMatchPageData(that.worker, that.job, matchUrl, matchId, matchCtn, responseData)); // Parse the data.
  1561. if (promisesUpdateParsing.length === dataG.length) { // wait for all parsing promises returned by parseMatchPageData method.
  1562. $.when.apply($, promisesUpdateParsing).then(
  1563. function (status) {
  1564. $.when(that.compareData())
  1565. .then(function (that) {
  1566. return that.updateData();
  1567. }, function () {
  1568. console.log('E R R O R');
  1569. })
  1570. .then(function (that, toAdd, toRem) { // datas append when a new match has been added.
  1571. console.log('UPDATEDATADONE:', toAdd);
  1572. if (typeof toAdd != "undefined" && toAdd.length > 0) {
  1573. console.log('UPDATEDATADONE:', toAdd);
  1574. for (var i = 0; i < toAdd.length; i++) {
  1575. console.log('appending shit to a new ctn:', toAdd[i]);
  1576. that.appendEachMatch(that.worker, that.job, toAdd[i].matchUrl, toAdd[i].matchId, toAdd[i].matchCtn, toAdd[i]);
  1577. }
  1578. }
  1579. // when a match has been removed.
  1580. console.log('UPDATEDATADONE:', toRem);
  1581. if (typeof toRem != "undefined" && toRem.length > 0) {
  1582. console.log('UPDATEDATADONE:', toRem);
  1583. for (var i = 0; i < toRem.length; i++) {
  1584. var matchUrl = toRem[i].matchUrl;
  1585. var matchId = toRem[i].matchId;
  1586. console.log('appending shit to a new ctn:', toAdd[i]);
  1587. console.log("TOREMOVE", toRem.length);
  1588. console.log('toRem[i].matchCtn', toRem[i].matchCtn);
  1589. // find, detach and append match ctn to shna
  1590. var toRemCtn = $('body').find('a[href="match?m=' + matchId + '"]').parents().eq(2);
  1591. var detachedToRemCtn = toRemCtn.detach();
  1592. detachedToRemCtn.appendTo('#sh-na').find('.match').addClass('notavailable');
  1593. console.log('detached', matchId, detachedToRemCtn, 'and appended to #sh-na');
  1594. // ajax call the match page to get the match result or status (winner/loser or postponed, closed etc...)
  1595. $.when(that.ajaxCalls(that.worker, that.job, matchUrl, matchId, detachedToRemCtn, settings.defaultTimeout))
  1596. .done(function (data, textStatus, jqXHR) {
  1597. console.log('REMOVEDONE:', textStatus, jqXHR, matchUrl, matchId);
  1598. var data = $(data);
  1599. var resultSel = data.find('.box-shiny-alt:eq(0)');
  1600. var teamARes = resultSel.find('b:eq(0)');
  1601. var teamBRes = resultSel.find('b:eq(1)');
  1602. var teamARes = teamARes.text().trim();
  1603. var teamBRes = teamBRes.text().trim();
  1604. console.log('teamARes', teamARes);
  1605. console.log('teamBRes', teamBRes);
  1606. var wonImg = '<img style="position: relative; left: 40px; top: -12px;" src="http://cdn.csgolounge.com/img/won.png">';
  1607. if (teamARes.indexOf('WIN') > -1 || teamBRes.indexOf('WIN') > -1) {
  1608. var matchResult = teamARes + ' vs ' + teamBRes;
  1609. var checkStatus = "lerror";
  1610. if (teamARes.indexOf('(win)') > -1) {
  1611. var ta = detachedToRemCtn.find('.teamtext');
  1612. var ta = ta.next();
  1613. ta.prev().html(wonImg);
  1614. }
  1615. if (teamARes.indexOf('(win)') > -1) {
  1616. var tb = detachedToRemCtn.find('teamtext');
  1617. var tb = tb.prev();
  1618. tb.prev().html(wonImg);
  1619. }
  1620. }
  1621.  
  1622. console.log('tatb', ta, tb);
  1623. var msSel = $('body').find('.box-shiny-alt div:eq(4)');
  1624. var matchStatus = msSel.text().trim();
  1625. console.log('matchStatus', matchStatus);
  1626. if (matchStatus !== "") {
  1627. var matchResult = matchStatus;
  1628. var checkStatus = "lerror";
  1629. }
  1630. if (typeof matchResult === "undefined") {
  1631. var matchResult = '<a href="' + matchUrl + '" target="_blank">Could not find result for match #' + matchId + ', check it by clicking here</a>';
  1632. var checkStatus = "lwarning";
  1633. }
  1634. // apppend match status and prepend info
  1635. $('#scriptinfo-box').prepend('<li class="' + checkStatus + ' sticker"><span class="timenow">' + that.tools() + '</span>A match has just been closed:<br /> ' + matchResult + '</li>');
  1636.  
  1637. })
  1638. .fail(function (jqXHR, stringStatus, exceptionObj) { // exceptionObj: "abort", "timeout", "No Transport".
  1639. console.log('REMOVEFAIL:', jqXHR, stringStatus, exceptionObj);
  1640. });
  1641. // append status to ctn and info
  1642. }
  1643. }
  1644. }, function () {
  1645. console.log('E R R O R');
  1646. });
  1647. });
  1648. }
  1649. });
  1650. px.fail(function (jqXHR, stringStatus, exceptionObj) { // exceptionObj: "abort", "timeout", "No Transport".
  1651. var dfd = new jQuery.Deferred();
  1652. promisesUpdateParsing.push(dfd.resolve()); // resolve the item that should have been parsed by promisesUpdateParsing anyway, we need to feed promisesUpdateParsing array to know all available data have been parsed by parseMatchPageData.
  1653.  
  1654. if (exceptionObj) {
  1655. switch (exceptionObj) {
  1656. case 'abort':
  1657. var error = 'abort';
  1658. break;
  1659. case 'timeout':
  1660. var error = 'timeout';
  1661. break;
  1662. case 'No Transport':
  1663. var error = 'No Transport';
  1664. break;
  1665. }
  1666. } else {
  1667. var error = 'error';
  1668. }
  1669. that.monitorWorker("error", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1670. console.log('REQUESTFORAUFAILED:', that.worker, that.job, matchUrl, matchId, matchCtn, jqXHR, stringStatus, exceptionObj);
  1671. var msg = ' There was an error while retrieving match #' + matchId + ' datas. Could not update it for now, trying again in ~' + settings.updateDelay / 1000 / 60 + ' minutes...';
  1672. $('#scriptinfo-box').prepend('<li class="lerror sticker"><span class="timenow">' + that.tools() + '</span>' + msg + '</li>');
  1673. });
  1674. }); // each ended.
  1675.  
  1676. $.when.apply($, promisesUpdateInit)
  1677. .done(function (that) {
  1678. console.log('Fired all methods for worker UPDATEPAGE, all done without errors.');
  1679. $('#force-refresh').removeClass('fr-loading').addClass('fr-notloading');
  1680. })
  1681. .fail(function (that) {
  1682. console.log('Fired all methods for worker UPDATEPAGE, all done WITH ERRORS.');
  1683. $('#force-refresh').removeClass('fr-loading').addClass('fr-notloading');
  1684. });
  1685. });
  1686. /* ---------------- */
  1687. });
  1688. AUmainpage.fail(function (jqXHR, stringStatus, exceptionObj) { // exceptionObj: "abort", "timeout", "No Transport".
  1689. $('#scriptinfo-box').prepend('<li class="lerror sticker"><span class="timenow">' + that.tools() + '</span> Main page request for auto update failed. Site might be overloaded ? If many tries fail again, please disable auto update until site trafic downs.');
  1690. console.log('Main page request for auto update failed.');
  1691. });
  1692. });
  1693. }
  1694. /*
  1695. * @UpdateInitialization()
  1696. *
  1697. getMainPageDistant
  1698. ajaxCalls
  1699. parseMainPage
  1700. initLoading
  1701. each dataG
  1702. ajaxCalls
  1703. monitorWorker
  1704. parseMatchPageData
  1705. compareData
  1706. if add => appendEachMatch
  1707. */
  1708.  
  1709.  
  1710. function FeedsInitialization() {
  1711. var initFeeds = new globalClass('feeds'); // Turn on feeds
  1712. $.when(initFeeds.initGlobalProcess()).then(function (that) {
  1713. pLog('DONE:', 'initGlobalProcess', that);
  1714. return that.globalInfos();
  1715. }).then(function (that) {
  1716. pLog('DONE:', 'globalInfos', that);
  1717. return that.initLoading();
  1718. }).then(function (that) {
  1719. pLog('DONE:', 'initLoading', that);
  1720. that[that.worker] = that.feeds;
  1721. // ask ajaxCalls to request each feeds
  1722. $.each(that.feeds.data, function (index, feedName) {
  1723. var url = that.feeds.feedsDatas[feedName].url;
  1724. var feedContainer = $("#" + feedName + "feed .feedslinks-box ul");
  1725. var job = feedName;
  1726. _log('feedName', that.worker, that.job, url, feedName, feedContainer);
  1727. $.when(that.ajaxCalls(that.worker, that.job, url, feedName, feedContainer, 30000))
  1728. .done(function (data, textStatus, jqXHR) {
  1729. var responseData = jqXHR.responseJSON;
  1730. _log('AJAX CALL DONE', data, textStatus, jqXHR);
  1731. that.monitorWorker("success", "request", feedContainer, feedName);
  1732. // when request is done, process the data.
  1733. $.when(that.appendEachFeed(that.worker, that.job, url, feedName, feedContainer, responseData)).then(function (that, data) {
  1734. that.monitorWorker("success", "view", feedContainer, feedName);
  1735. return that.updateLoading(that.worker, that.job, url, feedName, feedContainer, data);
  1736. });
  1737. })
  1738. .fail(function (jqXHR, stringStatus, exceptionObj) { // exceptionObj: "abort", "timeout", "No Transport".
  1739. if (exceptionObj) {
  1740. switch (exceptionObj) {
  1741. case 'abort':
  1742. var error = 'abort';
  1743. if (feedName === "hltv") {
  1744. $('#hltvfeed .feedslinks-box').append('<li>' + that.errors.feeds.abort + '</li>');
  1745. }
  1746. if (feedName === "reddit") {
  1747. $('#redditfeed .feedslinks-box').append('<li>' + that.errors.feeds.abort + '</li>');
  1748. }
  1749. break;
  1750. case 'timeout':
  1751. if (feedName === "hltv") {
  1752. $('#hltvfeed .feedslinks-box').append('<li>' + that.errors.feeds.timeout + '</li>');
  1753. }
  1754. if (feedName === "reddit") {
  1755. $('#redditfeed .feedslinks-box').append('<li>' + that.errors.feeds.timeout + '</li>');
  1756. }
  1757. var error = 'timeout';
  1758. break;
  1759. case 'No Transport':
  1760. if (feedName === "hltv") {
  1761. $('#hltvfeed .feedslinks-box').append('<li>' + that.errors.feeds.errors + '</li>');
  1762. }
  1763. if (feedName === "reddit") {
  1764. $('#redditfeed .feedslinks-box').append('<li>' + that.errors.feeds.errors + '</li>');
  1765. }
  1766. break;
  1767. }
  1768. } else {
  1769. var error = 'error';
  1770. }
  1771. that.monitorWorker("error", "request", feedContainer, feedName); // monitor global responses status to count how many succeed and failed.
  1772. pLog('Feeds failed to retrieve data', error, feedName, feedContainer);
  1773. });
  1774. });
  1775. }).done(function (that) {
  1776. pLog('DONE:', 'ajaxCalls', that);
  1777. pLog('done all.');
  1778. initFeeds.done();
  1779. });
  1780. }
  1781. /*
  1782. * @Feeds()
  1783. "initGlobalProcess",
  1784. "globalInfos",
  1785. "initLoading",
  1786. "getFeeds",
  1787. "ajaxCalls",
  1788. "appendEachFeed",
  1789. "updateLoading"
  1790. */
  1791.  
  1792. function initialization(initType) {
  1793. // var initGlobal = new globalClass('basicInit'); // init page view only
  1794. var worker = 'initialization'; // default
  1795. switch (initType) {
  1796. case "complete":
  1797. var worker = 'initialization';
  1798. break;
  1799. case "basic":
  1800. var worker = 'basicInit';
  1801. break;
  1802. }
  1803. var initGlobal = new globalClass(worker); // init page view only
  1804. $.when(initGlobal.initGlobalProcess()).then(function (that) {
  1805. pLog('DONE:', 'initGlobalProcess', that);
  1806. return that.initPageView();
  1807. }).then(function (that) {
  1808. pLog('DONE:', 'initPageView', that);
  1809. }).done(function (that) {
  1810. pLog('DONE:', 'BasicInitialization', that);
  1811. if (initType === "basic") { // a basic Init has been requested, finishing.
  1812. return initGlobal.done();
  1813. } else { // a complete init has been requested, continueing.
  1814. CompleteInitialization.call(initGlobal);
  1815. }
  1816. });
  1817. }
  1818. /*
  1819. * @BasicInitialization()
  1820. "initGlobalProcess",
  1821. "initPageView"
  1822. */
  1823. settings.switches.completeinit ? initialization('complete') : initialization('basic');
  1824. if (settings.switches.feeds) {
  1825. FeedsInitialization();
  1826. }
  1827.  
  1828. //UpdateInitialization();
  1829.  
  1830.  
  1831.  
  1832. //var initGlobal = new globalClass('basicInit'); // init page view only
  1833. //var initGlobal = new globalClass('UpdatePage'); // wrap init + get each match infos + appends
  1834.  
  1835. //var initGlobal = new globalClass('initialization'); // wrap init + get each match infos + appends
  1836. //initGlobal.initGlobalProcess();
  1837. //var initFeeds = new globalClass('feeds');
  1838. //initFeeds.initGlobalProcess();
  1839. //
  1840. //var initUpdatePage = new globalClass('UpdatePage'); // init updateData worker
  1841. //initUpdatePage.initGlobalProcess();
  1842. //