diegokfu / Farming Cards !

// ==UserScript==
// @name        Farming Cards !
// @namespace   Farming Cards !
// @icon        http://steamcommunity.com/favicon.ico
// @updateURL   https://openuserjs.org/src/scripts/diegokfu/Farming_Cards_!.user.js
// @downloadURL https://openuserjs.org/src/scripts/diegokfu/Farming_Cards_!.user.js
// @include     *://steamcommunity.com/market/search?category_753_Game[]=tag_app_*&category_753_cardborder[]=tag_cardborder_0&category_753_item_class[]=tag_item_class_2&appid=753*
// @include     *://store.steampowered.com/app/*
// @include     *://www.tremorgames.com/?action=showitem*
// @include     *://www.tremorgames.com/index.php?action=showitem*
// @version     0.4
// @grant       GM_xmlhttpRequest
// @require     https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js
// @author      Diego Ferreira
// ==/UserScript==

var g_rgWalletInfo = {"wallet_currency":7,"wallet_country":"BR","wallet_fee":1,"wallet_fee_minimum":1,"wallet_fee_percent":"0.05","wallet_publisher_fee_percent_default":"0.10","wallet_fee_base":0,"wallet_balance":4248,"wallet_delayed_balance":0,"wallet_max_balance":190000,"wallet_trade_max_balance":152000,"success":true,"rwgrsn":-2};

function CalculateAmountToSendForDesiredReceivedAmount( receivedAmount, publisherFee )
{
	if ( !g_rgWalletInfo['wallet_fee'] )
	{
		return receivedAmount;
	}

	publisherFee = ( typeof publisherFee == 'undefined' ) ? 0 : publisherFee;

	var nSteamFee = parseInt( Math.floor( Math.max( receivedAmount * parseFloat( g_rgWalletInfo['wallet_fee_percent'] ), g_rgWalletInfo['wallet_fee_minimum'] ) + parseInt( g_rgWalletInfo['wallet_fee_base'] ) ) );
	var nPublisherFee = parseInt( Math.floor( publisherFee > 0 ? Math.max( receivedAmount * publisherFee, 1 ) : 0 ) );
	var nAmountToSend = receivedAmount + nSteamFee + nPublisherFee;

	return {
		steam_fee: nSteamFee,
		publisher_fee: nPublisherFee,
		fees: nSteamFee + nPublisherFee,
		amount: parseInt( nAmountToSend )
	};
}

function CalculateFeeAmount( amount, publisherFee )
{
	if ( !g_rgWalletInfo['wallet_fee'] )
		return 0;

	publisherFee = ( typeof publisherFee == 'undefined' ) ? 0 : publisherFee;

	// Since CalculateFeeAmount has a Math.floor, we could be off a cent or two. Let's check:
	var iterations = 0; // shouldn't be needed, but included to be sure nothing unforseen causes us to get stuck
	var nEstimatedAmountOfWalletFundsReceivedByOtherParty = parseInt( ( amount - parseInt( g_rgWalletInfo['wallet_fee_base'] ) ) / ( parseFloat( g_rgWalletInfo['wallet_fee_percent'] ) + parseFloat( publisherFee ) + 1 ) );

	var bEverUndershot = false;
	var fees = CalculateAmountToSendForDesiredReceivedAmount( nEstimatedAmountOfWalletFundsReceivedByOtherParty, publisherFee );
	while ( fees.amount != amount && iterations < 10 )
	{
		if ( fees.amount > amount )
		{
			if ( bEverUndershot )
			{
				fees = CalculateAmountToSendForDesiredReceivedAmount( nEstimatedAmountOfWalletFundsReceivedByOtherParty - 1, publisherFee );
				fees.steam_fee += ( amount - fees.amount );
				fees.fees += ( amount - fees.amount );
				fees.amount = amount;
				break;
			}
			else
			{
				nEstimatedAmountOfWalletFundsReceivedByOtherParty--;
			}
		}
		else
		{
			bEverUndershot = true;
			nEstimatedAmountOfWalletFundsReceivedByOtherParty++;
		}

		fees = CalculateAmountToSendForDesiredReceivedAmount( nEstimatedAmountOfWalletFundsReceivedByOtherParty, publisherFee );
		iterations++;
	}

	// fees.amount should equal the passed in amount

	return fees;
}

function formatReal(int){
  var tmp = int+'';
  tmp = tmp.replace(/([0-9]{2})$/g, ",$1");
  if( tmp.length > 6 )
    tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");
  return int < 100 ? tmp.indexOf(",") == -1 ? "0,"+tmp : "0"+tmp: tmp;
}

function Intfee(value){
  var fee=CalculateFeeAmount(value, g_rgWalletInfo['wallet_publisher_fee_percent_default']).fees;
  value=parseInt(value.toString().replace(",", "").replace(".", ""));
  value-=parseInt(fee);
  return value;
}

if(window.location.href.indexOf("tremorgames.com/index.php?action=showitem") > -1){
  document.getElementById('pricecoins').innerHTML+=" - $"+formatReal(parseInt((document.getElementById('pricecoins').childNodes[0].innerHTML/900)*100));
}

