CS:GO Lounge Live

A csgolounge.com betting tool and enhancer.

  1. // ==UserScript==
  2. // @name CS:GO Lounge Live
  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. // @include http://*.csgolounge.com/
  9. // @include https://csgolounge.com/
  10. // @include https://csgolounge.com/#
  11. // @include https://*.csgolounge.com/
  12. // @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
  13. // @version 0.2.6.7
  14. // @icon http://img11.hostingpics.net/pics/365638LIVE.png
  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. var defaultTheme = ' \
  28. main {margin:0 auto; text-align:center;}\
  29. .box {display: inline-block;float: none;}\
  30. .standard{display: inline-block;float: none;}\
  31. #feedsbox {display: inline-block;float: none;vertical-align: top;position:relative;}\
  32. body {background-image: none;}\
  33. .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; } \
  34. .shownotav-btn:hover, .button:focus, #switchmainviewa:hover, #switchmainviewa:hover { background-color: #f6f6f6; color:#999;} \
  35. .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; } \
  36. .shownotav { width: 100%; padding: 0 50px; } \
  37. main section.box {width: 68%;};\
  38. .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} \
  39. .vsdetails{width: 10%; float: left; text-align: center;font-size: 16px;} \
  40. .detailsbox {border-radius: 8px; box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.5) inset, 0 1px 1px 0 rgba(255, 255, 255, 0.5); float: left; font-size: 14px; margin: 16px 2%; padding: 2px 2%; width: 59%; display:none;}\
  41. .teamtext {font-size:16px} \
  42. .detailsbox>div { background: none repeat scroll 0 0 #c5c5c5; float: left; margin: 5px 5px 0 0; padding: 5px; }\
  43. .details-betplaced .winsorloses { width:98%; }\
  44. .details-betplaced { min-width: 300px; } \
  45. .details-raw { text-align:left;line-height:16px }\
  46. .c-loading {background-image: url("http://img4.hostingpics.net/pics/5276773011.gif"); height: 100px; position: absolute; width: 100px;}\
  47. .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%;} \
  48. #c-overlay { background-color: rgba(0, 0, 0, 0.5); height: 100%; left: 0; position: absolute; top: 0; width: 100%; z-index: 10; }\
  49. #switchmainview {float: right; display:none;}\
  50. #mainloadingbar li {margin-left: auto; margin-right: auto; width: 260px;}\
  51. .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;}\
  52. .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;} \
  53. .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);} \
  54. .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);} \
  55. .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);}\
  56. .feeds {text-shadow: 1px 1px 0 #e5e5e5;margin: 16px 1%; font-size:14px;}\
  57. #feedsbox {width:29%; margin: 10px 0.5%; overflow-y:auto;}\
  58. .feeds-header {background: url("http://img11.hostingpics.net/pics/396420iconrssgrey.png") no-repeat scroll 0 0 / 33px auto rgba(0, 0, 0, 0)}\
  59. .feedbox-title-inner { float:left; padding: 0 40px;}\
  60. .feedstitle { height: 46px; opacity: 0.7; padding: 1%; text-align: center; text-align:left;}\
  61. .feedstitle a { display: block; height: 100%; width: 100%; } \
  62. #hltvfeed .feedstitle {background: url("http://img15.hostingpics.net/pics/49901496Zhddu.jpg") no-repeat scroll 50% center rgba(0, 0, 0, 0);}\
  63. #redditfeed .feedstitle {background: url("http://img15.hostingpics.net/pics/464286reddit.png") no-repeat scroll 50% center rgba(0, 0, 0, 0);}\
  64. #gosugamersfeed .feedstitle {background: url("http://img15.hostingpics.net/pics/241137gglogo.png") no-repeat scroll 50% center rgba(0, 0, 0, 0);}\
  65. .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%; } \
  66. .feedslinks-box {margin: 0 2% 16px;padding-top: 5px; text-align:left;}\
  67. .feedslinks-box table { border: 1px solid #bbbbbb; width: 100%; }\
  68. .feedslinks-box tr:nth-child(odd) { background-color: #bbbbbb; }\
  69. .feedslinks-box tr:nth-child(even) { background-color: #cccccc; }\
  70. .feedslinks-box td { border-bottom: 1px solid #dddddd; padding: 4px; }\
  71. #feedsbox .feedslinks-box tr:hover { background:#aaa; }\
  72. .feedslinks-box a {display: block;}\
  73. .feedslinks-box a:hover {opacity: 0.8; transition: 0.5s;}\
  74. .main-feedbox2 { background-color: #d0d0d0; 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%;}\
  75. .main-feedbox { background-color: #d0d0d0; border-radius: 5px;float: left;box-shadow: 1px 1px 1px 1px #bbb; width: 100%; border: 1px solid #bbb;}\
  76. .line2a { padding-left: 10px; text-align: center;font-size: 14px;}\
  77. .line2b { padding-right: 10px; text-align: center;font-size: 14px;}\
  78. .matchbox-summary { float: left; font-size: 12px; margin: 16px 0; width: 15%;}\
  79. .expandmatch-btn { color: #ddd; position:absolute; height: 20px; padding-left: 7px; font-size:20px;}\
  80. .expmatchbtn-ctn { float: right; margin-right: 9px; height: 25px; width: 25px;}\
  81. .infosbelow-lr {width: 35%; float: left;}\
  82. .infosbelow-center { float: left; font-size: 14px; text-align: center; width: 30%; } \
  83. .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;clear:both;}\
  84. .suminfo {}\
  85. .suminfo-info{background: url("http://img11.hostingpics.net/pics/344354iconinfov3.png") no-repeat scroll 2px center / 14px auto #ababab}\
  86. .suminfo-bet{background: url("http://img15.hostingpics.net/pics/666500Dice.png") no-repeat scroll 2px center / 16px auto #ababab}\
  87. .matchbox-summary .betplaced { background: url("http://img11.hostingpics.net/pics/788665dicegreen.png") no-repeat scroll 2px center / 16px auto #ababab; } \
  88. .suminfo-warning{background: url("http://img15.hostingpics.net/pics/701001warning16x16.png") no-repeat scroll 2px center / 14px auto #ababab}\
  89. .suminfo-error{background: url("http://img15.hostingpics.net/pics/477689error16x16.png") no-repeat scroll 2px center / 14px auto #ababab}\
  90. .suminfo-error:hover{background: url("http://img15.hostingpics.net/pics/477689error16x16.png") no-repeat scroll 2px center / 14px auto #D7D7D7; transition: 0.5s; opacity: 0.9;}\
  91. 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;}\
  92. 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;}\
  93. .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: 13px 75%;}\
  94. #feedstitle-loading {float: right; margin: 5px 15px 0 0; position:relative; width: 50px; background:url("http://img11.hostingpics.net/pics/460422feedstitleloading.gif") no-repeat scroll 3px center transparent;} \
  95. aside#submenu {float:left;opacity: 0.9;border-radius: 0 0 10px;}\
  96. main {padding-right:0;}\
  97. #submenutoggle { background: none repeat scroll 0 0 #252525; float: right; font-size: 30px; height: 40px; opacity: 1; text-align: center; width: 200px; }\
  98. aside#submenu > nav {margin:0}\
  99. #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;}\
  100. #shortsmblink { color: #ff8a00;}\
  101. .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; }\
  102. .matchloading-ctn { float: left; height: 50px; margin: 5px; position: absolute; width: 50px; }\
  103. #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; }\
  104. .infobox-ctn { background: none repeat scroll 0 0 #fff; border: 1px solid #ccc; border-radius: 3px; padding: 10px; text-align: center; }\
  105. #settings-aliases {padding:5px 0;}\
  106. 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; } \
  107. 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;} \
  108. 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;} \
  109. label:active i:before { box-shadow: inset 0 1px 0 0 rgba(0, 0, 0, 0.3); } \
  110. label:before { content: "off"; margin-left: 20px; text-transform: uppercase; transition: all 200ms ease; } \
  111. input[type=checkbox]:checked ~ label:before { content: "on"; text-transform: uppercase; margin-right: 30px; margin-left: 5px; } \
  112. 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%); } \
  113. input[type=checkbox]:checked ~ label i { right: 0px; } \
  114. input[type=checkbox] { display:none; }\
  115. .matchmain { text-shadow: 0 1px 1px #ffffff; }\
  116. .match {box-shadow:1px 2px 2px 2px #888;}\
  117. .title { color: #999; float: left; position: relative; width: 98%;padding: 1% 1% 0;margin-left:0;text-transform: none;} \
  118. .title:hover a {color: #999; text-shadow: none;}\
  119. .title a{ color: #999; text-shadow: none;} \
  120. #mainheader a:hover{ color: #777; text-shadow: none;} \
  121. #mainheader { font-weight: 300; line-height: 16px;min-height: 40px;float:left; color: #777;font-size: 12px;width: 100%;border: 1px solid #ccc;}\
  122. #mainheader .nomatchesfound {text-align:center;}\
  123. #mainheader li { margin: 3px; padding: 2px;}\
  124. .mainheader-c {}\
  125. .bets-header {background:url("http://cdn.csgolounge.com/img/bets.png") no-repeat;}\
  126. .mh-boxes {}\
  127. .mh-left {width:20%;float:left;padding:2px;}\
  128. .mh-center {width:50%;padding: 0 2px; margin:0 auto; text-align:center;max-height: 90px;}\
  129. .mh-right {width:175px;float:right;padding: 0 2px;}\
  130. #matchescount li {margin: 3px 0 0;}\
  131. #current-matchescount {font-weight:bold;}\
  132. 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;border-top: 1px solid #eee;} \
  133. .austatus { font-weight: bold; text-align: center;}\
  134. .austatus-inner { font-weight: normal; text-align:left; margin-top: 5px;}\
  135. .numofm, .numofb {font-weight:bold;}\
  136. .au-lasttime { float:right; font-weight:bold;color: #8a8a8a;}\
  137. .au-timeleft { float:right; font-weight:bold;color: #8a8a8a;}\
  138. .scriptinfo-header {}\
  139. #scriptinfo-box {font-size:12px;opacity:0.9;overflow-y:auto; max-height:80px; border: 1px solid #ccc;}\
  140. #scriptinfo-box .linfo {background: url("http://img15.hostingpics.net/pics/169315info16x16.png") no-repeat 2px center scroll rgba(0, 0, 0, 0);}\
  141. #scriptinfo-box .lwarning {background: url("http://img15.hostingpics.net/pics/701001warning16x16.png") no-repeat 2px center scroll rgba(0, 0, 0, 0);}\
  142. #scriptinfo-box .lerror {background: url("http://img15.hostingpics.net/pics/477689error16x16.png") no-repeat scroll 2px center rgba(0, 0, 0, 0);}\
  143. #mainheader #scriptinfo-box li { margin: 0;} \
  144. .scriptinfo-hide { font-size: 20px; left: 73%; line-height: 15px; position: absolute; }\
  145. .timenow {float: left; margin-left: 20px;}\
  146. .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;}\
  147. .timeleft { color: #666; font-size: 13px; font-weight:bold}\
  148. .timeRaw {font-size: 10px;}\
  149. .eventm { color: #333; float: right; font-size: 12px; }\
  150. .lspacer:after { content: "|"; }\
  151. .matchheader span { float: left;} \
  152. .lspacer { color: #777; font-size: 6px;}\
  153. .lspacer-mh { margin: 0 10px; }\
  154. .lspacer-tc { vertical-align: middle;}\
  155. .matchstatus .matchislive {color: #72A326; text-shadow: 1px 1px 0px #4A7010; font-weight: bold;font-size: 12px;}\
  156. .matchstatus .important-matchinfo {font-weight: bold; color: #D12121;font-size: 12px;}\
  157. #force-refresh-ctn {float:right;}\
  158. #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; }\
  159. #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;}\
  160. .matchid { font-size:10px; }\
  161. .detailsbox p strong { font-weight: bold; } \
  162. .detailsbox p { text-align:left; } \
  163. ';
  164. GM_addStyle(defaultTheme);
  165. // Grey scheme: Foreground color = #333333 // Background color = #bbbbbb
  166.  
  167. var scriptVersion = GM_info.script.version;
  168. //console.log(version);
  169. var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
  170. console.log('@Greasemonkey/@Tampermonkey settings:', GM_info);
  171. console.log('@JQuery: ', $.fn.jquery);
  172. console.log('@CSGLounge Live version:', scriptVersion);
  173.  
  174. // Global settings
  175. var settings = {
  176. "debug": {
  177. "global": false, // activates _log
  178. "feeds": "0",
  179. "autoUpdate": false // activate detailed autoupdate logging
  180. },
  181. "matchBoxStatus": "0", // Main view, boxes open, closed. feature disabled.
  182. "mainMenuStatus": "0", // 1 Show, 0 Hide main menu
  183. "updateDelay": "300000", // 5 mins = 300 seconds (*1000)
  184. "defaultTimeout": "10000", // 10 seconds
  185. "switches": {
  186. "completeinit": true,
  187. "feeds": true,
  188. "autoupdate": true,
  189. "feedsShow": true
  190. },
  191. "isNewVersion": {
  192. "oldVersion": "",
  193. "newVersion": "",
  194. "status": false
  195. },
  196. "isCsgo": true
  197. };
  198. // debug (forces settings rewrite)
  199. //localStorage.setItem("loungeLiveSettings", JSON.stringify(settings));
  200.  
  201. var host = window.location.host;
  202. if (host == "csgolounge.com") {
  203. settings.isCsgo = true;
  204. }
  205. ;
  206. if (host == "dota2lounge.com") {
  207. settings.isCsgo = false;
  208. }
  209. ;
  210.  
  211. /* Check for a newer version not elegant at all, will do that in a proper way later*/
  212. var scriptVersionChecker = (localStorage.getItem('loungeLive_lastversion') != scriptVersion);
  213. if (scriptVersionChecker) {
  214. var currentVersion = localStorage.getItem('loungeLive_lastversion');
  215. localStorage.setItem("loungeLive_lastversion", scriptVersion);
  216. settings.isNewVersion.oldVersion = currentVersion;
  217. settings.isNewVersion.newVersion = scriptVersion;
  218. settings.isNewVersion.status = true;
  219. localStorage.removeItem("loungeLiveSettings");
  220. localStorage.setItem("loungeLiveSettings", JSON.stringify(settings));
  221. }
  222.  
  223. var globalJobStatus = []; // global status for job to track if they are finished or not.
  224. var globalData = {
  225. "count": {
  226. "matchesAvail": 0,
  227. "betsPlaced": 0
  228. }
  229. };
  230.  
  231. if (localStorage.getItem("loungeLiveSettings") !== null) {
  232. settings = JSON.parse(localStorage.getItem("loungeLiveSettings"));
  233. console.log('@CSGLounge Live settings:', localStorage.getItem('loungeLiveSettings'));
  234. }
  235.  
  236. // get base url in ff.
  237. if (!isChrome) {
  238. var baseUrl = window.location.href;
  239. var regexp = /.*\/(.*?)$/;
  240. var match = regexp.exec(baseUrl);
  241. if (match[1] === '#') {
  242. var baseUrl = baseUrl.replace('#', '');
  243. }
  244. } else {
  245. var baseUrl = "https://csgolounge.com/";
  246. }
  247.  
  248. /*********************/
  249. /* DEBUG AND HELPERS */
  250. /*********************/
  251. // debug log if activated
  252. if (!isChrome) {
  253. _log = (function (undefined) { // if firefox
  254. var Log = Error; // proper inheritance...?
  255. Log.prototype.write = function (args) {
  256.  
  257. var lineNum = extractLineNumberFromStack(this.stack);
  258. var lineNumberStr = [[lineNum]];
  259. args = args.concat(lineNumberStr);
  260. args = sortArray(args);
  261. // console.log(args);
  262. if (console && console.log) {
  263. if (console.log.apply) {
  264. console.log.apply(console, args);
  265. } else {
  266. console.log(args);
  267. } // nicer display in some browsers
  268. }
  269. };
  270. var extractLineNumberFromStack = function (stack) {
  271.  
  272. var lineNum = stack.split('\n')[1];
  273. var lineNum = lineNum.split(' (')[0].substring(0, lineNum.length - 1);
  274. var lineNum = lineNum.split(':')[3].substring(0, lineNum.length - 1);
  275. return lineNum;
  276. };
  277. var sortArray = function (arrayTosort) { // swap 1st and last value.
  278. argsNew = [];
  279. for (var i = 0; i < arrayTosort.length; i++) {
  280. var j = i + 1;
  281. argsNew[j] = arrayTosort[i];
  282. }
  283.  
  284. var lastItem = argsNew.pop();
  285. argsNew[0] = lastItem;
  286. return argsNew;
  287. };
  288. return function (params) {
  289.  
  290. if (typeof settings.debug.global !== undefined || settings.debug.global)
  291. return;
  292. Log().write(Array.prototype.slice.call(arguments, 0));
  293. };
  294. })();
  295. } else {
  296. _log = function (args) {
  297. if (settings.debug.global) {
  298. console.log(args);
  299. }
  300. };
  301. }
  302. pLog = _log;
  303. auLog = function (args) {
  304. // console.log(['AU:'],' ', args);
  305. console.log(['AU:'], ' ', Array.prototype.slice.call(arguments, 0));
  306. };
  307. /* log tool */
  308. window.log = function () {
  309. log.history = log.history || []; // store logs to an array for reference
  310. log.history.push(arguments);
  311. if (this.console && settings.debug.global) {
  312. console.log(Array.prototype.slice.call(arguments));
  313. }
  314. };
  315. l = function (args) {
  316. console.log(args);
  317. };
  318. _l = function (args) {
  319. console.log(args);
  320. };
  321.  
  322. /****************/
  323. /* SCRIPT START */
  324. /****************/
  325. /* Global Class - wrap basically every workers jobs - process detailled below... */
  326. function globalClass(worker) {
  327. var self = this;
  328. this.worker = worker;
  329. this.job = {};
  330. this.job.init = true;
  331. this.job.done = false;
  332. this.job.update = false;
  333. this.job.retrieveMissing = false;
  334. this[this.worker] = {"data": []};
  335. console.log("Initializing INSTANCE for worker", this.worker, '', this[this.worker]);
  336. // matches ajax req errors & loading
  337. this.loading = {};
  338. this.loading.matchdiv = '<div class="matchloading-ctn"><div class="matchloading"></div></div>';
  339. // If error on retrieve is returned by matches ajax request: // errors.JOB.STRING
  340. this.errors = {};
  341. this.errors.match = {};
  342. this.errors.feeds = {};
  343. this.errors.match.aborted = 'Aborted';
  344. this.errors.match.timedOut = 'Timed out';
  345. this.errors.match.error = 'Error';
  346. this.errors.match.RetrieveFailedMatches = " item(s) failed to load."; // <a href='#' class='retrieve-failedmatches'>Retrieve missing item(s)</a>
  347. this.errors.feeds.timeout = "Feeds api didn't respond in time, please try again in one minute...";
  348. this.errors.feeds.abort = "Abort error, please try again later...";
  349. this.errors.feeds.errors = "There was an error, feeds api might be empty at the moment, please try again later...";
  350. this.liveNow = '<span class="matchislive">&nbsp; Live !</span>';
  351.  
  352. this.lbtnSw = '<img src="http://img11.hostingpics.net/pics/677948livelogo.png" alt="Back to lounge Live">Lounge Live';
  353. this.showTradesbtnSw = '<img alt="Show trades" src="//cdn.csgolounge.com/img/my_trades.png">show trades';
  354.  
  355. 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><span id="feedstitle-loading" class="feedloading"></span></div></div></section>';
  356.  
  357. this.feeds = {
  358. "data": [
  359. "reddit", "hltv"
  360. ],
  361. "feedsDatas": {
  362. "reddit": {
  363. "url": "https://vast-harbor-8484.herokuapp.com/api?feed=reddit",
  364. "datas": ""
  365. },
  366. "hltv": {
  367. "url": "https://vast-harbor-8484.herokuapp.com/api?feed=hltv",
  368. "datas": ""
  369. }
  370. }
  371. };
  372.  
  373. this.propsContainers = {
  374. "bestOf": ".infosbelow-center",
  375. "dateRaw": ".dateRaw",
  376. "matchStatus": ".matchstatus",
  377. "hasItemsPlaced": "",
  378. "itemsPlaced": "",
  379. "mainstream": "",
  380. "matchNameA": ".teamtext:eq(0) b",
  381. "matchNameB": ".teamtext:eq(1) b",
  382. "msstatus": "",
  383. "peopleItemsNum": ".peopleItemsNum",
  384. "teamAReward": ".infosbelow-lr span:eq(0)",
  385. "teamAperc": ".teamtext:eq(0) i",
  386. "teamBReward": ".infosbelow-lr span:eq(1)",
  387. "teamBet": "",
  388. "teamBperc": ".teamtext:eq(1) i",
  389. "timeLeft": ".timeleft",
  390. "timeRaw": ".timeRaw",
  391. "valueBetA": "",
  392. "valueBetB": ""
  393. };
  394. // build an array containing all properties.
  395. var buildPropList = function (propsContainers) {
  396. var propsList = [];
  397. for (var properties in propsContainers) {
  398. propsList.push(properties);
  399. }
  400. return propsList;
  401. };
  402. this.propList = buildPropList(this.propsContainers);
  403. this.arrow = {};
  404. this.arrow.up = '<span style="color: green;">&#8593;</span>';
  405. this.arrow.down = '<span style="color: red;">&#8595;</span>';
  406. this.arrow.equal = '&nbsp;';
  407. this.arrow.err = '&nbsp;';
  408. } /* ! globalClass(worker)*/
  409.  
  410.  
  411. globalClass.prototype.initGlobalProcess = function () {
  412. _log('*** Global INIT for worker ' + this.worker + ' ***');
  413. var dfd = new jQuery.Deferred();
  414. return dfd.resolve(this);
  415. }; // !initGlobalProcess
  416.  
  417. /*
  418. * monitorWorker method
  419. * @param {type} jobStatus = error || success
  420. * @param {type} container
  421. * @param {type} jobType = view || request
  422. * @param {type} id
  423. * @param {type} errorType = error details - eq. timeout, abort etc...
  424. * @feedsObj :
  425. loadingStatus.
  426. "index": 0,
  427. "totalItemsToLoad": dataLength,
  428. "globalMonitor": {
  429. "error": {"view" : 0, "request" : 0, "IDs" : [], "ctn" : []},
  430. "success": {"view" : 0, "request" : 0, "IDs" : [], "ctn" : []},
  431. "mustRetry": []
  432. }
  433. */
  434. globalClass.prototype.monitorWorker = function (jobStatus, jobType, container, id, errorType) { // jobStatus = error || success, jobType = view || request, errorType = error details - eq. timeout, abort etc...
  435. _log('... currently monitoring "' + this.worker + '" worker ...');
  436. // monitor global responses status to count how many succeed and failed.
  437. var globalMonitor = this[this.worker].loadingStatus.globalMonitor; // example. this.initialization.loadingStatus.globalMonitor
  438. // console.log('MONITOR', globalMonitor[jobStatus][jobType], jobType)
  439.  
  440. globalMonitor[jobStatus].IDs.push(id);
  441. globalMonitor[jobStatus].ctn.push(container);
  442. globalMonitor[jobStatus][jobType]++; // example. currentObj.success.view = 6.
  443.  
  444. if (jobType === "view") { // update loading status when append are done.
  445. this[this.worker].loadingStatus.index = (++this[this.worker].loadingStatus.index);
  446. }
  447. // if(jobStatus === "error") { // send error to errorHandling method
  448. // this.errorHandling(jobStatus, jobType, container, id, "global");
  449. // }
  450.  
  451. };
  452. globalClass.prototype.errorHandling = function (jobStatus, jobType, container, id, errorType) {
  453. var globalMonitor = this[this.worker].loadingStatus.globalMonitor; // example. this.initialization.loadingStatus.globalMonitor
  454.  
  455. if (this.worker === "initialization" && jobType === "request") { // error
  456. $('#scriptinfo-box').prepend('<li class="lerror sticker"><span class="timenow">' + this.tools() + '</span>An error occured (' + errorType + ') while requesting match #' + id + '.</li>');
  457. container.find('.matchloading-ctn').remove();
  458. container.append(this.errors.match[errorType]);
  459.  
  460. var summDest = container.find('.matchleft');
  461. var hasMBSumm = container.find('.matchbox-summary').length > 0 ? true : false;
  462. if (!hasMBSumm) {
  463. summDest.after('<div class="matchbox-summary"></div>');
  464. }
  465. var matchboxSummary = container.find('.matchbox-summary');
  466. var infoSticker = '<span class="sumbox suminfo-error firstretrieveerr"><a class="maindata-retrieve" href="#" title="Retrieve infos for this match manually"> Not up-to-date! (' + this.errors.match[errorType] + ') <br /> Click here to retrieve infos manually.</a></span>';
  467. matchboxSummary.html(infoSticker).delay(50).fadeOut().fadeIn('slow');
  468.  
  469. setTimeout(function () {
  470. $('#mainloadingbar').fadeOut('slow');
  471. $('#matchescount').fadeOut('slow');
  472. }, 5000);
  473. }
  474.  
  475. if (errorType === "done") {
  476. $('#scriptinfo-box').prepend('<li class="lerror sticker"><span class="timenow">' + this.tools() + '</span>' + globalMonitor.error.request + this.errors.match.RetrieveFailedMatches);
  477. }
  478.  
  479. };
  480. globalClass.prototype.done = function () {
  481. console.log('ALLDONE: worker ', this.worker, ' has finished his jobs. obj:', this);
  482.  
  483. // init is done
  484. if (this.worker === "initialization" && this.job.init && !this.job.retrieveMissing) {
  485. var globalMonitor = this[this.worker].loadingStatus.globalMonitor; // example. this.initialization.loadingStatus.globalMonitor
  486.  
  487. // store data in globalData obj
  488. globalData.currentData = {};
  489. globalData.currentData = this[this.worker].data;
  490. // check for errors
  491. if (globalMonitor.error.request > 0) {
  492. this.errorHandling("error", "", "", "", "done");
  493. }
  494. if (globalMonitor.error.request === 0) {
  495. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + this.tools() + '</span> ' + this.worker + ' done successfully.');
  496. }
  497. if (settings.isNewVersion.status) {
  498. if (currentVersion === null) {
  499. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + this.tools() + '</span> Welcome to Lounge Live version ' + scriptVersion + ', everything loaded successfully. Enjoy !</li>');
  500. } else if (typeof currentVersion !== "undefined") {
  501. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + this.tools() + '</span> Read more info about this update on <a href="https://www.reddit.com/r/LoungeLive/" target="_blank">Lounge Live subreddit</a>.</li>');
  502. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + this.tools() + '</span> Lounge Live has updated from version ' + currentVersion + ' to ' + scriptVersion + ' successfully.</li>');
  503. settings.isNewVersion.status = false;
  504. localStorage.setItem("loungeLiveSettings", JSON.stringify(settings));
  505. // if (this.worker === "initialization" || this.worker === "basicInit") {
  506. if (isChrome) {
  507. if ($('body').css('background').indexOf('imgur') > -1) {
  508. var msgs = 'You probably have CleanLounge theme enabled';
  509. var msge = ' Unfortunately, this script is currently not compatible with this theme. Even though it\'s compatible with Lounge Destroyer add-on. Please disable CleanLounge Theme for a proper layout.';
  510. $('#scriptinfo-box').prepend('<li class="lerror sticker"><span class="timenow">' + this.tools() + '</span>' + msgs + msge);
  511. alert(msgs + '\n Please disable CleanLounge Theme for a proper layout.');
  512. }
  513. }
  514. // }
  515. }
  516. var self = this;
  517. /* MAIN STYLE*/
  518. if (!isChrome) {
  519. var mainStyle = $('head link[type="text/css"]').attr('href');
  520. if (typeof mainStyle != "undefined") {
  521. var mainStyle = mainStyle.replace(/\d+$/, '');
  522. if (mainStyle != '//cdn.csgolounge.com/css/gray.min.css?') {
  523. $.ajax({
  524. method: 'GET',
  525. url: 'ajax/setSkin?skin=1',
  526. success: function (response) {
  527. console.log(response);
  528. }
  529. });
  530. $('head link[type="text/css"]').attr('href', "//cdn.csgolounge.com/css/gray.min.css?");
  531. }
  532. }
  533. }
  534. }
  535. }
  536. if (this.job.retrieveMissing) {
  537. var globalMonitor = this[this.worker].loadingStatus.globalMonitor; // example. this.initialization.loadingStatus.globalMonitor
  538. if (globalMonitor.error.request === 0) {
  539. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + this.tools() + '</span> Missing match(es) was/were retrieved successfully');
  540. }
  541. console.log('RETRIEVEMISSING', globalMonitor, globalMonitor.error.request, globalMonitor.success.IDs);
  542. }
  543. var dfd = new jQuery.Deferred();
  544. return dfd.resolve(this);
  545. };
  546. globalClass.prototype.initPageView = function () {
  547. _log('*** init Page View ***');
  548.  
  549. var self = this;
  550. // logo
  551. if (settings.isCsgo) {
  552. $('body').find('header a:eq(0)').html('<img id="logo" alt="CS:GO Marketplace" src="http://img11.hostingpics.net/pics/797445csgllivelogo4.png">');
  553. }
  554. /*
  555. * http://img11.hostingpics.net/pics/797445csgllivelogo4.png
  556. * http://img11.hostingpics.net/pics/501830csgllivelogo.png
  557. * http://img11.hostingpics.net/pics/926464csgllivelogo2.png
  558. * http://img11.hostingpics.net/pics/357697csgllivelogo3.png
  559. */
  560.  
  561. // Main view, boxes open, closed.
  562. initialization.matchBoxStatus = ' style="display:none;"';
  563. // hide main trade box
  564. $('#tradelist').parent().hide();
  565. $('#tradelist').hide();
  566. // Hide not available, add button
  567. var firstna = $('.matchmain .notavailable:first').parent();
  568. firstna.nextAll().andSelf().wrapAll("<div id='sh-na' style='display:none;'></div>")
  569. .parent().before('<a href="#" class ="shownotav-btn shownotav"><span>Show closed matches</span></a>');
  570. $("body").on("click", "a.shownotav-btn", function (e) {
  571. $('a.shownotav-btn').remove();
  572. $('#sh-na').slideDown('slow');
  573. e.preventDefault();
  574. });
  575. // Page Header
  576. $('.title, #bets').removeAttr('style');
  577. //matchheader
  578. $('.title:eq(1)').html('<div id="mainheader" class="bets-header mainheader-c"></div>');
  579. $('#mainheader').append('<div class="mh-boxes mh-left"><ul></ul> </div>');
  580. $('#mainheader').append('<div class="mh-boxes mh-right"><ul></ul></div></div>');
  581. $('#mainheader').append('<div class="mh-boxes mh-center"><ul id="scriptinfo-box"></ul></div>');
  582. $('.mh-left ul').append('<li class="sticker topcounts"></li>');
  583. if (settings.switches.autoupdate) {
  584. $('.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>');
  585. }
  586. $('.mh-center').prepend('<span class="scriptinfo-header">Lounge Live version: ' + scriptVersion + ' - <a href="https://www.reddit.com/r/LoungeLive/" target="_blank" title="Report a bug, suggest a feature, read change logs.">reddit</a> - <a target="_blank" href="https://steamcommunity.com/tradeoffer/new/?partner=81839980&token=VqSHKQT0" title="support the cause !">steam donation</a></span>');
  587. $('.mh-center').prepend('<span class="scriptinfo-hide"><a href="#" title="Hide errors and warnings">-</a></span>');
  588.  
  589. //matchheader
  590. $('.mh-right ul').append('<li>Matches Infos: <input type="checkbox" id="completeinit-switch" /> <label for="completeinit-switch" > <i></i> </label></li>');
  591. $('.mh-right ul').append('<li>Feeds: <input type="checkbox" id="feeds-switch" /> <label for="feeds-switch" > <i></i> </label></li>');
  592. $('.mh-right ul').append('<li>Auto Update: <input type="checkbox" id="autoupdate-switch" /> <label for="autoupdate-switch"> <i></i> </label></li>');
  593. $('.mh-right ul').append('<li>Feeds box: <input type="checkbox" id="feedsShow-switch" /> <label for="feedsShow-switch"> <i></i> </label></li>');
  594.  
  595. // Switches status
  596. $('#completeinit-switch').attr('checked', settings.switches.completeinit);
  597. $('#feeds-switch').attr('checked', settings.switches.feeds);
  598. $('#feedsShow-switch').attr('checked', settings.switches.feedsShow);
  599. $('#autoupdate-switch').attr('checked', settings.switches.autoupdate);
  600. $("#mainheader").on("click", "input#completeinit-switch", function (e) {
  601. if ($('input#completeinit-switch').is(":checked")) {
  602. settings.switches.completeinit = true;
  603. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Matches infos have been activated.</li>');
  604. } else {
  605. if (settings.switches.autoupdate) {
  606. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Auto update disable have been forced.</li>');
  607. }
  608. settings.switches.completeinit = false;
  609. settings.switches.autoupdate = false;
  610. $('#autoupdate-switch').attr('checked', settings.switches.autoupdate);
  611. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Matches infos have been disabled.</li>');
  612. }
  613. localStorage.setItem("loungeLiveSettings", JSON.stringify(settings));
  614. });
  615. $("#mainheader").on("click", "input#feeds-switch", function (e) {
  616. settings.switches.feeds = $('input#feeds-switch').is(":checked") ? true : false;
  617. localStorage.setItem("loungeLiveSettings", JSON.stringify(settings));
  618. if (!settings.switches.feeds) {
  619. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Feeds have been disabled.</li>');
  620. }
  621. if (settings.switches.feeds) {
  622. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Feeds have been activated.</li>');
  623. }
  624. });
  625. $("#mainheader").on("click", "input#autoupdate-switch", function (e) {
  626. if ($('input#completeinit-switch').is(":checked") === false) {
  627. $('#autoupdate-switch').attr('checked', false);
  628. alert('Turn on "matches infos" first.');
  629. $('#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>');
  630. } else {
  631. settings.switches.autoupdate = $('input#autoupdate-switch').is(":checked") ? true : false;
  632. localStorage.setItem("loungeLiveSettings", JSON.stringify(settings));
  633. if (!settings.switches.autoupdate) {
  634. clearInterval(window.autoUpdate);
  635. clearInterval(window.autoUpdateTimer);
  636. $('.au-timeleft').html('-');
  637. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Auto update has just been stopped and disabled.</li>');
  638. }
  639. if (settings.switches.autoupdate) {
  640. $('#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>');
  641. }
  642. }
  643.  
  644.  
  645. });
  646. $("#mainheader").on("click", "input#feedsShow-switch", function (e) {
  647. settings.switches.feedsShow = $('input#feedsShow-switch').is(":checked") ? true : false;
  648. localStorage.setItem("loungeLiveSettings", JSON.stringify(settings));
  649. if (!settings.switches.feedsShow) {
  650. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Feeds box is now hidden.</li>');
  651. $('#feedsbox').hide();
  652. }
  653. if (settings.switches.feedsShow) {
  654. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>Feeds box is now shown.</li>');
  655. $('#feedsbox').fadeIn('fast');
  656. }
  657. });
  658. // Hide lerror, lwarning in scriptinfo box
  659. $('#mainheader').on('click', '.scriptinfo-hide', function (e) {
  660. $('.lerror').slideToggle('fast');
  661. $('.lwarning').slideToggle('fast');
  662. $('.scriptinfo-hide a').text($('.lwarning').is(':visible') || $('.lerror').is(':visible') ? '+' : '-');
  663. e.preventDefault();
  664. });
  665.  
  666. // Big Main Switch Button
  667. //$('#mainheader').append('<div id="switchmainview"><a href="#" id="switchmainviewa" class="rounded-btn1"><span>' + btnMatchBoxStatus + '</span></a></div>')
  668.  
  669. $("#switchmainview").on("click", "a#switchmainviewa", function (e) {
  670. $(".detailsbox").slideToggle("fast", function () {
  671. $("#switchmainviewa span").text($('.detailsbox').is(':visible') ? "-" : "+");
  672. });
  673. e.preventDefault();
  674. });
  675. // Boxes expander
  676. $("#bets").on("click", "a.expandmatch-btn-a", function (e) {
  677. var $alinktext = $(e.target);
  678. var $detailsbox = $(e.target).parents().eq(2).find('.detailsbox');
  679. $detailsbox.slideToggle("fast", function () {
  680. $alinktext.text($detailsbox.is(':visible') ? "-" : "+");
  681. });
  682. e.preventDefault();
  683. });
  684. // SubMenu
  685. $('aside#submenu').prepend('<a id="submenutoggle"><span href="#" id="submenutogglelink">&#8592;</span></a>');
  686. $("#submenu").after('<a id="shortsmb" style="display:none;"><span id="shortsmblink" href="#">&#8600;</span></a>');
  687. if (settings.mainMenuStatus == '0') {
  688. $('aside#submenu').hide();
  689. $('#shortsmb').show();
  690. }
  691.  
  692. $("body").on("click", "a#shortsmb", function (e) {
  693. $('#shortsmb').hide('fast');
  694. $("aside#submenu").show("slide");
  695. settings.mainMenuStatus = '1';
  696. localStorage.setItem("loungeLiveSettings", JSON.stringify(settings));
  697. });
  698. $("#submenu").on("click", "a#submenutoggle", function (e) {
  699. $("aside#submenu").hide("slide", function () {
  700. $('#shortsmb').show();
  701. settings.mainMenuStatus = '0';
  702. localStorage.setItem("loungeLiveSettings", JSON.stringify(settings));
  703. });
  704. });
  705. // Error link when a matchbox has failed to retrieve matchInfos
  706. // NOTE: USE initialization worker FOR THIS
  707. $(".match").on("click", "a.maindata-retrieve", function (e) {
  708. self.job.retrieveMissing = true;
  709. self.job.init = false;
  710. var selector = $(this).closest('.matchmain');
  711. selector.find('.error').remove();
  712. CompleteInitialization.call(self, self.worker, selector);
  713. e.preventDefault();
  714. });
  715. $("#error-matchesload").on("click", "a.retrieve-failedmatches", function (e) {
  716. var selector = self[self.worker].loadingStatus.globalMonitor.error.ctn;
  717. $('#error-matchesload').empty();
  718. $(selector).each(function (index, value) {
  719. value.find('.error').remove();
  720. });
  721. CompleteInitialization.call(self, this.worker, selector);
  722. e.preventDefault();
  723. });
  724. $("#force-refresh-ctn").on("click", "a#force-refresh", function (e) {
  725. console.log('refreshing auto update..');
  726. self.infobox('info', 'Forcing a page refresh...');
  727. $('#force-refresh').removeClass('fr-notloading').addClass('fr-loading');
  728. // clearInterval(window.autoUpdate);
  729. // clearInterval(window.autoUpdateTimer);
  730. // self.autoUpdateTimers();
  731. // UpdateInitialization();
  732. // window.autoUpdate = setInterval(function () {
  733. // self.autoUpdateTimers();
  734. UpdateInitialization();
  735. // FeedsInitialization();
  736. // }, settings.updateDelay);
  737. e.preventDefault();
  738. });
  739. // infobox
  740. $('main').append('<div id="infobox-wrapper" style="display: none;"><div class="infobox-ctn"></div></div>');
  741. // show trades
  742. $('#menu').append('<a href="#" class="showtrades"><img alt="Show trades" src="//cdn.csgolounge.com/img/my_trades.png">show trades</a>');
  743.  
  744. $("#menu").on("click", "a.showtrades", function (e) {
  745. var ptl = [];
  746. ptl.push($('.box:eq(1)').fadeToggle('slow')); // matchbox
  747. ptl.push($('.box:eq(0)').fadeToggle('slow')); // trade box
  748. ptl.push($('.box:eq(0) #tradelist').fadeToggle('slow')); // tradebox inner
  749. $.when.apply($, ptl)
  750. .done(function () {
  751. ($('.box:eq(1)').is(':visible') && !$('.box:eq(0)').is(':visible')) ? $('a.showtrades').hide().html(self.showTradesbtnSw).fadeIn('fast') : $('a.showtrades').hide().html(self.lbtnSw).fadeIn('fast');
  752. });
  753. e.preventDefault();
  754. });
  755. // Feedbox floating
  756. $(window).on("scroll", window, function (e) {
  757. var a = $(window).scrollTop();
  758. var b = $(window).height();
  759. if (a >= 74) {
  760. $('#feedsbox').css("top", a - 74);
  761. $('#feedsbox').css("max-height", b);
  762. }
  763. if (a <= 74) {
  764. $('#feedsbox').css("top", 0);
  765. $('#feedsbox').css("max-height", b - 74);
  766. }
  767. });
  768. $(window).bind("resize", function () {
  769. var a = $(window).scrollTop();
  770. var b = $(window).height();
  771. if (a >= 74) {
  772. $('#feedsbox').css("max-height", b);
  773. }
  774. if (a <= 74) {
  775. $('#feedsbox').css("max-height", b - 74);
  776. }
  777. });
  778. _log('-init page view done.');
  779. var dfd = new jQuery.Deferred();
  780. return dfd.resolve(this);
  781. };
  782. /* Loop through dom .matchmain and retrieve infos */
  783. globalClass.prototype.parseMainPage = function (selector, rawData) {
  784. _log('*** parse Main Page ***');
  785. var data = (typeof rawData !== "undefined") ? rawData : 'body';
  786. if (typeof selector !== 'undefined' && selector !== "") {
  787. var matchesCtn = selector;
  788. } // If user has clicked to manually retrieve infos of a specific match
  789. else {
  790. var matchesCtn = $(data).find('.matchmain .match').not('.notavailable').parent();
  791. } //if not, selector is every match available on the page
  792. var csgl = {"data": []}; // global object, containing basically every data for every match.
  793.  
  794. if (matchesCtn.length >= 1) { // iterate through every matchmain box, find data, store it in csgl obj.
  795. $(matchesCtn).each(function (index, value) {
  796.  
  797. var matchUrlDest = $(this).find('a').attr('href');
  798. var matchId = matchUrlDest.replace('match?m=', '').replace("predict?m=", "");
  799. var matchUrl = baseUrl + matchUrlDest;
  800. var matchCtn = $(this).find('a[href="match?m=' + matchId + '"]').closest('.match');
  801. var matchPercA = $(this).find('a[href="match?m=' + matchId + '"] div.teamtext:eq(0) i').text();
  802. var matchPercB = $(this).find('a[href="match?m=' + matchId + '"] div.teamtext:eq(1) i').text();
  803. var matchNameA = $(this).find('a[href="match?m=' + matchId + '"] div.teamtext:eq(0) b').text();
  804. var matchNameB = $(this).find('a[href="match?m=' + matchId + '"] div.teamtext:eq(1) b').text();
  805. matchCtn.append('<div class="matchloading-ctn"><div class="matchloading"></div></div>'); // init loading display
  806.  
  807. var csglMatchData = {
  808. matchUrl: matchUrl,
  809. matchId: matchId,
  810. matchCtn: matchCtn,
  811. teamAperc: matchPercA,
  812. teamBperc: matchPercB,
  813. matchNameA: matchNameA,
  814. matchNameB: matchNameB
  815. };
  816. csgl.data.push(csglMatchData);
  817. }); // matches basic data retrieving has finished.
  818.  
  819. this[this.worker].data = csgl.data; // Obj = this.worker.data[matches]
  820.  
  821. // success
  822. _log('-parseMainPage success', this[this.worker].data);
  823. var dfd = new jQuery.Deferred();
  824. return dfd.resolve(this);
  825. } else {
  826. // escaped
  827. _log('parseMainPage escaped, no matches found'); // No matches has been found, append a message and retrieve the feed
  828. // updateLoading('', '1'); // Set progress bar to 100%
  829. $('#mainheader').append('<div class="nomatchesfound"><br />There are currently no matches to bet on ! ;( <br /> Try checking later...</div>');
  830. }
  831.  
  832. };
  833. // gather and append global infos
  834. globalClass.prototype.globalInfos = function () {
  835. _log('*** global infos ***');
  836. var numberOfMatchesS = $('body').find('.matchmain .match').not('.notavailable').parent().length; // ??!
  837.  
  838. var dfd = new jQuery.Deferred();
  839. return dfd.resolve(this);
  840. };
  841. globalClass.prototype.initLoading = function () { // init loading
  842. _log('... Init Loading ...');
  843. var data = this[this.worker].data;
  844. if (data === "undefined" || data === 0) {
  845. dataLength = 1;
  846. }
  847.  
  848. if (typeof data === "object") {
  849. var dataLength = (Object.getOwnPropertyNames(data).length) - 1;
  850. } // USEFUL 'TILL I FIX THE WORKER OBJ FORMAT ?
  851. else {
  852. var dataLength = data.length;
  853. }
  854.  
  855. this[this.worker].loadingStatus = {// loading vars
  856. "index": 0,
  857. "totalItemsToLoad": dataLength,
  858. "globalMonitor": {
  859. "error": {"view": 0, "request": 0, "IDs": [], "ctn": []},
  860. "success": {"view": 0, "request": 0, "IDs": [], "ctn": []},
  861. "mustRetry": []
  862. } // index to monitor how many ajax requests succeed
  863. };
  864. // VIEW
  865. if (localStorage.getItem("loungeLiveSettings") !== null) {
  866. settings = JSON.parse(localStorage.getItem("loungeLiveSettings"));
  867. console.log('@CSGLounge Live settings:', localStorage.getItem('loungeLiveSettings'));
  868. }
  869. var hasFeedsbox = ($('main').find('#feedsbox')).length > 0 ? true : false;
  870. if (settings.switches.feeds && !hasFeedsbox) { // append feeds container and init loading gif
  871. $('main').append(this.feedbox);
  872. }
  873. if (!settings.switches.feedsShow) { // hide if hide is checked
  874. $('#feedsbox').hide();
  875. }
  876. if (this.worker === "feeds" && hasFeedsbox) { // append feeds container and init loading gif
  877. $.each(data, function (index, value) {
  878. if (($('main #feedsbox').find('#' + value + 'feed-ctn')).length == 0) {
  879. $('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"><table><tbody></tbody></table></div> </div> </article>');
  880. }
  881. });
  882. $('.feedloading').fadeIn('fast');
  883. } else if (this.worker === "initialization" || this.worker === "basicInit") { // matches count and loading bar
  884. if ($('#matchescount').length === 0) {
  885. $('#mainheader .mh-center ul').append('<li id="matchescount">loading: <span id="current-matchescount">0</span> / <span id="total-matchescount"></span></li>');
  886. $('#mainheader .mh-center ul').append('<li id="mainloadingbar"><div class="progress"><span style="width: 0%;"><span>0%</span></span></div></li>');
  887. }
  888. // matchescount
  889. var numberOfMatchesS = $('body').find('.matchmain .match').not('.notavailable').parent().length;
  890. $('.topcounts').html('<span class="numofm"> ' + numberOfMatchesS + '</span> matches available. <span class="lspacer lspacer-tc"></span> <span class="numofb">0</span> bet(s) placed.'); // dot = &#149;
  891. $('#mainheader #matchescount #total-matchescount').html(numberOfMatchesS);
  892. } else { // any worker VIEW
  893.  
  894. }
  895. // console.log("initloadingEND", this[this.worker].loadingStatus);
  896. var dfd = new jQuery.Deferred();
  897. return dfd.resolve(this);
  898. };
  899. // Ajax requests prototype, do the worker requests, parse the data, return whatever needed
  900. globalClass.prototype.ajaxCalls = function (worker, job, url, id, container, timeout) {
  901. _log('... ajaxCalls ...');
  902. _log("Request sent for worker:", worker, " url: ", url, " id: ", id, " container: ", container);
  903. if (typeof timeout === "undefined") {
  904. timeout = settings.defaultTimeout;
  905. }
  906.  
  907. this.genericCall = function () {
  908. var self = this;
  909. _log('ajax req for: ', worker, ' @: ', url, container);
  910. return $.ajax({
  911. method: 'GET',
  912. url: url,
  913. timeout: timeout,
  914. success: function (data) { // Request complete, parse data
  915. // _log('request complete for: url:', url, ' id: ', id,' container:', container, 'RESULT=', data);
  916. _log("response received for worker:", worker, "url;", url);
  917. },
  918. onabort: function (data) {
  919. _log('onabort error throwed for request=> url:', url, ' id: ', id, ' container:', container, 'RESULT=', data);
  920. },
  921. ontimeout: function (data) {
  922. _log('ontimeout error throwed for request=> url:', url, ' id: ', id, ' container:', container, 'RESULT=', data);
  923. },
  924. onerror: function (data) {
  925. _log('onerror error throwed for request=> url:', url, ' id: ', id, ' container:', container, 'RESULT=', data);
  926. }
  927. });
  928. };
  929. return this.genericCall();
  930. };
  931.  
  932. // Global INIT Parse each match page request
  933. globalClass.prototype.parseMatchPageData = function (worker, job, url, id, container, data) {
  934. console.log('*!* parsing... ', id);
  935. _log('... parseMatchPageData ...');
  936. _log('parsing data for url:', url, ' id: ', id, ' container:', container);
  937. var self = this;
  938. var $d = $(data);
  939. var tar = '.box-shiny-alt:eq(0) .full .half:eq(0)';
  940. var tar = $d.find(tar);
  941. var teamAReward = tar.length > 0 ? tar.html().split("<br>")[1] : '';
  942. var tbr = '.box-shiny-alt:eq(0) .full .half:eq(1)';
  943. var tbr = $d.find(tbr);
  944. var teamBReward = tbr.length > 0 ? tbr.html().split("<br>")[1] : '';
  945. var vba = '.box-shiny-alt:eq(0) .full .half:eq(0)';
  946. var vba = $d.find(vba);
  947. var valueBetA = vba.length > 0 ? vba.html().split("<br>")[2] : '';
  948. var vbb = '.box-shiny-alt:eq(0) .full .half:eq(1)';
  949. var vbb = $d.find(vbb);
  950. var valueBetB = vbb.length > 0 ? vbb.html().split("<br>")[2] : '';
  951. var tl = '.box-shiny-alt:eq(0) .half:eq(0)';
  952. var tl = $d.find(tl);
  953. var timeLeft = tl.length > 0 ? tl.text() : '';
  954. var bo = '.box-shiny-alt:eq(0) .half:eq(1)';
  955. var bo = $d.find(bo);
  956. var bestOf = bo.length > 0 ? bo.text() : '';
  957. var t = '.box-shiny-alt:eq(0) .half:eq(2)';
  958. var t = $d.find(t);
  959. var time = t.length > 0 ? t.text() : '';
  960. var d = 'section.box:eq(0) .box-shiny-alt .half:eq(2)';
  961. var d = $d.find(d);
  962. var date = d.length > 0 ? d.attr("title") : '';
  963. var pin = 'section.box:eq(1) div.box-shiny-alt .full:eq(0)';
  964. var pin = $d.find(pin);
  965. var peopleItemsNum = pin.length > 0 ? pin.text() : '';
  966. // var matchDateFull = convertCsglDate(date, time);
  967. // var matchDateHuman = matchDateFull[1];
  968. // var matchDateRobot = matchDateFull[0];
  969.  
  970. // Optional (itemsPlaced, mainstream) // TODO: (I know it's ugly, just leaving it like this for readability until all these features are implemented)
  971. var mst = '.box-shiny-alt div:eq(4)'; // postponed, rules #x etc...
  972. if ($d.find(mst).length) {
  973. var matchStatus = $d.find(mst).text().trim();
  974. } else {
  975. var matchStatus = "";
  976. }
  977.  
  978. var ip = '.box-shiny-alt .full:eq(2)';
  979. var tb = '.box-shiny-alt a.active';
  980. if ($d.find(ip).length) {
  981. var itemsPlaced = $d.find(ip).html();
  982. var teamBet = $d.find(tb).index();
  983. if (teamBet == '1') {
  984. var teamBet = 'a';
  985. }
  986. if (teamBet == '3') {
  987. var teamBet = 'b';
  988. }
  989. var hasItemsPlaced = true;
  990. } else {
  991. var itemsPlaced = 'No bet placed.';
  992. var hasItemsPlaced = false;
  993. var teamBet = false;
  994. }
  995. var ms = '#stream #mainstream';
  996. if ($d.find(ms).length) {
  997. var mainstream = $d.find(ms).html();
  998. var msstatus = '1';
  999. } else {
  1000. var mainstream = 'No stream available';
  1001. var msstatus = '0';
  1002. }
  1003. //var streamlink = $('#chat_embed').attr("src");
  1004. //console.log(streamlink)
  1005. $(self[self.worker].data).each(function (index, value) {
  1006. if (value.matchId === id) {
  1007. value.teamAReward = teamAReward;
  1008. value.teamBReward = teamBReward;
  1009. value.valueBetA = teamAReward;
  1010. value.valueBetB = teamBReward;
  1011. value.peopleItemsNum = $.trim(peopleItemsNum);
  1012. value.timeLeft = timeLeft;
  1013. value.bestOf = bestOf;
  1014. value.timeRaw = $.trim(time);
  1015. value.dateRaw = date;
  1016. value.matchStatus = matchStatus;
  1017. // value.matchDateRobot = matchDateRobot;
  1018. // value.matchDateHuman = matchDateHuman;
  1019. value.hasItemsPlaced = hasItemsPlaced;
  1020. value.itemsPlaced = itemsPlaced;
  1021. value.teamBet = teamBet;
  1022. value.msstatus = msstatus;
  1023. value.mainstream = mainstream;
  1024. }
  1025.  
  1026. });
  1027. _log(self.worker + ' OBJ: ', self[self.worker]);
  1028. // retrieve the object with data for the current "id"
  1029. var result = $.grep(self[self.worker].data, function (e) {
  1030. return e.matchId == id;
  1031. });
  1032. var data = result[0];
  1033. _log('parseMatchPageData worker', worker, 'done for', url);
  1034. var dfd = new jQuery.Deferred();
  1035. return dfd.resolve(self, data, this);
  1036. // dfd.resolve()
  1037. // return dfd.promise(self, data, this);
  1038. };
  1039. /*
  1040. * appendEachMatch Method
  1041. * @param {type} worker
  1042. * @param {type} job
  1043. * @param {type} url
  1044. * @param {type} id
  1045. * @param {type} container
  1046. * @param {type} data
  1047. * @returns {this, container, id}
  1048. */
  1049. globalClass.prototype.appendEachMatch = function (worker, job, url, id, container, data) {
  1050. _log('*** appendEachMatch ***');
  1051. // console.log("Appending match #",id, 'data:', data, this);
  1052. //
  1053.  
  1054. // SummaryBox (labels eg. "No bet placed" "hltv link" "reddit link" etc..."
  1055. var summDest = container.find('.matchleft');
  1056. var hasMBSumm = container.find('.matchbox-summary').length > 0 ? true : false;
  1057. if (!hasMBSumm) {
  1058. summDest.after('<div class="matchbox-summary"></div>');
  1059. }
  1060. if (typeof (data.teamAperc) !== "undefined" && (data.teamAperc).length > 0) { // TODO: und && length vars checker
  1061. //GATHER INFOS TO APPEND
  1062. // var placedbet = !data.hasItemsPlaced ? data.itemsPlaced : '&nbsp;'; // TODO REM IF UNNEEDED
  1063. // infos Below TeamA vs TeamB
  1064.  
  1065. // LoungeDestroyer timezone conversion. Not really stolen, users asked for compatibility.
  1066. // The purpose is not to have any duplicate features with other plugins/scripts, so this one is temporary 'til there is a better solution with LD devs.
  1067. // if (isChrome) {
  1068. // chrome.storage.local.get(function (data) {
  1069. //// @ localstorage LD vars.
  1070. //// changeTimeToLocal
  1071. //// displayTzAbbr
  1072. //// timezone
  1073. //// americanosTime
  1074. // function convertLoungeTime(loungeTimeString) {
  1075. // if (data.userSettings.changeTimeToLocal != '0') {
  1076. // // I am no timezone expert, but I assume moment.js treats CET/CEST automatically
  1077. // var trimmedTime = loungeTimeString.replace('CET', '').replace('CEST', '').trim();
  1078. //
  1079. // // Intl.DateTimeFormat().resolved.timeZone, might be derpy in other browsers
  1080. //
  1081. // if (moment.tz.zone(timezoneName)) {
  1082. // var format = (data.userSettings.americanosTime == '0' ? 'HH:mm' : 'h:mm A');
  1083. // format = (data.userSettings.displayTzAbbr == '0' ? format : format + ' z');
  1084. // return moment.tz(trimmedTime, 'HH:mm', 'CET').tz(timezoneName).format(format);
  1085. // }
  1086. // }
  1087. //
  1088. // return false;
  1089. // }
  1090. // var d = data.userSettings;
  1091. // var d = JSON.parse(d);
  1092. // console.log('USER TIMEZONE', d.timezone);
  1093. // });
  1094. // }
  1095.  
  1096. var teamAReward = typeof data.teamAReward == "undefined" || data.teamAReward == "undefined" ? "" : data.teamAReward;
  1097. var teamBReward = typeof data.teamBReward == "undefined" || data.teamAReward == "undefined" ? "" : data.teamBReward;
  1098. var teamAReward = data.teamAReward == "" ? "&nbsp;" : data.teamAReward;
  1099. var teamBReward = data.teamBReward == "" ? "&nbsp;" : data.teamBReward;
  1100. console.log('teamAReward', teamAReward);
  1101. console.log('teamAReward', typeof teamAReward);
  1102. var infosbelow = '<div class="infosbelow-lr infosbelow-tb"> <div class="line2a"><span title="csgolounge bet reward value">' + teamAReward + '</span></div> </div> <div class="infosbelow-center">&nbsp;' + data.bestOf + '</div> <div class="infosbelow-lr infosbelow-tb"> <div class="line2b"> <span title="csgolounge bet reward value">' + teamBReward + '</span> </div>';
  1103. // Match box header (eg. time left, date cup etc...)
  1104. var mDataHeaderSpacer = '<span class="lspacer lspacer-mh"></span>';
  1105. var headerDTimeLeft = '<span class="timeleft">' + data.timeLeft + '</span>';
  1106. var headerDMatchStatus = '<span class="matchstatus"></span>';
  1107. var headerDTimeRaw = '<span class="timeRaw">&nbsp;&nbsp;(' + data.timeRaw + ')</span>';
  1108. var headerDDateRaw = settings.isCsgo ? '<span class="dateRaw">' + data.dateRaw + '</span>' + mDataHeaderSpacer : "";
  1109. var headerDPItemNum = '<span class="peopleItemsNum">' + data.peopleItemsNum + '</span>';
  1110. var headerDEvent = '<span class="eventm">CCS</span>';
  1111. container.parent().find('.whenm').remove(); // cleanup csgl whenm div in matchheader
  1112.  
  1113. var notUpToDate = container.find('.suminfo-warning'); // check for not up-to-date sticker warning and remove if it exists
  1114. var retrieveError = container.find('.suminfo-error'); // check for error sticker and remove if it exists
  1115. if (notUpToDate.length > 0) {
  1116. notUpToDate.remove();
  1117. }
  1118. if (retrieveError.length > 0) {
  1119. retrieveError.remove();
  1120. }
  1121. // matchheader (time left, date, additionnal info, cup)
  1122. var $w = $('body').find('a[href="match?m=' + id + '"]').parents().eq(2).find('.matchheader');
  1123. var $w2 = $('body').find('a[href="match?m=' + id + '"]').parents().eq(2).find('.matchheader');
  1124. var $w3 = container.parent().find('.matchheader');
  1125. // APPEND
  1126. // matchheader
  1127. // console.log('** Appending (appendEachMatch): ***', data.matchStatus, worker, job, url, id, container, data, '$w2', $w2, '$w3', $w3, headerDTimeLeft + headerDMatchStatus + headerDTimeRaw + mDataHeaderSpacer + headerDDateRaw + mDataHeaderSpacer + headerDPItemNum);
  1128. $w2.append(headerDTimeLeft + headerDMatchStatus + headerDTimeRaw + mDataHeaderSpacer + headerDDateRaw + headerDPItemNum);
  1129.  
  1130. var msCtn = container.parent().find('.matchstatus');
  1131. var msIICtn = container.parent().find('.important-matchinfo');
  1132. if ((data.timeLeft).indexOf('ago') > -1 && (data.matchStatus == "")) {
  1133. msCtn.html(this.liveNow);
  1134. }
  1135. if (typeof data.matchStatus !== "undefined" && data.matchStatus !== "") {
  1136. var msCtn = container.parent().find('.matchstatus');
  1137. msCtn.html('<span class="important-matchinfo">&nbsp;' + data.matchStatus + '&nbsp;</span>');
  1138. }
  1139. // remove matchstatus container if there is no important info anymore to display
  1140. if (msIICtn.length > 0 && (typeof data.matchStatus == "undefined" || data.matchStatus == "")) {
  1141. msCtn.remove();
  1142. }
  1143. // Teams percentages arrows boxes
  1144. var teamTextA = container.parent().find('.teamtext').eq('0');
  1145. var teamTextB = container.parent().find('.teamtext').eq('1').find('i');
  1146. teamTextA.append('<span class="arrow-teama"></span>');
  1147. teamTextB.before('<span class="arrow-teamb"></span>');
  1148.  
  1149. // Infos below the TeamA vs TeamB part
  1150. data.matchCtn.find('a:first').append(infosbelow);
  1151.  
  1152. var hasDetailsBetBox = (container.find('.details-betplaced')).length > 0 ? true : false;
  1153.  
  1154. if (data.hasItemsPlaced) {
  1155. // details-box - details-betplaced
  1156. if (!hasDetailsBetBox) {
  1157. container.append('<div class="detailsbox details-betplaced"' + initialization.matchBoxStatus + '></div>');
  1158. }
  1159. // Dest container for details
  1160. var detBoxBet = container.find('.details-betplaced');
  1161.  
  1162. globalData.count.betsPlaced++;
  1163. data.matchCtn.find('.matchbox-summary').append('<span class="sumbox suminfo-bet betplaced">A bet has been placed.</span>').delay(50).fadeIn('slow');
  1164. $('.numofb').html(globalData.count.betsPlaced).delay(50).fadeOut().fadeIn('slow');
  1165. // Expand button
  1166. (data.matchCtn).prepend('<div class="expmatchbtn-ctn"><a class="expandmatch-btn-a"><span class="expandmatch-btn">+</span></a></div>');
  1167. detBoxBet.append(data.itemsPlaced);
  1168. } else {
  1169. data.matchCtn.find('.matchbox-summary').append('<span class="sumbox suminfo-bet nobetplaced">No bet placed.</span>').delay(50).fadeIn('slow');
  1170. }
  1171. console.log('MS', data.msstatus, data.mainstream);
  1172. // TODO: ADD STREAMLINK
  1173. // MAINSTREAM
  1174. // if (data.msstatus == '1') {
  1175. // 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>')
  1176. // }
  1177. // $('.sh-stream').click(function(){
  1178. // var $t = $(this).parents().eq(2);
  1179. // alert($t.find('.mainstream'))
  1180. // return false;
  1181. // });
  1182. // loading display
  1183. data.matchCtn.find('.matchloading-ctn').remove();
  1184. console.log('append done for id:', id);
  1185. }
  1186.  
  1187. var dfd = new jQuery.Deferred();
  1188. return dfd.resolve(this, container, id);
  1189. };
  1190. globalClass.prototype.updateLoading = function (loadingStatus) {
  1191. var loadingStatus = this[this.worker].loadingStatus;
  1192. if (this.worker === "feeds") {
  1193. if (loadingStatus.index + 1 === loadingStatus.totalItemsToLoad) { // feeds have finished loading
  1194. $('.feedloading').fadeOut('fast');
  1195. }
  1196. } else if (this.worker === "initialization") { // status bar render for worker initialization
  1197. var status = loadingStatus.index;
  1198. var total = loadingStatus.totalItemsToLoad;
  1199. var newPart = (status / total) * 100;
  1200. var newPartShow = Math.round(newPart);
  1201. $('.progress > span').css('width', newPart + '%');
  1202. $('.progress > span > span').text(newPartShow + '%');
  1203. if (status === total) {
  1204. $('.progress > span').css('width', '100%');
  1205. $('.progress > span > span').text('100%');
  1206. $('#mainloadingbar').fadeOut('slow');
  1207. $('#matchescount').fadeOut('slow');
  1208. }
  1209. $('#mainheader #matchescount #current-matchescount').html(loadingStatus.index); // loading counter "X"/y
  1210. } else { // any worker
  1211. }
  1212. };
  1213. /* *********** Feed Jobs *********** */
  1214.  
  1215. globalClass.prototype.appendEachFeed = function (worker, job, url, id, container, data) {
  1216. _log('*** appendEachFeed ***');
  1217. var self = this;
  1218. // var data = JSON.parse(data.response);
  1219. console.log('FEEDS', id, data);
  1220.  
  1221. var date = data.datas.date;
  1222. var data = data.datas.feedProperties;
  1223. var feedData = '';
  1224. $.each(data, function (index, value) {
  1225. var feedUrl = typeof value.feedUrls !== "undefined" ? value.feedUrls.reddit : value.feedUrl; // value.feedUrls = (reddit links list) csgl, reddit, hltv.
  1226. var feedDate = (value.feedDate).indexOf('Not found') > -1 ? "&nbsp;" : value.feedDate; // don't show "Not Found" text.
  1227. feedData += '<tr><td><a href="' + feedUrl + '" target="_blank" title="' + value.feedCup + '">' + value.feedMatchname + '</a></td><td><a href="' + feedUrl + '" target="_blank" title="' + value.feedCup + '">' + feedDate + '</a></td></tr>';
  1228. container.html(feedData);
  1229. });
  1230.  
  1231. if (id === "hltv" && data.datas !== "0") {
  1232. var currentdate = new Date(parseInt(date));
  1233. var dateTime = "<a href='http://www.hltv.org/' target='_blank'>Last Sync: <br />" + currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/" + currentdate.getFullYear() + "<br /> " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds() + "</a>";
  1234. $('#hltvfeed .feedstitle').html(dateTime);
  1235. }
  1236. else {
  1237.  
  1238. }
  1239. if (id === "reddit" && data.datas !== "0") {
  1240. var currentdate = new Date(parseInt(date));
  1241. var dateTime = "<a href='http://www.reddit.com/r/csgobetting/' target='_blank'>Last Sync: <br />" + currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/" + currentdate.getFullYear() + "<br /> " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds() + "</a>";
  1242. $('#redditfeed .feedstitle').html(dateTime);
  1243. $.each(data, function (index, value) {
  1244. var matchUrl = value.feedUrls.csgl;
  1245. var matchUrlHltv = value.feedUrls.hltv;
  1246. var matchUrlReddit = value.feedUrls.reddit;
  1247. var idExp = /(\d+)(?!.*\d)/;
  1248. if (matchUrl.indexOf('csgolounge.com/match?m=') > -1) {
  1249. var matchId = idExp.exec(matchUrl)[0];
  1250. var container = $('body').find('a[href="match?m=' + matchId + '"]').parents().eq(1);
  1251.  
  1252. var sumBox = container.find('.matchbox-summary');
  1253. var hasExpandBtn = (container.find('.expandmatch-btn')).length > 0 ? true : false;
  1254. var hasDetailsRawBox = (container.find('.details-raw')).length > 0 ? true : false;
  1255.  
  1256. // details-box - details-raw
  1257. if (!hasDetailsRawBox) {
  1258. if (container.find('.expandmatch-btn').text() == "-") {
  1259. var displayStatus = "style='display:block;'";
  1260. }
  1261. else if (container.find('.expandmatch-btn').text() == "+") {
  1262. var displayStatus = "style='display:none;'";
  1263. }
  1264. container.append('<div class="detailsbox details-raw"' + displayStatus + '></div>');
  1265. }
  1266. // stickers
  1267. var redditSticker = sumBox.find('.reddit-link');
  1268. var hltvSticker = sumBox.find('.hltv-link');
  1269. // Dest container for details
  1270. var detBoxRaw = container.find('.details-raw');
  1271.  
  1272. if (matchUrlReddit.length > 0) {
  1273. if (redditSticker.length > 0) {
  1274. redditSticker.remove();
  1275. }
  1276.  
  1277. sumBox.append('<a class="reddit-link" target="_blank" href="' + matchUrlReddit + '" ><span class="sumbox suminfo-info">reddit</span></a>');
  1278. if (!hasExpandBtn) {
  1279. container.prepend('<div class="expmatchbtn-ctn"><a class="expandmatch-btn-a"><span class="expandmatch-btn">+</span></a></div>');
  1280. var hasExpandBtn = true;
  1281. }
  1282. }
  1283. // if (redditSticker.length > 0) {
  1284. // sumBox.append('<a class="reddit-link" target="_blank" href="' + matchUrlReddit + '" ><span class="sumbox suminfo-info">reddit</span></a>');
  1285. // }
  1286. if (matchUrlHltv.length > 0) {
  1287. if (hltvSticker.length > 0) {
  1288. hltvSticker.remove();
  1289. }
  1290. sumBox.append('<a class="hltv-link" target="_blank" href="' + matchUrlHltv + '" ><span class="sumbox suminfo-info">hltv</span></a>');
  1291. if (!hasExpandBtn) {
  1292. container.prepend('<div class="expmatchbtn-ctn"><a class="expandmatch-btn-a"><span class="expandmatch-btn">+</span></a></div>');
  1293. var hasExpandBtn = true;
  1294. }
  1295. }
  1296. // if (hltvSticker.length == 0) {
  1297. // sumBox.append('<a class="hltv-link" target="_blank" href="' + matchUrlHltv + '" ><span class="sumbox suminfo-info">hltv</span></a>');
  1298. // }
  1299.  
  1300.  
  1301. var htm = $.parseHTML(value.rawData.selftextHTML);
  1302. var htm = $.text(htm);
  1303. var paragraphs = $(htm).find('p');
  1304. detBoxRaw.empty();
  1305.  
  1306. $.each(paragraphs, function (i, v) {
  1307. var txt = $(v).text();
  1308. if (txt.indexOf('Match Information') == -1 && txt.indexOf('Date') == -1 && txt.indexOf('Time') == -1 && txt.indexOf('Link') == -1) {
  1309. detBoxRaw.append(v);
  1310. }
  1311. });
  1312. // detBoxRaw.html(rawDetails).show();
  1313.  
  1314.  
  1315.  
  1316.  
  1317. // var mapsCtn = detBox.find('.details-maps');
  1318. // var playersCtn = detBox.find('.details-players');
  1319. //
  1320. // if (value.maps.length > 1) {
  1321. // mapsCtn.append('Map(s): ' + value.maps);
  1322. // mapsCtn.show();
  1323. // }
  1324. //
  1325. // var playersListA = '<span style="font-weight:bold">' + value.teamA + ' : </span>';
  1326. // var playersListB = '<span style="font-weight:bold">' + value.teamB + ' : </span>';
  1327. // if (value.playersList.teamA[0] != "Notfound") {
  1328. // for (var i = 0; i < value.playersList.teamA.length; i++) {
  1329. // playersListA += ' ' + value.playersList.teamA[i] + ' - ';
  1330. // if (i === value.playersList.teamA.length - 1) {
  1331. // playersListA += ' ' + value.playersList.teamA[i] + '.';
  1332. // }
  1333. // }
  1334. // }
  1335. // if (value.playersList.teamB[0] != "Notfound") {
  1336. // for (var i = 0; i < value.playersList.teamB.length; i++) {
  1337. // playersListB += ' ' + value.playersList.teamB[i] + ' - ';
  1338. // if (i === value.playersList.teamB.length - 1) {
  1339. // playersListB += ' ' + value.playersList.teamB[i] + '.';
  1340. // }
  1341. // }
  1342. // }
  1343. // if (value.playersList.teamB[0] != "Notfound" || value.playersList.teamA[0] != "Notfound") {
  1344. // playersCtn.append(playersListA + '<br />' + playersListB);
  1345. // playersCtn.show();
  1346. // }
  1347.  
  1348. // console.log(matchId);
  1349. // console.log('MAPS', value.maps);
  1350. // console.log('teamA', value.playersList.teamA);
  1351. // console.log('teamB', value.playersList.teamB);
  1352. }
  1353. });
  1354.  
  1355. }
  1356.  
  1357. var dfd = new jQuery.Deferred();
  1358. return dfd.resolve(this, this[this.worker].loadingStatus);
  1359. };
  1360. /* *********** Update Page *********** */
  1361.  
  1362. globalClass.prototype.getMainPageDistant = function () {
  1363. _l('*** Initialization of Update Page Data ***');
  1364. // globalData.currentData = globalClass.initialization.data; // store local infos retrieved with initialization worker
  1365. console.log("getMainPageDistant", "this", this, this.worker);
  1366. var dfd = new jQuery.Deferred();
  1367. return dfd.resolve(this);
  1368. };
  1369. globalClass.prototype.compareData = function () {
  1370. /* CurrentData = data on the page before the update
  1371. * NewData = data on the DISTANT page
  1372. * DiffData = currentData (+ add - rem from newData)
  1373. * result of currentData and newData comparison (add&rem) => will use it to compare current props (diffData[]) with new props (newData[])
  1374. */
  1375. _log('*** Compare Page Data ***');
  1376. //COMPARE
  1377. var currentData = globalData.currentData;
  1378. var newData = this[this.worker].data;
  1379. console.log(this.tools(), 'globalData.currentData - compareData START', globalData.currentData);
  1380. console.log(this.tools(), 'newData - compareData START', newData);
  1381. // console.log(JSON.stringify(currentData))
  1382. // console.log(JSON.stringify(newData))
  1383.  
  1384. var globalMonitor = this[this.worker].loadingStatus.globalMonitor;
  1385. if (globalMonitor.error.request > 0) { // if there was at least 1 req error in match pages requests.
  1386. for (var i = 0; i < globalMonitor.error.IDs; i++) {
  1387.  
  1388. }
  1389. }
  1390.  
  1391. /* DEBUG */
  1392. // rem
  1393. // newData.splice(1, 1) // completely removes item 1 of array until next item (1 item for 1 time)
  1394. // add
  1395. // var editThat = [];
  1396. // newData.forEach(function (obj) { // cloning diffData with currentData
  1397. // var clonedObj = {};
  1398. // var clonedObj = jQuery.extend(true, {}, obj);
  1399. // editThat.push(clonedObj);
  1400. // });
  1401. // editThat[1].matchId = "9999";
  1402. // editThat[1].matchUrl = "http://csgolounge.com/match?m=9999";
  1403. // var last = newData.length;
  1404. // newData[last] = editThat[1];
  1405. /* DEBUG */
  1406.  
  1407. var propsToUpdate = []; // we are building this array a bit below, containing all properties to update.
  1408.  
  1409. var diffData = []; // result of currentData and newData comparison (add&rem) => will use it to compare current props (diffData[]) with new props (newData[])
  1410.  
  1411. currentData.forEach(function (obj) { // cloning diffData with currentData
  1412. var clonedObj = {};
  1413. var clonedObj = jQuery.extend(true, {}, obj); // true = deep copy, none or false = shallow copy
  1414. diffData.push(clonedObj);
  1415. });
  1416. // matches to add & to remove.
  1417. function dataDifferenceADD(currentData, newData) {
  1418. var x = {};
  1419. currentData.forEach(function (obj) {
  1420. x[obj.matchId] = obj;
  1421. });
  1422. return newData.filter(function (obj) {
  1423. return !(obj.matchId in x);
  1424. });
  1425. }
  1426. function dataDifferenceREM(currentData, newData) {
  1427. var x = {};
  1428. newData.forEach(function (obj) {
  1429. x[obj.matchId] = obj;
  1430. });
  1431. return currentData.filter(function (obj) {
  1432. return !(obj.matchId in x);
  1433. });
  1434. }
  1435. var toAdd = dataDifferenceADD(currentData, newData);
  1436. console.log('"TOADD:"', toAdd);
  1437. var toRem = dataDifferenceREM(currentData, newData);
  1438. console.log('"TOREMOVE:"', toRem);
  1439. // console.log("toAdd", JSON.stringify(toAdd))
  1440. // console.log("newData", JSON.stringify(newData))
  1441. toAdd.forEach(function (obj) { //add
  1442. diffData.push(obj); // push toAdd to diffData OBJ
  1443. propsToUpdate.push(obj);
  1444. });
  1445. toRem.forEach(function (obj) { //rem
  1446. var index = diffData.map(function (x) {
  1447. return x.matchId;
  1448. }).indexOf(obj.matchId); // grep index of toRem matchId in currentData
  1449. if (index > -1) {
  1450. diffData.splice(index, 1); // remove toRem element(s) in diffData
  1451. }
  1452. });
  1453. this.remAndAdd = {};
  1454. this.remAndAdd.rem = toRem;
  1455. this.remAndAdd.add = toAdd;
  1456. // console.log("diffData", JSON.stringify(diffData))
  1457. // console.log("newData", JSON.stringify(newData))
  1458.  
  1459. /*
  1460. #1 props checks
  1461. - loop through each prop of newData
  1462. => check if current prop is in diffData
  1463. - if yes => compare values => if diff => update dom & obj
  1464. - if no => update dom & obj
  1465. */
  1466.  
  1467. for (var i = 0; i < newData.length; i++) {
  1468. var newValuesObj = newData[i];
  1469. var matchId = newValuesObj.matchId; // GET MATCHID
  1470. var currentValues = $.grep(diffData, function (element, index) { // Grep matchId in diffData
  1471. return element.matchId === matchId;
  1472. });
  1473. console.log('@compareData: --------- Checking matchID: ', matchId, ' ---------');
  1474. if (typeof currentValues !== "undefined" && currentValues.length !== 0) {
  1475. var currentValuesObj = currentValues[0]; // item of diffData array with current/old values (eg. {matchId: 2185, matchCtn: "div"...})
  1476.  
  1477. //console.log('currentValuesObj', currentValuesObj)
  1478.  
  1479. // build a list of properties for each array of values
  1480. var currentArrayOfProps = Object.getOwnPropertyNames(currentValuesObj);
  1481. var newArrayOfProps = Object.getOwnPropertyNames(newValuesObj);
  1482. // console.log('allvars', newValuesObj, matchId, currentValuesObj, currentArrayOfProps, newArrayOfProps)
  1483.  
  1484. percStatus = {}; // percentage status: up, down, equal, err status
  1485. for (var j = 0; j < newArrayOfProps.length; j++) { // iterate over the props array from newData
  1486.  
  1487. /* Results */
  1488. // newValuesObj = obj from newData (eg. Object { matchUrl="http://csgolounge.com/match?m=3022", matchId="3022", matchCtn={...}, plus...})
  1489. // currentValuesObj = obj from diffData (eg. Object { matchUrl="http://csgolounge.com/match?m=3022", matchId="3022", matchCtn={...}, plus...})
  1490. // propNameToCheck / newArrayOfProps[j] = teamBReward
  1491. // newValuesPropValue / newValuesObj[propNameToCheck] = 5.4 for 1
  1492. /* !Results */
  1493.  
  1494. var propNameToCheck = newArrayOfProps[j];
  1495. var newValuesPropValue = newValuesObj[propNameToCheck];
  1496. var currentValuesPropValue = currentValuesObj[propNameToCheck];
  1497. if (settings.debug.autoUpdate) {
  1498. console.log('propNameToCheck', propNameToCheck);
  1499. console.log('newValuesObj', newValuesObj);
  1500. console.log('currentValuesObj', currentValuesObj);
  1501. console.log('newValuesPropValue', newValuesPropValue);
  1502. console.log('currentValuesPropValue', currentValuesPropValue);
  1503. console.log('newArrayOfProps', newArrayOfProps);
  1504. console.log('currentArrayOfProps', currentArrayOfProps);
  1505. console.log('newValuesPropValue', newValuesPropValue);
  1506. console.log('currentValuesPropValue', currentValuesPropValue);
  1507. }
  1508. if ((currentValuesPropValue !== newValuesPropValue) && typeof newValuesPropValue != "undefined") { // prop is different in newDatas & currentData, newData prop is defined.
  1509. if (settings.debug.autoUpdate) {
  1510. console.log('#' + matchId, 'currentValuesPropValue', currentValuesPropValue, 'newValuesPropValue', newValuesPropValue);
  1511. }
  1512. // we populate an array (propsToUpdate) containing objects with props to update. We set obj at the array id it was in newData.
  1513. // eg. newData[2] = { "matchId": "2789", "prop" : "value" ... } => propToUpdate[2] = { "matchId": "2789", "propXToUpdate" : "valueXToUpdate" ...}
  1514.  
  1515. 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
  1516. percStatus[propNameToCheck] = currentValuesPropValue < newValuesPropValue ? "up" : currentValuesPropValue > newValuesPropValue ? "down" : currentValuesPropValue == newValuesPropValue ? "equal" : "err";
  1517. }
  1518.  
  1519. var elementPos = propsToUpdate.map(function (x) { // Checking if we have already an obj for this matchId in propsToUpdate
  1520. return x.matchId;
  1521. }).indexOf(newValuesObj.matchId); // id in array
  1522.  
  1523. if (elementPos === -1) { // we've no obj, creating it.
  1524. var objToPush = {// basic obj containing matchId.
  1525. "matchId": newValuesObj.matchId
  1526. };
  1527. }
  1528. // setting objToPush properties
  1529. objToPush[propNameToCheck] = newValuesPropValue; // populating current prop in our obj
  1530. if (typeof percStatus[propNameToCheck] !== "undefined" && percStatus[propNameToCheck].length > 0) { // add percStatus if we've it.
  1531. objToPush.percStatus = percStatus;
  1532. }
  1533. // pushing obj or updating propsToUpdate array.
  1534. if (elementPos === -1) {
  1535. propsToUpdate.push(objToPush); // pushing obj containing prop, or prop + matchId.
  1536. } else {
  1537. propsToUpdate[elementPos] = objToPush; // pushing obj containing prop, or prop + matchId.
  1538. }
  1539. }
  1540.  
  1541. } // !for loop (newArrayOfProps, properties list from newData)
  1542. }
  1543. } // !for loop (newData)
  1544.  
  1545. console.log(this.tools(), 'newData - compareData END', newData);
  1546. console.log(this.tools(), 'diffData - compareData END', diffData);
  1547. // console.log(this.tools(), 'propsToUpdate - compareData END', propsToUpdate);
  1548. globalData.currentData = newData; // update globalData Object
  1549. this.propsToUpdate = propsToUpdate; // public prop, will be used by updateData to generate the VIEW
  1550. // console.log(JSON.stringify(propsToUpdate))
  1551.  
  1552. var dfd = new jQuery.Deferred();
  1553. return dfd.resolve(this);
  1554. };
  1555. globalClass.prototype.updateData = function () {
  1556. // _l('*** Update Page Data ***');
  1557. console.log('*** Update Page Data ***', this.propsToUpdate);
  1558. var self = this;
  1559. // UPDATE
  1560. /* 1) grep matchId
  1561. * 2) find container in dom
  1562. * 3) find props containers in matchmain container
  1563. * 4) update containers
  1564. */
  1565. // 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 "}]
  1566. // console.log(propsToUpdate.length)
  1567.  
  1568. // ADD && REM TO DOM
  1569. // REMOVES
  1570. var addedMatchesCtn = []; // container to pass as selector to CompleteInitialization.call(that, worker, selector) for props loading
  1571. var toAdd = this.remAndAdd.add;
  1572. var toRem = this.remAndAdd.rem;
  1573. // TO ADD DEBUG
  1574. // var m = [];
  1575. // $.each($('body').find('.matchmain .match').not('.notavailable').parent(), function (i, v) {
  1576. // m.push(v)
  1577. // });
  1578. // console.log('v', m)
  1579. // var toAdd = [m[1], m[3]]
  1580.  
  1581. // TO REM DEBUG
  1582. // var toRem = [{"matchUrl": "http://csgolounge.com/match?m=3076", "matchId": "3076", "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", "hasItemsPlaced": "0", "itemsPlaced": "No bet placed.", "teamBet": "0", "msstatus": "0", "mainstream": "No stream available"}];
  1583. // var matchCtnx = $('body').find('a[href="match?m=3076"]').closest('.match').parent(); // debug
  1584. // console.log(matchCtnx);
  1585. // console.log(toRem);
  1586. // toRem[0].matchCtn = matchCtnx; // debug
  1587.  
  1588. // Count bet placed
  1589. $.each(globalData.currentData, function (i, v) {
  1590. var subContainer = $('body').find('a[href="match?m=' + v.matchId + '"]').closest('.match');
  1591. if (v.hasItemsPlaced) {
  1592. globalData.count.betsPlaced++;
  1593. $('.numofb').html(globalData.count.betsPlaced).delay(50).fadeOut().fadeIn('slow');
  1594. subContainer.find('.nobetplaced').remove(); // remove sticker
  1595. if (subContainer.find('.betplaced').length <= 0) { // append sticker if it's not present yet.
  1596. subContainer.find('.matchbox-summary').append('<span class="sumbox suminfo-bet betplaced">A bet has been placed.</span>').delay(50).fadeIn('slow');
  1597. }
  1598. if (subContainer.find('.winsorloses').length <= 0) { // append items if it's not present yet.
  1599. if (subContainer.find('.expandmatch-btn').text() == "-") {
  1600. var displayStatus = "style='display:block;'";
  1601. }
  1602. else if (subContainer.find('.expandmatch-btn').text() == "+") {
  1603. var displayStatus = "style='display:none;'";
  1604. }
  1605. subContainer.append('<div class="detailsbox details-betplaced"' + displayStatus + '>' + v.itemsPlaced + '</div>');
  1606. }
  1607. }
  1608. });
  1609. if (toRem.length > 0) {
  1610. $('.numofm').html((globalData.currentData).length).delay(50).fadeOut().fadeIn('slow'); // update matches available count
  1611. }
  1612. if (toAdd.length > 0) {
  1613. // detach all containers
  1614. var matchmainCtn = $('body').find('.matchmain .match').not('.notavailable').parent();
  1615. var detachedMM = [];
  1616. $.each(matchmainCtn, function (i, v) { // detach all matches containers in detachedMM array
  1617. var matchUrlDest = $(v).find('.matchleft a').attr('href');
  1618. if (typeof matchUrlDest == "undefined") { // container is a predict.
  1619. var matchUrlDest = $(v).find('.match a').attr('href');
  1620. }
  1621. var matchId = matchUrlDest.replace('match?m=', '').replace('predict?m=', '');
  1622. //detached.push($(v).detach())
  1623. var detachedMatches = {
  1624. };
  1625. detachedMatches.matchCtn = $(v).detach();
  1626. detachedMatches.matchId = matchId;
  1627. detachedMM.push(detachedMatches);
  1628. });
  1629. console.log('detachedMM', detachedMM);
  1630. // rebuld the page with reattached matches containers and added match containers
  1631. $.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
  1632. // check if v.matchId is in a 'toAdd' match, if yes, grep matchCtn in newData, else attach current matchCtn
  1633. var matchToAdd = $.grep(toAdd, function (element, index) { // check if match is in toAdd
  1634. return element.matchId === v.matchId;
  1635. });
  1636. //var matchToAdd = matchToAdd[0];
  1637.  
  1638. // matchIsNew so toAdd: yes, no.
  1639. var matchIsNew = (matchToAdd.length > 0) ? true : false;
  1640. if (matchIsNew) { // current matchId is also in toAdd.
  1641. console.log('matchIsNew TRUE', matchToAdd[0].matchCtn);
  1642. if (typeof matchToAdd[0].matchCtn !== 'undefined') {
  1643. $(matchToAdd[0].matchCtn).parent().insertBefore('.shownotav').delay(50).fadeOut().fadeIn('slow');
  1644. console.log('added new match:', v.matchCtn, v);
  1645. addedMatchesCtn.push($(matchToAdd[0].matchCtn).parent());
  1646. $('#scriptinfo-box').prepend('<li class="linfo sticker"><span class="timenow">' + self.tools() + '</span>A new match has been added ' + v.matchNameA + ' vs ' + v.matchNameB + ' <span class="matchid">(<a href="' + v.matchUrl + '" target="_blank">#' + v.matchId + '</a>)</span></li>');
  1647. $('.numofm').html((globalData.currentData).length).delay(50).fadeOut().fadeIn('slow');
  1648. }
  1649. }
  1650. if (!matchIsNew) { // matchCtn is in detachedMatches
  1651. var matchToReAppend = $.grep(detachedMM, function (element, index) {
  1652. // console.log('matchIsNOTNew', detachedMM, element, v.matchId);
  1653. //return element.matchId === v.matchId;
  1654. return element.matchId === v.matchId;
  1655. });
  1656. var matchToReAppend = matchToReAppend[0];
  1657. // console.log('matchToReAppend, matchIsNOTNew ', matchToReAppend)
  1658. if (typeof matchToReAppend.matchCtn !== 'undefined') {
  1659. $(matchToReAppend.matchCtn).insertBefore('.shownotav');
  1660. }
  1661. }
  1662. });
  1663. }
  1664. // Properties update
  1665.  
  1666.  
  1667. var propsToUpdate = this.propsToUpdate;
  1668. function getPropValue(obj, prop) {
  1669. var toRet;
  1670. $.each(obj, function (propl, val) {
  1671. if (propl === prop) {
  1672. toRet = val;
  1673. return false;
  1674. }
  1675. });
  1676. return toRet;
  1677. }
  1678. var debugAU = false;
  1679. for (var x = 0; x < propsToUpdate.length; x++) { // loop through propsToUpdate
  1680. var obj = propsToUpdate[x]; // obj in propsToUpdate array
  1681. var matchId = obj.matchId;
  1682.  
  1683. var subContainer = $('body').find('a[href="match?m=' + matchId + '"]').closest('.match'); // .match ctn
  1684. var container = subContainer.parent(); // .matchmain ctn
  1685.  
  1686. if (debugAU) {
  1687. console.log(['AU:'], ' ', '-------- check matchId:', matchId, ' ------');
  1688. console.log(['AU:'], ' ', 'var x in propsToUpdate', 'container', container, 'obj', obj, 'prop', prop, 'dest', destCtn, 'destSel', destCtnSel);
  1689. }
  1690. for (var prop in obj) { // browse each prop of the obj
  1691. if (debugAU) {
  1692. console.log(['AU:'], ' ', '(var prop in obj)', 'prop', prop);
  1693. }
  1694. if (prop !== "matchId" || prop !== "teamBperc" || prop !== "teamAperc" || prop !== "percStatus" || prop !== "matchCtn") {
  1695. var destCtnSel = getPropValue(this.propsContainers, prop); // where to append the prop
  1696. var destCtn = container.find(destCtnSel);
  1697. if (destCtn.length > 0) {
  1698. if (prop === "timeRaw") { // timeRaw formating ( (19:00 CEST) )
  1699. var newValue = '&nbsp;&nbsp;(' + obj[prop] + ')';
  1700. } else {
  1701. var newValue = obj[prop];
  1702. }
  1703. destCtn.html(newValue).delay(100).fadeOut().fadeIn('slow');
  1704. console.log('Updated matchId:', matchId, ' prop:', prop, ' with value:', newValue, 'in container:', destCtn);
  1705. }
  1706. }
  1707.  
  1708. if (prop === "timeLeft") { // Live !, Postponed, Closed etc...
  1709. console.log("PROPTIMELEFT:", prop, obj[prop], this, container, msCtn, this.liveNow, obj[prop].indexOf('ago'));
  1710. if (obj[prop].indexOf('ago') > -1) {
  1711. var msCtn = container.find('.matchstatus');
  1712. msCtn.html(this.liveNow);
  1713. }
  1714. }
  1715.  
  1716. if (prop === "percStatus") { // arrows
  1717. if (typeof obj.percStatus.teamAperc !== "undefined") {
  1718. var destCtn = container.find('.arrow-teama');
  1719. if (typeof destCtn !== "undefined" && destCtn.length > 0) {
  1720. destCtn.html(this.arrow[obj.percStatus.teamAperc]).delay(100).fadeOut().fadeIn('slow');
  1721. }
  1722. }
  1723. if (typeof obj.percStatus.teamBperc !== "undefined") {
  1724. var destCtn = container.find('.arrow-teamb');
  1725. if (typeof destCtn !== "undefined" && destCtn.length > 0) {
  1726. destCtn.html(this.arrow[obj.percStatus.teamBperc]).delay(100).fadeOut().fadeIn('slow');
  1727. }
  1728. }
  1729. }
  1730. if (prop === "teamBperc" || prop === "teamAperc") {
  1731. var destCtnSel = getPropValue(this.propsContainers, prop); // where to append the prop
  1732. var destCtn = container.find(destCtnSel);
  1733. if (destCtn.length > 0) {
  1734. if (debugAU) {
  1735. console.log(['AU:'], ' ', 'prop', prop, 'dest', destCtn, 'destSel', destCtnSel);
  1736. }
  1737. var newValue = obj[prop];
  1738. destCtn.html(newValue).delay(100).fadeOut().fadeIn('slow');
  1739. }
  1740. }
  1741.  
  1742. } // for (var prop in obj)
  1743. } // for (var x in propsToUpdate)
  1744.  
  1745. var dfd = new jQuery.Deferred();
  1746. return dfd.resolve(this, toAdd, toRem);
  1747. };
  1748. globalClass.prototype.autoUpdateTimers = function () {
  1749. var today = new Date();
  1750. var hh = today.getHours();
  1751. var mm = today.getMinutes();
  1752. var ss = today.getSeconds();
  1753. if (ss <= 9)
  1754. ss = "0" + ss;
  1755. if (mm <= 9)
  1756. mm = "0" + mm;
  1757. var timeNow = hh + ':' + mm + ':' + ss;
  1758. $('.au-lasttime').html(timeNow);
  1759. // var mins = settings.updateDelay;
  1760. var secs = settings.updateDelay / 1000;
  1761. var currentSeconds = 0;
  1762. var currentMinutes = 0;
  1763. if (typeof window.autoUpdateTimer != "undefined") {
  1764. clearInterval(window.autoUpdateTimer);
  1765. }
  1766.  
  1767. window.autoUpdateTimer = setInterval(function () {
  1768. auCountDown();
  1769. }, 1000);
  1770. function auCountDown() {
  1771. currentMinutes = Math.floor(secs / 60);
  1772. currentSeconds = secs % 60;
  1773. if (currentSeconds <= 9)
  1774. currentSeconds = "0" + currentSeconds;
  1775. secs--;
  1776. $('.au-timeleft').html(currentMinutes + "m " + currentSeconds + "s");
  1777. if (secs === -1) {
  1778. clearInterval(window.autoUpdateTimer);
  1779. $('.au-timeleft').html('updating...');
  1780. }
  1781. }
  1782.  
  1783.  
  1784. };
  1785. /* *********** join Matches And Feed *********** */
  1786. globalClass.prototype.compareMatchesWithFeed = function () {
  1787. _log('*** Compare Matches With Feeds ***');
  1788. };
  1789. globalClass.prototype.appendFeedToMatches = function () {
  1790. _log('*** Append Feed to Matches ***');
  1791. };
  1792. globalClass.prototype.tools = function () {
  1793. _log('*** tools ***');
  1794. var today = new Date();
  1795. var hh = today.getHours();
  1796. var mm = today.getMinutes();
  1797. var ss = today.getSeconds();
  1798. if (ss <= 9)
  1799. ss = "0" + ss;
  1800. if (mm <= 9)
  1801. mm = "0" + mm;
  1802. var timeNow = hh + ':' + mm + ':' + ss;
  1803. return timeNow;
  1804. };
  1805. globalClass.prototype.toolsx = {
  1806. 'time': function () {
  1807. var today = new Date();
  1808. var hh = today.getHours();
  1809. var mm = today.getMinutes();
  1810. var ss = today.getSeconds();
  1811. if (ss <= 9)
  1812. ss = "0" + ss;
  1813. if (mm <= 9)
  1814. mm = "0" + mm;
  1815. var timeNow = hh + ':' + mm + ':' + ss;
  1816. return timeNow;
  1817. }
  1818. };
  1819. globalClass.prototype.infobox = function (status, message) { // self.infobox('err', 'LOLOLOLO')
  1820. _log('*** infobox ***');
  1821. var defaultContainer = '#scriptinfo-box';
  1822. switch (status) {
  1823. case 'err':
  1824. var errorType = 'lerror';
  1825. break;
  1826. case 'info':
  1827. var errorType = 'linfo';
  1828. break;
  1829. case 'warn':
  1830. var errorType = 'lwarning';
  1831. break;
  1832. }
  1833. var defaultPrepend = $(defaultContainer).prepend('<li class="' + errorType + ' sticker"><span class="timenow">' + this.toolsx.time() + '</span> ' + message + '</li>');
  1834. };
  1835.  
  1836. function CompleteInitialization(worker, selector) {
  1837. // var initGlobal = new globalClass('initialization'); // wrap init + get each match infos + appends
  1838. var selector = (typeof selector === "undefined") ? "" : selector;
  1839. this.job.retrieveMissing = (typeof selector != "undefined" && selector.length > 0) ? true : false;
  1840. console.log('this (CompleteInitialization)', this, worker, selector, this.job.retrieveMissing);
  1841. $.when(this.parseMainPage(selector)).then(function (that) {
  1842. pLog('DONE:', 'parseMainPage', that);
  1843. return that.globalInfos();
  1844. }).then(function (that) {
  1845. pLog('DONE:', 'globalInfos', that);
  1846. return that.initLoading();
  1847. }).then(function (that) { // Get Match Infos LOOP
  1848. var promisesCompleteInit = [];
  1849. var data = that[that.worker].data;
  1850. $.each(data, function (index, matchUrl) {
  1851. var matchUrl = data[index].matchUrl;
  1852. var matchId = data[index].matchId;
  1853. var matchCtn = data[index].matchCtn;
  1854. _log('curr =', matchUrl, that);
  1855. var p = that.ajaxCalls(that.worker, that.job, matchUrl, matchId, matchCtn, settings.defaultTimeout); //
  1856. promisesCompleteInit.push(p);
  1857. p.done(function (data, textStatus, jqXHR) {
  1858. var responseData = jqXHR.responseText;
  1859. that.monitorWorker("success", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1860.  
  1861. // when request is done, process the data.
  1862. $.when(that.parseMatchPageData(that.worker, that.job, matchUrl, matchId, matchCtn, responseData)).then(function (that, data) {
  1863. return that.appendEachMatch(that.worker, that.job, matchUrl, matchId, matchCtn, data);
  1864. }).then(function (that, matchCtn, matchId) {
  1865. pLog('DONE: CompleteInitialization, appendEachMatch', that);
  1866. that.monitorWorker("success", "view", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1867. return that.updateLoading(that[that.worker].loadingStatus); // send each request status individually to updateLoading
  1868. });
  1869. });
  1870. p.fail(function (jqXHR, stringStatus, exceptionObj) { // exceptionObj: "abort", "timeout", "No Transport".
  1871. if (exceptionObj) {
  1872. switch (exceptionObj) {
  1873. case 'abort':
  1874. var errorType = 'abort';
  1875. that.errorHandling("error", "request", matchCtn, matchId, errorType);
  1876. that.monitorWorker("error", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1877. break;
  1878. case 'timeout':
  1879. var errorType = 'timeout';
  1880. that.errorHandling("error", "request", matchCtn, matchId, errorType);
  1881. that.monitorWorker("error", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1882. break;
  1883. case 'No Transport':
  1884. var errorType = 'No Transport';
  1885. that.errorHandling("error", "request", matchCtn, matchId, errorType);
  1886. that.monitorWorker("error", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1887. break;
  1888. }
  1889. } else {
  1890. var errorType = 'error';
  1891. that.errorHandling("error", "request", matchCtn, matchId, errorType);
  1892. that.monitorWorker("error", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1893. }
  1894. pLog('Failed to retrieve a match in CompleteInitialization', errorType, matchUrl);
  1895. });
  1896. }); // each ended.
  1897.  
  1898. $.when.apply($, promisesCompleteInit)
  1899. .always(function () {
  1900. that.done();
  1901. pLog('DONE: CompleteInitialization ajax req and appends have just finished.');
  1902. if (settings.switches.feeds) {
  1903. FeedsInitialization();
  1904. }
  1905. if (settings.switches.autoupdate) {
  1906. console.log('Initializing Update in ' + settings.updateDelay / 1000 / 60 + ' minutes');
  1907. // console.log('GLOBALOBJ',that.initialization.data)
  1908. // console.log('GLOBALOBJ',globalData.currentData )
  1909. that.autoUpdateTimers();
  1910. window.autoUpdate = setInterval(function () {
  1911. console.log('UpdateInitialization');
  1912. that.autoUpdateTimers();
  1913. UpdateInitialization();
  1914. }, settings.updateDelay);
  1915. }
  1916. })
  1917. .done(function () {
  1918. console.log('Fired all methods for worker init without errors.');
  1919. })
  1920. .fail(function () {
  1921. console.log('Fired all methods for worker init WITH ERRORS.');
  1922. });
  1923. });
  1924. }
  1925. /*
  1926. * @CompleteInitialization()
  1927. "parseMainPage",
  1928. "globalInfos",
  1929. "initLoading",
  1930. "getMatchInfos", // WRAPPED THIS DIRECTLY IN CompleteInitialization function.
  1931. "ajaxCalls",
  1932. "parseMatchPageData",
  1933. "appendEachMatch",
  1934. "updateLoading"
  1935. */
  1936.  
  1937. function UpdateInitialization() { // (AU = Auto Update)
  1938. globalData.count.betsPlaced = 0;
  1939. pLog('UpdateInitialization fired !');
  1940. var initUpdate = new globalClass('updatePage'); // init page view only
  1941. $.when(initUpdate.getMainPageDistant())
  1942. .then(function (that) {
  1943. var AUmainpage = initUpdate.ajaxCalls(initUpdate.worker, "updatePage", baseUrl, "", "", settings.defaultTimeout);
  1944. AUmainpage.done(function (data, textStatus, jqXHR) {
  1945. pLog('req ', baseUrl, ' done.');
  1946. $.when(that.parseMainPage("", data))
  1947. .then(function (that) {
  1948. pLog('DONE:', 'globalInfos', that);
  1949. return that.initLoading();
  1950. })
  1951. /* ---------------- */
  1952. .then(function (that, data) { // Get Match Infos LOOP
  1953. _log('parseMainPage DONE', that[that.worker]);
  1954. var promisesUpdateInit = [];
  1955. var promisesUpdateParsing = [];
  1956. var dataG = that[that.worker].data;
  1957. $.each(dataG, function (index, matchUrl) {
  1958. var matchUrl = dataG[index].matchUrl;
  1959. var matchId = dataG[index].matchId;
  1960. var matchCtn = dataG[index].matchCtn;
  1961. //console.log('curr =', matchUrl, that);
  1962. var px = that.ajaxCalls(that.worker, that.job, matchUrl, matchId, matchCtn, settings.defaultTimeout); //
  1963. promisesUpdateInit.push(px);
  1964. px.done(function (data, textStatus, jqXHR) { // ajax request is complete and has success status.
  1965. var responseData = jqXHR.responseText;
  1966. pLog('DONE', that.worker, that.job, matchUrl, matchId, matchCtn);
  1967. that.monitorWorker("success", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  1968. var matchboxSummary = $('body').find('a[href="match?m=' + matchId + '"]').closest('.match').find('.matchbox-summary');
  1969. var ntuSticker = matchboxSummary.find('.notuptodate');
  1970. if (ntuSticker.length > 0) {
  1971. ntuSticker.delay(50).fadeOut().fadeIn('slow').remove();
  1972. } // not up-to-date sticker
  1973. promisesUpdateParsing.push(that.parseMatchPageData(that.worker, that.job, matchUrl, matchId, matchCtn, responseData)); // Parse the data.
  1974. if (promisesUpdateParsing.length === dataG.length) { // wait for all parsing promises returned by parseMatchPageData method.
  1975. $.when.apply($, promisesUpdateParsing).then(
  1976. function (status) {
  1977. $.when(that.compareData())
  1978. .then(function (that) {
  1979. return that.updateData();
  1980. }, function () {
  1981. console.log('E R R O R');
  1982. })
  1983. .then(function (that, toAdd, toRem) { // datas append when a new match has been added.
  1984. if (typeof toAdd != "undefined" && toAdd.length > 0) {
  1985. console.log('UPDATEDATADONE (toAdd):', toAdd);
  1986. for (var i = 0; i < toAdd.length; i++) {
  1987. console.log('"TOADD:" Sending this to "appendEachMatch":', that.worker, that.job, toAdd[i].matchUrl, toAdd[i].matchId, toAdd[i].matchCtn, toAdd[i]);
  1988. that.appendEachMatch(that.worker, that.job, toAdd[i].matchUrl, toAdd[i].matchId, toAdd[i].matchCtn, toAdd[i]);
  1989. }
  1990. }
  1991. // when a match has been removed.
  1992. if (typeof toRem != "undefined" && toRem.length > 0) {
  1993. console.log('UPDATEDATADONE (toRem):', toRem);
  1994. for (var i = 0; i < toRem.length; i++) {
  1995. var matchUrl = toRem[i].matchUrl;
  1996. var matchId = toRem[i].matchId;
  1997. console.log('"TOREMOVE:" main obj:', toRem[i]);
  1998. // find, detach and append match ctn to shna
  1999. var toRemCtn = $('body').find('a[href="match?m=' + matchId + '"]').parents().eq(2);
  2000. var detachedToRemCtn = toRemCtn.detach();
  2001. detachedToRemCtn.appendTo('#sh-na').find('.match').addClass('notavailable');
  2002. console.log('"TOREMOVE:" detached ctn #', matchId, detachedToRemCtn, 'and appended to #sh-na');
  2003. // ajax call the match page to get the match result or status (winner/loser or postponed, closed etc...)
  2004. $.when(that.ajaxCalls(that.worker, that.job, matchUrl, matchId, detachedToRemCtn, settings.defaultTimeout))
  2005. .done(function (data, textStatus, jqXHR) {
  2006. /* TODO: SHOULD NOT STANDS IN PROCESS, SHOULD BE IN A PRIVATE VIEW METHOD + VERY VERBOSE :( */
  2007. console.log('"TOREMOVE:" REMOVEDONE:', textStatus, jqXHR, matchUrl, matchId);
  2008. var data = $(data);
  2009. var resultSel = data.find('.box-shiny-alt:eq(0)');
  2010. var teamARes = resultSel.find('b:eq(0)');
  2011. var teamBRes = resultSel.find('b:eq(1)');
  2012. var teamARes = teamARes.text().trim();
  2013. var teamBRes = teamBRes.text().trim();
  2014. var wonAImg = '<img style="position: relative; left: 40px; top: -12px;" src="http://cdn.csgolounge.com/img/won.png">';
  2015. var wonBImg = '<img style="position: relative; left: 40px; top: -12px;" src="http://cdn.csgolounge.com/img/won.png">';
  2016. var checkStatus = "linfo";
  2017.  
  2018. var taIsWinner = teamARes.indexOf('(win)') > -1 ? true : false;
  2019. var tbIsWinner = teamBRes.indexOf('(win)') > -1 ? true : false;
  2020. if (taIsWinner || tbIsWinner) {
  2021. var matchResult = teamARes + ' vs ' + teamBRes;
  2022. if (taIsWinner) {
  2023. var ta = detachedToRemCtn.find('.teamtext:eq(0)').prev();
  2024. console.log("TOREMOVE:", 'win', detachedToRemCtn, ta);
  2025. ta.html(wonAImg);
  2026. }
  2027. if (tbIsWinner) {
  2028. var tb = detachedToRemCtn.find('.teamtext:eq(1)').prev();
  2029. console.log("TOREMOVE:", 'win', detachedToRemCtn, tb);
  2030. tb.html(wonBImg);
  2031. }
  2032. }
  2033. detachedToRemCtn.find('.matchislive').html(''); // cleanup 'live !' status.
  2034. var msSel = data.find('.box-shiny-alt div:eq(4)');
  2035. var matchStatus = msSel.text().trim();
  2036. if (matchStatus !== "") {
  2037. var matchResult = matchStatus;
  2038. }
  2039. if (typeof matchResult === "undefined") {
  2040. var matchResult = '<a href="' + matchUrl + '" target="_blank">Could not find result for this match, check it by clicking here</a>';
  2041. var checkStatus = "lwarning";
  2042. }
  2043. // apppend match status and prepend info
  2044. $('#scriptinfo-box').prepend('<li class="' + checkStatus + ' sticker"><span class="timenow">' + that.tools() + '</span>A match has been closed: ' + matchResult + ' <span class="matchid">(<a href="' + matchUrl + '" target="_blank">#' + matchId + '</a>)</span></li>');
  2045.  
  2046. })
  2047. .fail(function (jqXHR, stringStatus, exceptionObj) { // exceptionObj: "abort", "timeout", "No Transport".
  2048. console.log('"TOREMOVE:" REMOVEFAIL:', jqXHR, stringStatus, exceptionObj);
  2049. });
  2050. // append status to ctn and info
  2051. }
  2052. }
  2053. }, function () {
  2054. console.log('E R R O R: something went wrong while adding or removing a match.');
  2055. });
  2056. });
  2057. }
  2058. });
  2059. px.fail(function (jqXHR, stringStatus, exceptionObj) { // exceptionObj: "abort", "timeout", "No Transport".
  2060. var dfd = new jQuery.Deferred();
  2061. 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.
  2062.  
  2063. if (exceptionObj) {
  2064. switch (exceptionObj) {
  2065. case 'abort':
  2066. var error = 'abort';
  2067. break;
  2068. case 'timeout':
  2069. var error = 'timeout';
  2070. break;
  2071. case 'No Transport':
  2072. var error = 'No Transport';
  2073. break;
  2074. }
  2075. } else {
  2076. var error = 'error';
  2077. }
  2078. that.monitorWorker("error", "request", matchCtn, matchId); // monitor global responses status to count how many succeed and failed.
  2079. console.log('REQUESTFORAUFAILED:', that.worker, that.job, matchUrl, matchId, matchCtn, jqXHR, stringStatus, exceptionObj);
  2080. 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...';
  2081. // sticker in matchbox summary
  2082. var matchboxSummary = $('body').find('a[href="match?m=' + matchId + '"]').closest('.match').find('.matchbox-summary');
  2083. var hasNTUSticker = matchboxSummary.find('.notuptodate').length > 0 ? true : false;
  2084. var haserrSticker = matchboxSummary.find('.firstretrieveerr').length > 0 ? true : false;
  2085. if (!hasNTUSticker && !haserrSticker) {
  2086. var infoSticker = '<span class="sumbox suminfo-warning notuptodate"> Not up-to-date!</span>';
  2087. matchboxSummary.append(infoSticker).delay(50).fadeOut().fadeIn('slow');
  2088. }
  2089. $('#scriptinfo-box').prepend('<li class="lwarning sticker"><span class="timenow">' + that.tools() + '</span>' + msg + '</li>');
  2090. });
  2091. }); // each ended.
  2092.  
  2093. $.when.apply($, promisesUpdateInit) // All AutoUpdate ajax calls returned their promises.
  2094. .done(function (that) {
  2095. console.log('Fired all methods for worker UPDATEPAGE, all done without errors.');
  2096. $('#force-refresh').removeClass('fr-loading').addClass('fr-notloading');
  2097. if (settings.switches.feeds) {
  2098. FeedsInitialization();
  2099. }
  2100. })
  2101. .fail(function (that) {
  2102. console.log('Fired all methods for worker UPDATEPAGE, all done WITH ERRORS.');
  2103. $('#force-refresh').removeClass('fr-loading').addClass('fr-notloading');
  2104. });
  2105. });
  2106. });
  2107. AUmainpage.fail(function (jqXHR, stringStatus, exceptionObj) { // exceptionObj: "abort", "timeout", "No Transport".
  2108. $('#scriptinfo-box').prepend('<li class="lerror sticker"><span class="timenow">' + that.tools() + '</span> Main page request for auto update failed. Site might be overloaded or your connection dropped ? If many tries fail again, please disable auto update until site trafic downs.');
  2109. console.log('Main page request for auto update failed.');
  2110. });
  2111. });
  2112. }
  2113. /*
  2114. * @UpdateInitialization()
  2115. *
  2116. getMainPageDistant
  2117. ajaxCalls
  2118. parseMainPage
  2119. initLoading
  2120. each dataG
  2121. ajaxCalls
  2122. monitorWorker
  2123. parseMatchPageData
  2124. compareData
  2125. if add => appendEachMatch
  2126. */
  2127.  
  2128.  
  2129. function FeedsInitialization() {
  2130. var initFeeds = new globalClass('feeds'); // Turn on feeds
  2131. $.when(initFeeds.initGlobalProcess()).then(function (that) {
  2132. pLog('DONE:', 'initGlobalProcess', that);
  2133. return that.globalInfos();
  2134. }).then(function (that) {
  2135. pLog('DONE:', 'globalInfos', that);
  2136. return that.initLoading();
  2137. }).then(function (that) {
  2138. pLog('DONE:', 'initLoading', that);
  2139. that[that.worker] = that.feeds;
  2140. // ask ajaxCalls to request each feeds
  2141. $.each(that.feeds.data, function (index, feedName) {
  2142. var url = that.feeds.feedsDatas[feedName].url;
  2143. var feedContainer = $("#" + feedName + "feed .feedslinks-box tbody");
  2144. var job = feedName;
  2145. _log('feedName', that.worker, that.job, url, feedName, feedContainer);
  2146. $.when(that.ajaxCalls(that.worker, that.job, url, feedName, feedContainer, 30000))
  2147. .done(function (data, textStatus, jqXHR) {
  2148. var responseData = jqXHR.responseJSON;
  2149. _log('AJAX CALL DONE', data, textStatus, jqXHR);
  2150. that.monitorWorker("success", "request", feedContainer, feedName);
  2151. // when request is done, process the data.
  2152. $.when(that.appendEachFeed(that.worker, that.job, url, feedName, feedContainer, responseData)).then(function (that, data) {
  2153. that.monitorWorker("success", "view", feedContainer, feedName);
  2154. return that.updateLoading(that.worker, that.job, url, feedName, feedContainer, data);
  2155. });
  2156. })
  2157. .fail(function (jqXHR, stringStatus, exceptionObj) { // exceptionObj: "abort", "timeout", "No Transport".
  2158. if (exceptionObj) {
  2159. switch (exceptionObj) {
  2160. case 'abort':
  2161. var error = 'abort';
  2162. if (feedName === "hltv") {
  2163. $('#hltvfeed .feedslinks-box').append('<li>' + that.errors.feeds.abort + '</li>');
  2164. }
  2165. if (feedName === "reddit") {
  2166. $('#redditfeed .feedslinks-box').append('<li>' + that.errors.feeds.abort + '</li>');
  2167. }
  2168. break;
  2169. case 'timeout':
  2170. if (feedName === "hltv") {
  2171. $('#hltvfeed .feedslinks-box').append('<li>' + that.errors.feeds.timeout + '</li>');
  2172. }
  2173. if (feedName === "reddit") {
  2174. $('#redditfeed .feedslinks-box').append('<li>' + that.errors.feeds.timeout + '</li>');
  2175. }
  2176. var error = 'timeout';
  2177. break;
  2178. case 'No Transport':
  2179. if (feedName === "hltv") {
  2180. $('#hltvfeed .feedslinks-box').append('<li>' + that.errors.feeds.errors + '</li>');
  2181. }
  2182. if (feedName === "reddit") {
  2183. $('#redditfeed .feedslinks-box').append('<li>' + that.errors.feeds.errors + '</li>');
  2184. }
  2185. break;
  2186. }
  2187. } else {
  2188. var error = 'error';
  2189. }
  2190. that.monitorWorker("error", "request", feedContainer, feedName); // monitor global responses status to count how many succeed and failed.
  2191. pLog('Feeds failed to retrieve data', error, feedName, feedContainer);
  2192. });
  2193. });
  2194. }).done(function (that) {
  2195. pLog('DONE:', 'ajaxCalls', that);
  2196. pLog('done all.');
  2197. initFeeds.done();
  2198. });
  2199. }
  2200. /*
  2201. * @Feeds()
  2202. "initGlobalProcess",
  2203. "globalInfos",
  2204. "initLoading",
  2205. "getFeeds",
  2206. "ajaxCalls",
  2207. "appendEachFeed",
  2208. "updateLoading"
  2209. */
  2210.  
  2211. function initialization(initType) {
  2212. // var initGlobal = new globalClass('basicInit'); // init page view only
  2213. var worker = 'initialization'; // default
  2214. switch (initType) {
  2215. case "complete":
  2216. var worker = 'initialization';
  2217. break;
  2218. case "basic":
  2219. var worker = 'basicInit';
  2220. break;
  2221. }
  2222. var initGlobal = new globalClass(worker); // init page view only
  2223. $.when(initGlobal.initGlobalProcess()).then(function (that) {
  2224. pLog('DONE:', 'initGlobalProcess', that);
  2225. return that.initPageView();
  2226. }).then(function (that) {
  2227. pLog('DONE:', 'initPageView', that);
  2228. }).done(function (that) {
  2229. pLog('DONE:', 'BasicInitialization', that);
  2230. if (initType === "basic") { // a basic Init has been requested, finishing.
  2231. return initGlobal.done();
  2232. } else { // a complete init has been requested, continueing.
  2233. CompleteInitialization.call(initGlobal);
  2234. }
  2235. });
  2236. }
  2237. /*
  2238. * @BasicInitialization()
  2239. "initGlobalProcess",
  2240. "initPageView"
  2241. */
  2242. settings.switches.completeinit ? initialization('complete') : initialization('basic');
  2243.  
  2244.  
  2245. /* INSTANCES DECLARATIONS */
  2246. //UpdateInitialization();
  2247.  
  2248. //var initGlobal = new globalClass('basicInit'); // init page view only
  2249. //var initGlobal = new globalClass('UpdatePage'); // wrap init + get each match infos + appends
  2250.  
  2251. //var initGlobal = new globalClass('initialization'); // wrap init + get each match infos + appends
  2252. //initGlobal.initGlobalProcess();
  2253. //var initFeeds = new globalClass('feeds');
  2254. //initFeeds.initGlobalProcess();
  2255. //
  2256. //var initUpdatePage = new globalClass('UpdatePage'); // init updateData worker
  2257. //initUpdatePage.initGlobalProcess();
  2258. //
  2259.  
  2260.  
  2261.