egortsygvintsevgmail.com / l2cCraftCost

// ==UserScript==
// @name l2cCraftCost
// @author Zeptor
// @version 1.2
// @include http://l2central.info/classic/*
	var w;
    if (typeof unsafeWindow != undefined) {
        w = unsafeWindow
    } else {
        w = window;
    }
	
	// include tabletop.1.3.5.min.js
	(function(e){"use strict";var t=false;if(typeof module!=="undefined"&&module.exports){t=true;var n=require("request")}var r=false;var i=false;try{var s=new XMLHttpRequest;if(typeof s.withCredentials!=="undefined"){r=true}else{if("XDomainRequest"in window){r=true;i=true}}}catch(o){}var u=Array.prototype.indexOf;var a=function(e,t){var n=0,r=e.length;if(u&&e.indexOf===u)return e.indexOf(t);for(;n<r;n++)if(e[n]===t)return n;return-1};var f=function(e){if(!this||!(this instanceof f)){return new f(e)}if(typeof e==="string"){e={key:e}}this.callback=e.callback;this.wanted=e.wanted||[];this.key=e.key;this.simpleSheet=!!e.simpleSheet;this.parseNumbers=!!e.parseNumbers;this.wait=!!e.wait;this.reverse=!!e.reverse;this.postProcess=e.postProcess;this.debug=!!e.debug;this.query=e.query||"";this.orderby=e.orderby;this.endpoint=e.endpoint||"https://spreadsheets.google.com";this.singleton=!!e.singleton;this.simple_url=!!e.simple_url;this.callbackContext=e.callbackContext;if(typeof e.proxy!=="undefined"){this.endpoint=e.proxy.replace(/\/$/,"");this.simple_url=true;this.singleton=true;r=false}this.parameterize=e.parameterize||false;if(this.singleton){if(typeof f.singleton!=="undefined"){this.log("WARNING! Tabletop singleton already defined")}f.singleton=this}if(/key=/.test(this.key)){this.log("You passed an old Google Docs url as the key! Attempting to parse.");this.key=this.key.match("key=(.*?)&")[1]}if(/pubhtml/.test(this.key)){this.log("You passed a new Google Spreadsheets url as the key! Attempting to parse.");this.key=this.key.match("d\\/(.*?)\\/pubhtml")[1]}if(!this.key){this.log("You need to pass Tabletop a key!");return}this.log("Initializing with key "+this.key);this.models={};this.model_names=[];this.base_json_path="/feeds/worksheets/"+this.key+"/public/basic?alt=";if(t||r){this.base_json_path+="json"}else{this.base_json_path+="json-in-script"}if(!this.wait){this.fetch()}};f.callbacks={};f.init=function(e){return new f(e)};f.sheets=function(){this.log("Times have changed! You'll want to use var tabletop = Tabletop.init(...); tabletop.sheets(...); instead of Tabletop.sheets(...)")};f.prototype={fetch:function(e){if(typeof e!=="undefined"){this.callback=e}this.requestData(this.base_json_path,this.loadSheets)},requestData:function(e,n){if(t){this.serverSideFetch(e,n)}else{var s=this.endpoint.split("//").shift()||"http";if(r&&(!i||s===location.protocol)){this.xhrFetch(e,n)}else{this.injectScript(e,n)}}},xhrFetch:function(e,t){var n=i?new XDomainRequest:new XMLHttpRequest;n.open("GET",this.endpoint+e);var r=this;n.onload=function(){try{var e=JSON.parse(n.responseText)}catch(i){console.error(i)}t.call(r,e)};n.send()},injectScript:function(e,t){var n=document.createElement("script");var r;if(this.singleton){if(t===this.loadSheets){r="Tabletop.singleton.loadSheets"}else if(t===this.loadSheet){r="Tabletop.singleton.loadSheet"}}else{var i=this;r="tt"+ +(new Date)+Math.floor(Math.random()*1e5);f.callbacks[r]=function(){var e=Array.prototype.slice.call(arguments,0);t.apply(i,e);n.parentNode.removeChild(n);delete f.callbacks[r]};r="Tabletop.callbacks."+r}var s=e+"&callback="+r;if(this.simple_url){if(e.indexOf("/list/")!==-1){n.src=this.endpoint+"/"+this.key+"-"+e.split("/")[4]}else{n.src=this.endpoint+"/"+this.key}}else{n.src=this.endpoint+s}if(this.parameterize){n.src=this.parameterize+encodeURIComponent(n.src)}document.getElementsByTagName("script")[0].parentNode.appendChild(n)},serverSideFetch:function(e,t){var r=this;n({url:this.endpoint+e,json:true},function(e,n,i){if(e){return console.error(e)}t.call(r,i)})},isWanted:function(e){if(this.wanted.length===0){return true}else{return a(this.wanted,e)!==-1}},data:function(){if(this.model_names.length===0){return undefined}if(this.simpleSheet){if(this.model_names.length>1&&this.debug){this.log("WARNING You have more than one sheet but are using simple sheet mode! Don't blame me when something goes wrong.")}return this.models[this.model_names[0]].all()}else{return this.models}},addWanted:function(e){if(a(this.wanted,e)===-1){this.wanted.push(e)}},loadSheets:function(e){var n,i;var s=[];this.foundSheetNames=[];for(n=0,i=e.feed.entry.length;n<i;n++){this.foundSheetNames.push(e.feed.entry[n].title.$t);if(this.isWanted(e.feed.entry[n].content.$t)){var o=e.feed.entry[n].link.length-1;var u=e.feed.entry[n].link[o].href.split("/").pop();var a="/feeds/list/"+this.key+"/"+u+"/public/values?alt=";if(t||r){a+="json"}else{a+="json-in-script"}if(this.query){a+="&sq="+this.query}if(this.orderby){a+="&orderby=column:"+this.orderby.toLowerCase()}if(this.reverse){a+="&reverse=true"}s.push(a)}}this.sheetsToLoad=s.length;for(n=0,i=s.length;n<i;n++){this.requestData(s[n],this.loadSheet)}},sheets:function(e){if(typeof e==="undefined"){return this.models}else{if(typeof this.models[e]==="undefined"){return}else{return this.models[e]}}},loadSheet:function(e){var t=new f.Model({data:e,parseNumbers:this.parseNumbers,postProcess:this.postProcess,tabletop:this});this.models[t.name]=t;if(a(this.model_names,t.name)===-1){this.model_names.push(t.name)}this.sheetsToLoad--;if(this.sheetsToLoad===0)this.doCallback()},doCallback:function(){if(this.sheetsToLoad===0){this.callback.apply(this.callbackContext||this,[this.data(),this])}},log:function(e){if(this.debug){if(typeof console!=="undefined"&&typeof console.log!=="undefined"){Function.prototype.apply.apply(console.log,[console,arguments])}}}};f.Model=function(e){var t,n,r,i;this.column_names=[];this.name=e.data.feed.title.$t;this.elements=[];this.raw=e.data;if(typeof e.data.feed.entry==="undefined"){e.tabletop.log("Missing data for "+this.name+", make sure you didn't forget column headers");this.elements=[];return}for(var s in e.data.feed.entry[0]){if(/^gsx/.test(s))this.column_names.push(s.replace("gsx$",""))}for(t=0,r=e.data.feed.entry.length;t<r;t++){var o=e.data.feed.entry[t];var u={};for(var n=0,i=this.column_names.length;n<i;n++){var a=o["gsx$"+this.column_names[n]];if(typeof a!=="undefined"){if(e.parseNumbers&&a.$t!==""&&!isNaN(a.$t))u[this.column_names[n]]=+a.$t;else u[this.column_names[n]]=a.$t}else{u[this.column_names[n]]=""}}if(u.rowNumber===undefined)u.rowNumber=t+1;if(e.postProcess)e.postProcess(u);this.elements.push(u)}};f.Model.prototype={all:function(){return this.elements},toArray:function(){var e=[],t,n,r,i;for(t=0,r=this.elements.length;t<r;t++){var s=[];for(n=0,i=this.column_names.length;n<i;n++){s.push(this.elements[t][this.column_names[n]])}e.push(s)}return e}};if(t){module.exports=f}else{e.Tabletop=f}})(this)
	// end inclusion
	
	if (w.self != w.top) {
        return;
    }
	
    if (/http:\/\/l2central.info\/classic/.test(w.location.href)) {
        var buttonTd = $("td:contains(' Базовая цена:')").first().siblings().last();
        var craftButton = 
            $('<button/>', 
              { text: "Крафт", 
               click: function () {
                   Tabletop.init( { key: '1Cbc8Vnx95vGx_j5lCEuX3iTAXuBMARhMKxsl_qw0MkI',
                                   callback: function(data) {         console.log('got data'); calculatecraftCostTrade(data); },
                                   simpleSheet: true, 
                                   parseNumbers: true,
                                   prettyColumnNames: false } );
               }
              });
        buttonTd.append(craftButton);
        console.log(craftButton);
    }
	
	var resMap = {};
	var craftCostTrade = 0;
	var craftCostBuy = 0;
	
	function calculatecraftCostTrade(data) {
		for(var i = 0; i < data.length; i++) {
			resMap[data[i].name] = [data[i].costtrade || 0, data[i].costbuy || 0];
		}
        $("a:contains('Создание: 100%')").click();
        var expander = $("span.fancytree-expander").last();
        expander.click();
        var total = expander.parent().find("b:contains('Всего материалов')").first();
		var childs = total.parent().parent().next().children().children();
		for (var i = 0; i < childs.length; i++) {
			var item = childs[i].querySelectorAll('span')[0];
			calculateResCost(item);
		}
		
		total.text(total.text() + " на " + craftCostTrade + "/" + craftCostBuy + " ");
        var linkEdit = $('<a/>', {
            text: "редактировать",
            href: 'https://docs.google.com/spreadsheets/d/1Cbc8Vnx95vGx_j5lCEuX3iTAXuBMARhMKxsl_qw0MkI/edit'
        });
		total.append(linkEdit);
	}
	
	function calculateResCost(item) {
		var itemName = item.querySelectorAll('.i_name>a')[0].text;
		var itemCountNode = item.querySelectorAll('.i_count')[0];
		var itemCountText = itemCountNode.innerHTML;
		var itemCount = itemCountText.substring(0, itemCountText.indexOf(' '));
		
		var resCostTrade = 0, resCostBuy = 0;
		if (resMap[itemName]) {
			resCostTrade = getTotalCost(resMap[itemName][0], itemCount);
			craftCostTrade += resCostTrade;
			resCostBuy = getTotalCost(resMap[itemName][1], itemCount);
			craftCostBuy += resCostBuy;
		}

		if (!resCostTrade && !resCostBuy) {
			itemCountNode.innerHTML += " (цена не указана)";
		} else {
			itemCountNode.innerHTML += " за " + resCostTrade + "/" + resCostBuy + " (по " + resMap[itemName][0] + "/" + resMap[itemName][1] + ")";
		}
	}
	
	function getTotalCost(cost, num) {
		return (cost || 0) * num;
	}
	
	function getByText( xpath ){	
		return document.evaluate( xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
	}
// ==/UserScript==