if(window.location.href.indexOf("tremorgames.com/index.php?action=showitem") > -1 && document.getElementById("productlink").href.indexOf("/app/") > -1){
  
  var appid=document.getElementById("productlink").href.split("app/")[1].split("/")[0];
  
  GM_xmlhttpRequest({
        method: "GET",
        timeout: 10000,
        url: "http://store.steampowered.com/api/appdetails?filters=price_overview&appids="+appid,
        onload: function(r) {
          var data=JSON.parse(r.responseText)[appid].data.price_overview;
          var currency=data.currency;
          var initial=data.initial;
          var final=data.final;
          var discount=data.discount_percent;
          $('#view_item_left').children('img').after('<br><br>Preço Atual: R$'+formatReal(final)+((discount > 0) ? " ("+discount+"% Off)" : "")+'<br>')
          for(x in document.getElementsByTagName("i")){
            if(document.getElementsByTagName("i")[x].innerHTML.toLowerCase().indexOf("item worth") > -1){
              document.getElementsByTagName("i")[x].innerHTML = 'Item Worth : '+formatReal(initial)+' '+currency;
            }
          }
        }  
  });
  
  link="http://steamcommunity.com/market/search?category_753_Game[]=tag_app_"+appid+"&category_753_cardborder[]=tag_cardborder_0&category_753_item_class[]=tag_item_class_2&appid=753&start=0&count=20&currency=7";
  GM_xmlhttpRequest({
        method: 'GET',
        url: "http://steamcommunity.com/market/search/render?category_753_Game[]=tag_app_"+appid+"&category_753_cardborder[]=tag_cardborder_0&category_753_item_class[]=tag_item_class_2&appid=753&start=0&count=50&currency=7",
        onload: function(r) {
          var data=JSON.parse(r.responseText);
          var reiceve=Math.ceil((data.total_count/2));
            
          var xmlString = data.results_html
          , parser = new DOMParser()
          , doc = parser.parseFromString(xmlString, "text/html");
          
          var media=0;
          var total=data.total_count;
          for (var i = 0; i < total; i++) {
            var price=(doc.getElementsByClassName("market_table_value normal_price")[i].childNodes[3].innerHTML.replace("R$ ", ""));
            media+=parseInt(price.replace(",", ""));
          }
          
          var average=parseInt(media/total);
          if(reiceve > 0){
            $('#item_name').after("<a href='"+link+"'>Dropa "+reiceve+" de "+total+" Cartas - Preço Medio: "+formatReal(average)+" - 'Desconto': "+formatReal(Intfee(average*(Math.ceil(total/2))).toString().replace(".",","))+"</a>");
          }
          
        }  
  });
}

if(document.location.href.indexOf("/app/") > -1){
    
    appid=location.href.split("app/")[1].split("/")[0];
    link="http://steamcommunity.com/market/search?category_753_Game[]=tag_app_"+appid+"&category_753_cardborder[]=tag_cardborder_0&category_753_item_class[]=tag_item_class_2&appid=753&start=0&count=20&currency=7";
     GM_xmlhttpRequest({
        method: 'GET',
        url: "http://steamcommunity.com/market/search/render/?category_753_Game[]=tag_app_"+appid+"&category_753_cardborder[]=tag_cardborder_0&category_753_item_class[]=tag_item_class_2&appid=753&start=0&count=20&currency=7",
        onload: function(r) {
          var data=JSON.parse(r.responseText);
          var reiceve=Math.ceil((data.total_count/2));
            
          var xmlString = data.results_html
          , parser = new DOMParser()
          , doc = parser.parseFromString(xmlString, "text/html");
          var media=0;
          var total=data.total_count;
          for (var i = 0; i < total; i++) {
            var price=(doc.getElementsByClassName("market_table_value normal_price")[i].childNodes[3].innerHTML.replace("R$ ", ""));
            media+=parseInt(price.replace(",", ""));
          }
          var average=parseInt(media/total);
          if(reiceve > 0){ 
              document.getElementsByClassName('apphub_AppName')[0].innerHTML=document.getElementsByClassName('apphub_AppName')[0].innerHTML+"<br><a href='"+link+"' style='text-align:center;'>"+reiceve+"-"+total+" Cartas - Preço Medio: "+formatReal(average)+" - 'Desconto': "+formatReal(Intfee(average*(Math.ceil(total/2))).toString().replace(".",","))+"</a>";
          }
          
        }  
  });
    
} else if(document.location.href.indexOf("/market/") > -1){
    
    var media=parseInt('0');
    var total=document.getElementsByClassName("market_table_value normal_price").length;
    for (var i = 0; i < total; i++) {
        var price=(document.getElementsByClassName("market_table_value normal_price")[i].childNodes[3].innerHTML.replace("R$ ", ""));
        media+=parseInt(price.replace(",", ""));
    }
    var average=parseInt(media/total);
    document.getElementsByClassName("market_sortable_column")[3].innerHTML = "<span class='market_listing_header_namespacer'></span>NOME - PREÇO MEDIO: "+formatReal(average)+" | DESCONTO: "+formatReal(average*(Math.ceil(total/2)))+" (TAXA: "+formatReal(Intfee(average*(Math.ceil(total/2))).toString().replace(".",","))+")<span class='market_sort_arrow' style='display:none;'></span>";
}