Advertisement
Guest User

ss

a guest
Sep 18th, 2014
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.01 KB | None | 0 0
  1. // ==UserScript==
  2. // @name LoungeStats
  3. // @namespace LoungeStats
  4. // @author Kinsi http://reddit.com/u/kinsi55
  5. // @include http://csgolounge.com/myprofile
  6. // @include http://dota2lounge.com/myprofile
  7. // @version 0.2.0
  8. // @require http://bibabot.de/stuff/jquery-2.1.1.min.js
  9. // @require http://bibabot.de/stuff/jquery.jqplot.min.js
  10. // @require http://bibabot.de/stuff/jqplot.cursor.min.js
  11. // @require http://bibabot.de/stuff/jqplot.dateAxisRenderer.min.js
  12. // @require http://bibabot.de/stuff/jqplot.highlighter.min.js
  13. // @downloadURL http://bibabot.de/stuff/LoungeStats.user.js
  14. // @updateURL http://bibabot.de/stuff/LoungeStats.user.js
  15. // @grant GM_xmlhttpRequest
  16. // @grant GM_addStyle
  17. // ==/UserScript==
  18.  
  19. // You are not allowed to share modified versions of this script
  20. // You are not allowed to sell the whole, or parts of this script
  21. // Copyright belongs to "Kinsi" (user Kinsi55 on reddit, /id/kinsi on steam)
  22.  
  23. var cleanparse = false;
  24. var inexactAlert = false;
  25. var bets = [];
  26.  
  27. var setting_method = localStorage['LoungeStats_setting_method'];
  28. var setting_currency = localStorage['LoungeStats_setting_currency'];
  29. var setting_bvalue = localStorage['LoungeStats_setting_bvalue'];
  30. var setting_xaxis = localStorage['LoungeStats_setting_xaxis'];
  31. var setting_debug = localStorage['LoungeStats_setting_debug'];
  32. var loading = false;
  33. var user_steam64 = $('#profile .full:last-child input').val().split('=').pop();
  34.  
  35. var currencysymbol = '$';
  36.  
  37. if(setting_currency == '3') {
  38. currencysymbol = '€';
  39. }
  40. else if(setting_currency == '2') {
  41. currencysymbol = '£';
  42. }
  43. else if(setting_currency == '5') {
  44. currencysymbol = 'р';
  45. }
  46.  
  47. //Well, since you cant force the market price (exact algo) this has to do the trick.
  48. var curr_usd_eur = 1.2937;
  49. var curr_usd_gbp = 1.63336;
  50. var curr_usd_rub = 0.027058;
  51. var curr_usd_brd = 0.445971;
  52.  
  53. var app_id = window.location.hostname == 'dota2lounge.com' ? '570' : '730';
  54.  
  55. //http://stackoverflow.com/a/6700/3526458
  56. Object.size = function(obj) {
  57. var size = 0, key;
  58. for (key in obj) {
  59. if (obj.hasOwnProperty(key)) size++;
  60. }
  61. return size;
  62. };
  63.  
  64. function getLoungeBetHistory(callback) {
  65. if(app_id == '730') {
  66. $.ajax({
  67. url: 'ajax/betHistory.php',
  68. type: 'POST',
  69. success: function(data){callback(data)},
  70. error: function(){callback(null)}
  71. });
  72. } else {
  73. $.ajax({
  74. url: 'ajax/betHistory.php',
  75. type: 'POST',
  76. success: function(data){
  77. $.ajax({
  78. url: 'ajax/betHistoryArchives.php',
  79. type: 'POST',
  80. success: function(dataArchived){callback(data.split("</tbody>")[0]+dataArchived.split("<tbody>")[1])},
  81. error: function(){callback(null)}
  82. });
  83. },
  84. error: function(){callback(null)}
  85. });
  86. }
  87. }
  88.  
  89. function parseLoungeBetHistory(html, callback) {
  90. var doommeedd = $.parseHTML(html);
  91. var cacheWeapons = {}; bets = []; var donerequests = 0;
  92.  
  93. var nomatchcache = user_steam64 != localStorage['LoungeStats_cachedid'];
  94.  
  95. // Preparse, get all matches, all overal needed weapons and arrify them
  96. //var arrayitemlength = $(doommeedd).find('tr:nth-child(3n+1)').length-1;
  97.  
  98. $($(doommeedd).find('tr:nth-child(3n+1)').get().reverse()).each(function(i, bet) {
  99. //i=arrayitemlength-i;
  100. var betid = bet.children[2].children[0].href.split('=').pop();
  101.  
  102. if(setting_debug == 1) console.log('Parsing match #' + betid);
  103. if(localStorage['LoungeStats_betcache_'+betid] && !cleanparse && !nomatchcache) {
  104. var parsedStorage = JSON.parse(localStorage['LoungeStats_betcache_'+betid]);
  105. var items = parsedStorage['items']['won'].concat(parsedStorage['items']['bet']);
  106. for(i in items) {
  107. var itemname = items[i];
  108. var localKeyName = getItemKeyName(itemname, parsedStorage['date']);
  109. if(!cacheWeapons[localKeyName] && !localStorage[localKeyName]) {
  110. //Price of an item is needed thats not cached yet, add it to cache que
  111. if(setting_debug == 1) console.log('Added ' + itemname + ' To cache que...');
  112. cacheWeapons[localKeyName] = [itemname, parsedStorage['date']];
  113. }
  114. }
  115. //Match was cached before, no need to do anything.
  116. bets.push(betid);
  117. } else {
  118. //Match wasnt cached, parse & cache...
  119. var date = bet.children[6].textContent;
  120. var matchoutcome = bet.children[1].children[0].classList[0];
  121. var tocache = {'date': date, 'matchoutcome': matchoutcome, 'items': {'bet':[], 'won':[]}};
  122.  
  123. tocache['teams'] = [bet.children[2].children[0].textContent, bet.children[4].children[0].textContent];
  124. //tricky tricky, if the team you bet on is the second option this will take the second item out of the teams array and set the "bet" value to it, otherwise the first.
  125. tocache['winner'] = tocache['teams'][(bet.children[4].style["fontWeight"] == 'font-weight:bold')];
  126. //var betItems = $(bet).find('tr:nth-child('+(i*3+2)+') td:nth-child(2) div.name b'); ||much slower.
  127. var betItems = $(bet).next().find("div.item > div.name > b");
  128.  
  129. //var wonItems = $(doommeedd).find('tr:nth-child('+(i*3+3)+') td:nth-child(2) div.name b'); ||366x slower
  130. var wonItems = $(bet).next().next().find("div.item > div.name > b:first-child");
  131. //Iterate trough all the items and add them to an array
  132. $(betItems).each(function(i, item) {
  133. var itemname = item.textContent.trim();
  134. var localKeyName = getItemKeyName(itemname, date);
  135. tocache['items']['bet'].push(itemname);
  136.  
  137. if(cleanparse || (!cacheWeapons[localKeyName] && !getItemPrice(itemname, date))) {
  138. //Price of an item is needed thats not cached yet, add it to cache que
  139. if(setting_debug == 1) console.log('Added ' + itemname + ' To cache que(B)...');
  140. cacheWeapons[localKeyName] = [itemname, date];
  141. }
  142. });
  143. $(wonItems).each(function(i, item) {
  144. var itemname = item.textContent.trim();
  145. var localKeyName = getItemKeyName(itemname, date);
  146. tocache['items']['won'].push(itemname);
  147.  
  148. if(cleanparse || (!cacheWeapons[localKeyName] && !getItemPrice(itemname, date))) {
  149. //Price of an item is needed thats not cached yet, add it to cache que
  150. if(setting_debug == 1) console.log('Added ' + itemname + ' To cache que(W)...');
  151. cacheWeapons[localKeyName] = [itemname, date];
  152. }
  153. });
  154. console.log("g");
  155. localStorage['LoungeStats_betcache_' + betid] = JSON.stringify(tocache);
  156. bets.push(betid);
  157. }
  158. });
  159.  
  160. //Remember which user the bets were cached for
  161. localStorage['LoungeStats_cachedid'] = user_steam64;
  162.  
  163. if(setting_debug == 1) console.log('cached weaps:'); console.log(cacheWeapons);
  164.  
  165. //iterate trough all the que'd items that the price is needed of, get & cache it.
  166. var cancel = false;
  167. var cwlen = Object.size(cacheWeapons);
  168.  
  169. if(cwlen > 0) {
  170. $('#loungestats_datacontainer').html('<progress id="loungestats_loadprogress" value="0" max="' + cwlen + '"></progress><br/>Loading uncached item prices<label id="loungestats_loadprogresslabel">(0/' + cwlen + ')</label>...');
  171. getAllPrices(cacheWeapons, Object.keys(cacheWeapons), setting_method == 1 ? 420 : 600, 0, function(success) {
  172. if(success) {
  173. $('#loungestats_datacontainer').html('Generating stats... (If you can see this either you are using a calculator or, more likely, something went horribly wrong)');
  174. callback(true);
  175. } else {
  176. $('#loungestats_datacontainer').html('Could not connect to steam communitymarket API, try again later...');
  177. loading = false;
  178. }
  179. }, function(prog) {
  180. $('#loungestats_loadprogress').val(prog);
  181. $('#loungestats_loadprogresslabel').html('(' + prog + '/' + cwlen + ')');
  182. }, setting_method != 0);
  183. }
  184. else {
  185. $('#loungestats_datacontainer').html('Generating stats... (If you can see this either you are using a calculator or, more likely, something went horribly wrong)');
  186. callback(true);
  187. }
  188. }
  189.  
  190. function plot_zomx(plot, minx, maxx) {
  191. plot.replot({ axes: {
  192. xaxis: {
  193. min: minx,
  194. max: maxx
  195. }
  196. }});
  197. }
  198.  
  199. function generateStatsPage() {
  200. var overallValue = 0.0;
  201. var overallWon = 0.0;
  202. var overallLost = 0.0;
  203. var overallWonCount = 0;
  204. var overallLostCount = 0;
  205. var biggestwin = 0.0;
  206. var biggestwinid = 0;
  207. var biggestloss = 0.0;
  208. var biggestlossid = 0;
  209. var winstreakstart = 0; var winstreaktemp = 0; var winstreaklast = 0;
  210. var losestreakstart = 0; var losestreaktemp = 0; var losestreaklast = 0;
  211. var last = null;
  212.  
  213. var chartData = [];
  214. var betData = [];
  215.  
  216. //iterate trough bets array
  217. for(var i in bets) {
  218. var betid = bets[i];
  219. var b = JSON.parse(localStorage['LoungeStats_betcache_' + betid]);
  220.  
  221. var value = 0.0;
  222. var betValue = 0.0;
  223. if(b['matchoutcome'] == 'won' || b['matchoutcome'] == 'lost') {
  224. if(last != b['matchoutcome']) {
  225. winstreaktemp = 0;
  226. losestreaktemp = 0;
  227. last = b['matchoutcome'];
  228. }
  229. if(b['matchoutcome'] == 'won') {
  230. winstreaktemp++;
  231. overallWonCount++;
  232. if(winstreaktemp > winstreaklast) {
  233. winstreakstart = i - (winstreaktemp-1);
  234. winstreaklast = winstreaktemp;
  235. }
  236. } else {
  237. losestreaktemp++;
  238. overallLostCount++;
  239. if(losestreaktemp > losestreaklast) {
  240. losestreakstart = i - (losestreaktemp-1);
  241. losestreaklast = losestreaktemp;
  242. }
  243. }
  244. }
  245.  
  246. if(b['matchoutcome'] == 'won') {
  247. for(var item in b['items']['won']) {
  248. var itemname = b['items']['won'][item];
  249. value += getItemPrice(itemname, b['date']);
  250. }
  251.  
  252. overallWon += value;
  253. overallValue += value;
  254. if(value > biggestwin) {
  255. biggestwin = value;
  256. biggestwinid = betid;
  257. }
  258. }
  259. for(var item in b['items']['bet']) {
  260. var itemname = b['items']['bet'][item];
  261. betValue += getItemPrice(itemname, b['date']);
  262. }
  263. if(b['matchoutcome'] == 'lost') {
  264. value = betValue;
  265. overallLost += value;
  266. overallValue -= value;
  267. if(value > biggestloss) {
  268. biggestloss = value;
  269. biggestlossid = betid;
  270. }
  271. }
  272. if(setting_debug == 1) console.log('node(' + b['date'] + ')->' + overallValue);
  273.  
  274. chartData.push([setting_xaxis == 0 ? b['date'] : i, parseFloat(overallValue.toFixed(2)), betValue, value, b['teams'].join(' vs. ')]);
  275. if(setting_bvalue == 1) {
  276. betData.push([setting_xaxis == 0 ? b['date'] : i, betValue, b['teams'].join(" vs. ")]);
  277. }
  278. }
  279.  
  280. //generate DOM content
  281. $('#loungestats_datacontainer').empty();
  282. $('#loungestats_datacontainer').append('<a id="loungestats_fullscreenbutton" class="button">Toggle Fullscreen</a><div id="pricehistory" style="position: relative; height: 400px; clear: both;" class="jqplot-target"></div>');
  283.  
  284. var xaxis_def = setting_xaxis == 0 ? {renderer:$.jqplot.DateAxisRenderer,tickOptions: {formatString: '%d %b %y'}} : {renderer: $.jqplot.LinearAxisRenderer};
  285.  
  286. var plot = $.jqplot('pricehistory', [chartData, betData], {
  287. title:{text: 'Overall profit over time'},
  288. gridPadding:{left: 55, right: 35, top: 25, bottom: 25},
  289. axesDefaults:{ showTickMarks:false },
  290. axes:{
  291. xaxis: xaxis_def,
  292. yaxis: {
  293. pad: 1,
  294. tickOptions:{formatString: '%0.2f ' + currencysymbol, labelPosition: 'end', tooltipLocation: 'sw'}
  295. }
  296. },
  297. canvasOverlay: {show: true},
  298. grid: {gridLineColor: '#414141', borderColor: '#414141', background: '#373737'},
  299. cursor: {show: true, zoom: true, showTooltip: false},
  300. highlighter: {show: true, tooltipOffset: 20, fadeTooltip: true, yvalues: 4},
  301. series:[{lineWidth:2, markerOptions:{show: false, style:'circle'}, highlighter: {formatString: '<strong>%s</strong><br>Overall Profit: %s<br>Value bet: %s<br>Value won/lost: %s<br>Game: %s'}},
  302. {lineWidth:1, markerOptions:{show: false, style:'circle'}, highlighter: {formatString: '<strong>%s</strong><br>Value bet: %s<br>Game: %s', tooltipLocation: 'sw'}}],
  303. seriesColors: [ "#FF8A00", "#008A00" ]
  304. });
  305.  
  306. $("#pricehistory").dblclick(function() {plot_zomx(plot, null, null)});
  307.  
  308. $('#loungestats_fullscreenbutton').click(function() {toggleFullscreen(plot)});
  309.  
  310. $(window).on('resize', function(event, ui) {plot.replot();});
  311.  
  312. $('#loungestats_datacontainer').append('<hr>Overall value of items won: ' + overallWon.toFixed(2) + ' ' + currencysymbol);
  313. $('#loungestats_datacontainer').append('<br>Overall value of items lost: ' + overallLost.toFixed(2) + ' ' + currencysymbol);
  314. $('#loungestats_datacontainer').append('<br>Overall won bets: ' + overallWonCount + '/' + parseInt(overallWonCount + overallLostCount) + ' (' + parseInt(100/parseInt(overallWonCount + overallLostCount)*parseInt(overallWonCount)) + '%)');
  315. $('#loungestats_datacontainer').append('<br>Net value: ' + overallValue.toFixed(2) + ' ' + currencysymbol);
  316. $('#loungestats_datacontainer').append('<br>Highest win: ' + biggestwin.toFixed(2) + ' ' + currencysymbol + '<a href="/match?m=' + biggestwinid + '"> (Match link)</a>');
  317. $('#loungestats_datacontainer').append('<br>Highest loss: ' + biggestloss.toFixed(2) + ' ' + currencysymbol + '<a href="/match?m=' + biggestlossid + '"> (Match link)</a>');
  318. $('#loungestats_datacontainer').append('<br>Longest losing streak: ' + losestreaklast + '<a id="loungestats_zoonon_lls" href="javascript:void(0)"> (Show on plot)</a>');
  319. $('#loungestats_datacontainer').append('<br>Longest winning streak: ' + winstreaklast + '<a id="loungestats_zoonon_lws" href="javascript:void(0)"> (Show on plot)</a>');
  320.  
  321. $('#loungestats_zoonon_lws').click(function() {
  322. plot_zomx(plot,chartData[winstreakstart][0],chartData[winstreakstart+winstreaklast][0]);
  323. }).removeAttr('id');
  324. $('#loungestats_zoonon_lls').click(function() {
  325. plot_zomx(plot,chartData[losestreakstart][0],chartData[losestreakstart+losestreaklast][0]);
  326. }).removeAttr('id');
  327.  
  328. $('#loungestats_reloadbutton').show();
  329. }
  330.  
  331. var activefast = 0;
  332. var fastindex = 0;
  333.  
  334. function getAllPrices(itemarray, itemarraykeylist, delay, arrayoffset, callback, progresscallback, exact) {
  335. if(!arrayoffset) arrayoffset = 0;
  336. var item = itemarray[itemarraykeylist[arrayoffset]];
  337.  
  338. if(!item) {
  339. if(activefast == 0) callback(true)
  340. return true;
  341. }
  342. if(exact) {
  343. cacheItemExact(item[0], item[1], function(success) {
  344. if(success) {
  345. progresscallback(arrayoffset+1);
  346. //Recursively re-call myself with a delay until all prices are parsed, this is because the amount of requests to the market possible is limited
  347. setTimeout(function(){getAllPrices(itemarray, itemarraykeylist, delay, arrayoffset+1, callback, progresscallback, exact)}, delay);
  348. }
  349. else {
  350. $('#loungestats_datacontainer').html('Could not connect to steam communitymarket API, try again later...');
  351. callback(false);
  352. }
  353. });
  354. } else {
  355. while(activefast < 10) {
  356. activefast++;
  357. if(arrayoffset == 0) fastindex = 0;
  358. fastindex++;
  359. cacheItem(item[0], function(success) {
  360. if(success) {
  361. activefast--;
  362. progresscallback(fastindex-activefast);
  363. getAllPrices(itemarray, itemarraykeylist, delay, fastindex, callback, progresscallback, exact);
  364. if(setting_debug == 1) console.log(donerequests);
  365. }
  366. else {
  367. fastindex = itemarraykeylist.length +1;
  368. $('#loungestats_datacontainer').html('Could not connect to steam communitymarket API, try again later...');
  369. callback(false);
  370. }
  371. }, item[1]);
  372. }
  373. }
  374. }
  375.  
  376. function cacheItem(itemname, callback, exactfallback) {
  377. if(setting_debug == 1) console.log('Caching item price of ' + itemname + '...');
  378. var localKeyName = getItemKeyName(itemname, exactfallback);
  379.  
  380. GM_xmlhttpRequest({
  381. method: 'GET',
  382. url: 'http://steamcommunity.com/market/priceoverview/?currency=' + localStorage['LoungeStats_setting_currency'] + '&appid=' + app_id + '&market_hash_name=' + encodeURI(itemname),
  383. onload: function(response) {
  384. if(response.status == 200) {
  385. var responseParsed = JSON.parse(response.responseText);
  386. if(responseParsed.success == true && responseParsed.hasOwnProperty('median_price')) {
  387. var price = responseParsed['median_price'].replace('&#36;','').replace('&#163;','').replace('&#8364;','').replace('p&#1091;&#1073;.','').replace(',', '.').trim();
  388. if(setting_debug == 1) console.log('Cached item price of ' + itemname + ' | Price: ' + price);
  389. localStorage.setItem(localKeyName, price);
  390. callback(true);
  391. return;
  392. }// No median price seems existant, attempt to use the lowest price
  393. else if(responseParsed.success == true && responseParsed.hasOwnProperty('lowest_price')) {
  394. var price = parseFloat(responseParsed['lowest_price'].replace('&#36;','').replace('&#163;','').replace('&#8364;','').replace('p&#1091;&#1073;.','').replace(',', '.').trim());
  395. if(responseParsed['lowest_price'].indexOf('&#36;') > -1){
  396. //hi
  397. }
  398. else if(responseParsed['lowest_price'].indexOf('&#163;') > -1){
  399. price *= curr_usd_gbp;
  400. }
  401. else if(responseParsed['lowest_price'].indexOf('&#8364;') > -1){
  402. price *= curr_usd_eur;
  403. } else if(responseParsed['lowest_price'].indexOf('p&#1091;&#1073;') > -1){
  404. price *= curr_usd_rub;
  405. } else if(responseParsed['lowest_price'].indexOf('&#82;&#36;') > -1){
  406. price *= curr_usd_brd;
  407. }
  408.  
  409. if(setting_debug == 1) console.log('Cached item price of ' + itemname + ' | Price: ' + price);
  410. localStorage.setItem(localKeyName, price);
  411. callback(true);
  412. return;
  413. }// No lowest price seems existant, assume price as 0 since i cant do anything else really
  414. else if(setting_debug == 1) {
  415. console.log('Failed to load ' + itemname + ', assuming as 0');
  416. }
  417. }
  418. localStorage.setItem(localKeyName, 0.0);
  419. callback(true);
  420. }
  421. });
  422. }
  423.  
  424. //Converting usd to other currencies using static conversion rates (Thanks GabeN)
  425. function convertUsd(usd)
  426. {
  427. if(setting_currency == '3') {
  428. return usd / curr_usd_eur;
  429. }
  430. else if(setting_currency == '2') {
  431. return usd / curr_usd_gbp;
  432. }
  433. else if(setting_currency == '5') {
  434. return usd / curr_usd_rub;
  435. }
  436. else if(setting_currency == '7') {
  437. return usd / curr_usd_brd;
  438. }
  439. return usd;
  440. }
  441.  
  442. function cacheItemExact(itemname, loungetime, callback) {
  443. if(setting_debug == 1) console.log('Caching exact item price of ' + itemname + '...');
  444. var betdate = new Date(Date.parse(loungetime.replace(/-/g,' ') + ' +0'));
  445. var localKeyName = getItemKeyName(itemname, loungetime);
  446. GM_xmlhttpRequest({
  447. method: 'GET',
  448. //tricky stuff, since i cant get the price history when im not logged in, im downloading the items market page. Even if there are not items on sale at that very moment
  449. //in the javascript there still is an array with the past price history
  450. url: 'http://steamcommunity.com/market/listings/' + app_id + '/' + encodeURI(itemname) + '?l=english',
  451. onload: function(response) {
  452. if(response.status == 200) {
  453. //which i do filter out with this regex pattern
  454. var rgx = /var line1=\[\[(.*)\]\]/.exec(response.responseText);
  455. var curr = /var strFormatPrefix[^]*?var strFormatSuffix[^]*?;/.exec(response.responseText);
  456. var inexact = false;
  457.  
  458. if(rgx) {
  459. var arr = JSON.parse('[[' + rgx[1] + ']]');
  460.  
  461. if(arr != null) {
  462. var prev = null;
  463. //and iterate trough it here if it was found
  464. var p = 0.0;
  465. for(var i in arr) {
  466. var datadate = new Date(Date.parse(arr[i][0]));
  467. p = parseFloat(arr[i][1]);
  468.  
  469. if(curr[0].indexOf('&#36;') > -1) {
  470. //hi
  471. }
  472. else if(curr[0].indexOf('&#163;') > -1) {
  473. p *= curr_usd_gbp;
  474. }
  475. else if(curr[0].indexOf('&#8364;') > -1) {
  476. p *= curr_usd_eur;
  477. } else if(curr[0].indexOf('p&#1091;&#1073;') > -1){
  478. p *= curr_usd_rub;
  479. } else if(curr[0].indexOf('&#82;&#36;') > -1){
  480. p *= curr_usd_brd;
  481. } else { inexact = true }
  482.  
  483.  
  484. if(datadate >= betdate && (prev == null || prev < betdate)) {
  485. if(inexact && !inexactAlert) {
  486. inexactAlert = true;
  487. alert("For your Information. Since you are using the exact method you want exact prices. Because of this, i am alerting you that i cant provide exact prices for you sadly, the reason being that i dont know how to deal with your local currency. The best you can do is to select US$ as your currency, this will display values in your local currency. The alternative is to use the fast method because i can tell steam which currency i want the prices in for that, which i cant for the price history sadly. I'm sorry for that");
  488. }
  489. if(setting_debug == 1) console.log('Parsed: ' + datadate + ' Requested: ' + loungetime)
  490. localStorage[localKeyName] = p;
  491. callback(true);
  492. return;
  493. }
  494. prev = datadate;
  495. }
  496. if(setting_debug == 1) console.log('Parsed: ' + datadate + ' Requested: ' + loungetime)
  497. localStorage[localKeyName] = parseFloat(arr[i][1]);
  498. callback(true);
  499. return;
  500. }
  501. }
  502. }
  503. //otherwise attempt to use the inexact price instead of the exact price since i cant do anything else really
  504. if((response.responseText.indexOf('There is no price history available for this item yet.') > -1) || response.responseText.indexOf('There are no listings for this item.') > -1) {
  505. if(setting_debug == 1) console.log('Falling back to unexact price...');
  506. cacheItem(itemname, callback, loungetime);
  507. return;
  508. }
  509. callback(false);
  510. }
  511. });
  512. }
  513. //Internal function for generating central localstorage key names
  514. function getItemKeyName(itemname, loungetime)
  515. {
  516. if(loungetime && setting_method != 0) {
  517. var betdate = new Date(Date.parse(loungetime.replace(/-/g,' ') + ' +0'));
  518. return 'LoungeStats_itemexact_' + betdate.getUTCDate() + '_' + betdate.getUTCMonth() + '_' + betdate.getYear() + '_' + itemname.replace(/ /g, '_');
  519. } else {
  520. return 'LoungeStats_' + currencysymbol + 'item_' + itemname.replace(/ /g, '_');
  521. }
  522. }
  523.  
  524. function getItemPrice(itemname, loungetime)
  525. {
  526. var localKeyName = getItemKeyName(itemname, loungetime);
  527. if(localStorage[localKeyName]){
  528. if(loungetime && setting_method != 0) {
  529. return convertUsd(parseFloat(localStorage[localKeyName]));
  530. }
  531. return parseFloat(localStorage[localKeyName]);
  532. }
  533. return false;
  534. }
  535. //Main sub that handles most of the stuff
  536. function loadStats(clean) {
  537. if(loading){
  538. alert('I\'m already loading, sheesh.')
  539. return;
  540. }
  541.  
  542. if(typeof(Storage) == void(0)) {
  543. $('#ajaxCont').html('Your browser does not seem to support localstorage, update it and try again.');
  544. return;
  545. }
  546. else if(!setting_method) {
  547. $('#ajaxCont').html('Please set up Loungestats first');
  548. $('#loungestats_overlay').fadeIn(500);
  549. return;
  550. }
  551. cleanparse = clean;
  552. $('#ajaxCont').html('<a id="loungestats_settingsbutton" class="button">LoungeStats Settings</a><a id="loungestats_reloadbutton" class="button" style="display: none;">Refresh cache</a><a class="button" target="_blank" href="http://steamcommunity.com/tradeoffer/new/?partner=33309635&token=H0lCbkY3">Donate to Loungestats ♥</a><a class="button" target="_blank" href="http://reddit.com/r/LoungeStats">Report a bug</a><br><hr><br><div id="loungestats_datacontainer"><img src="../img/load.gif" id="loading" style="margin: 0.75em 2%"></div>');
  553. $('#loungestats_reloadbutton').click(function() {loadStats(true)});
  554. $('#loungestats_settingsbutton').click(function() {$('#loungestats_overlay').fadeIn(500)}).removeAttr('id');
  555. loading = true;
  556. getLoungeBetHistory(function(data) {
  557. if(data != null) {
  558. parseLoungeBetHistory(data, function(success) {
  559. if(success) {
  560. generateStatsPage();
  561. }
  562. loading = false;
  563. });
  564. } else {
  565. loading = false;
  566. $('#loungestats_datacontainer').html('Looks like Lounge is dead at the moment..');
  567. }
  568. });
  569. }
  570.  
  571. function toggleFullscreen(jqplot)
  572. {
  573. if($("#pricehistory").hasClass('fullsc')) {
  574. $('#pricehistory').removeClass('fullsc');
  575. $('#loungestats_fullscreenbutton').removeClass('fullsc');
  576. } else {
  577. $('#pricehistory').addClass('fullsc');
  578. $('#loungestats_fullscreenbutton').addClass('fullsc');
  579. }
  580. jqplot.replot();
  581. }
  582.  
  583. //called when save is pressed in the settings
  584. function saveSettings()
  585. {
  586. localStorage['LoungeStats_setting_method'] = $('#loungestats_method').val(); setting_method = localStorage['LoungeStats_setting_method'];
  587. localStorage['LoungeStats_setting_currency'] = $('#loungestats_currency').val(); setting_currency = localStorage['LoungeStats_setting_currency'];
  588. localStorage['LoungeStats_setting_bvalue'] = $('#loungestats_bgraph').val(); setting_bvalue = localStorage['LoungeStats_setting_bvalue'];
  589. localStorage['LoungeStats_setting_xaxis'] = $('#loungestats_xaxis').val(); setting_xaxis = localStorage['LoungeStats_setting_xaxis'];
  590. localStorage['LoungeStats_setting_debug'] = $('#loungestats_debug').val(); setting_debug = localStorage['LoungeStats_setting_debug'];
  591.  
  592. if(setting_currency == '3') {
  593. currencysymbol = '€';
  594. }
  595. else if(setting_currency == '2') {
  596. currencysymbol = '£';
  597. }
  598. else if(setting_currency == '5') {
  599. currencysymbol = 'р';
  600. }
  601. else if(setting_currency == '1') {
  602. currencysymbol = '$';
  603. }
  604. else {
  605. currencysymbol = 'R$';
  606. }
  607. $('#loungestats_overlay').fadeOut(500);
  608. loadStats();
  609. }
  610.  
  611. //I know that gm scripts are called on the documentReady, i like having it like this nevertheless.
  612. function init() {
  613. $('#main section:nth-child(2) div:nth-child(1)').append('<a id="loungestats_tabbutton" class="button">Stats</a>');
  614. GM_addStyle(".jqplot-highlighter-tooltip {background-color: #393938; border: 1px solid gray; padding: 5px; color: #ccc} \
  615. .jqplot-xaxis {margin-top: 5px; font-size: 12px} \
  616. .jqplot-yaxis {margin-right: 5px; width: 55px; font-size: 12px} \
  617. .jqplot-yaxis-tick {text-align: right; width: 100%} \
  618. #loungestats_overlay {z-index: 9000; display: none; top: 0px; left: 0px; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.4); position: fixed} \
  619. #loungestats_settings_title {text-align: center; font-size: 12px; height: 40px; border: 2px solid #DDD; border-top: none; background-color: #EEE; width: 100%; margin-top: -10px; -webkit-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; padding: 10px 5px 0 5px; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;} \
  620. #loungestats_settingswindow {font-size: 13px; z-index: 9001; padding: 10px; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; position: relative; background-color: white; left: 50%; top: 50%; width: 300px; margin-left: -151px; height: 400px; margin-top: -201px; -webkit-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 0 10px -5px #000; box-shadow: 0 0 10px -5px #000; border: 1px solid gray} \
  621. #loungestats_settingswindow select{margin: 5px 0; width: 100%; height: 22px !important} \
  622. #loungestats_fullscreenbutton{position: absolute; right: 29px; top: -5px; z-index: 9001; height: 14px;z-index: 8998} \
  623. #loungestats_fullscreenbutton.fullsc{position: fixed;margin: 0;right: 34px} \
  624. #pricehistory.fullsc{background-color: #ddd;height: 100% !important;left: 0;margin: 0;position: fixed !important;top: 0;width: 100%;} \
  625. #loungestats_datacontainer{position: relative} \
  626. .jqplot-highlighter-tooltip{z-index: 8999;}");
  627.  
  628. $('body').append('<div id="loungestats_overlay"> \
  629. <div id="loungestats_settingswindow"> \
  630. <div id="loungestats_settings_title">Loungestats 0.2.0B Settings | by <a href="http://reddit.com/u/kinsi55">/u/kinsi55</a><br><br></div> \
  631. Pricing accuracy <a class="info">?<p class="infobox"><br>Fastest: Use current item prices for all bets<br><br>Most accurate: Use item prices at approximately the time of the bet, as little delay as possible between requests<br><br>Most accurate & safest: Same as Most accurate, but with a bit more delay between requests</p></a>:<br> \
  632. <select id="loungestats_method"> \
  633. <option value="0">Fastest</option> \
  634. <option value="1">Most accurate</option> \
  635. <option value="2">Most accurate & safest</option> \
  636. </select><br><br> \
  637. Currency:<br> \
  638. <select id="loungestats_currency"> \
  639. <option value="1">US Dollar(Most exact)</option> \
  640. <option value="3">Euro</option> \
  641. <option value="2">Great British Pound</option> \
  642. <option value="5">Rubel</option> \
  643. <option value="7">Brazilian real</option> \
  644. </select><br><br> \
  645. Show bet value graph:<br> \
  646. <select id="loungestats_bgraph"> \
  647. <option value="1">Yes</option> \
  648. <option value="0">No</option> \
  649. </select><br><br> \
  650. X-Axis:<br> \
  651. <select id="loungestats_xaxis"> \
  652. <option value="0">Date</option> \
  653. <option value="1">Incrementing</option> \
  654. </select><br><br> \
  655. Debug mode:<br> \
  656. <select id="loungestats_debug"> \
  657. <option value="0">Off</option> \
  658. <option value="1">On</option> \
  659. </select><br><br> \
  660. <div style="position: absolute; bottom: 10px;"> \
  661. <a id="loungestats_settings_save" class="button">Save</a> \
  662. <a id="loungestats_settings_close" class="button">Close</a> \
  663. </div> \
  664. </div> \
  665. </div>');
  666. if(setting_method) {
  667. $('#loungestats_method').val(setting_method);
  668. $('#loungestats_currency').val(setting_currency);
  669. $('#loungestats_bgraph').val(setting_bvalue);
  670. $('#loungestats_xaxis').val(setting_xaxis);
  671. $('#loungestats_debug').val(setting_debug);
  672. }
  673. $('#loungestats_tabbutton').click(function() {loadStats(false);}).removeAttr('id');
  674. $('#loungestats_overlay, #loungestats_settings_close').click(function() {$('#loungestats_overlay').fadeOut(500);});
  675. $('#loungestats_settings_save').click(function() {saveSettings()});
  676. $('#loungestats_settingswindow').click(function(e) {return false;});
  677. }
  678.  
  679. init();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement