MediaWiki:Common.js: Difference between revisions

From Official Factorio Wiki
Jump to navigation Jump to search
m (typo)
(fuck variables)
Line 2: Line 2:
/* Infobox updating */
/* Infobox updating */
var NoInfobox = ["Basic oil processing", "Advanced oil processing", "Coal liquefaction", "Empty barrel", "Heavy oil cracking", "Light oil cracking", "Solid fuel from heavy oil", "Solid fuel from light oil", "Solid fuel from petroleum gas"]
var NoInfobox = ["Basic oil processing", "Advanced oil processing", "Coal liquefaction", "Empty barrel", "Heavy oil cracking", "Light oil cracking", "Solid fuel from heavy oil", "Solid fuel from light oil", "Solid fuel from petroleum gas"]
var version = "0.15.12";
var version = "0.15.12";
Line 25: Line 24:
};
};


function getPage(Title) { //returns content
$.ajax({
url: 'https://wiki.factorio.com/api.php',
data: {
format: 'json',
action: 'query',
titles: Title,
prop: 'revisions',
rvprop: 'content'
},
async: false,
dataType: 'json',
type: 'GET',
success: function( data ) {
var pages = data.query.pages;
var revisions = pages[Object.keys(pages)[0]].revisions[0];
var content = revisions[Object.keys(revisions)[2]];
var title = pages[Object.keys(pages)[0]].title;
},
error: function( xhr ) {
alert( 'Error: Request failed.' );
content = "";
}
});
return content;
};


var PagePara = "";
var PagePara = "";
function getOldPara(PageParaStart, Length, Name, ItemName) { //also uses OldContent
function getOldPara(Content, PageParaStart, Length, Name, ItemName) {
if (PageParaStart < Length) { //if the start is less than the length of the para name (Name) then the search was unsuccessful
if (PageParaStart < Length) { //if the start is less than the length of the para name (Name) then the search was unsuccessful
console.log(ItemName + ": No " + Name + " found on page.");
console.log(ItemName + ": No " + Name + " found on page.");
PagePara = "";
PagePara = "";
} else {
} else {
var PageParaCut = OldContent.slice(PageParaStart);
var PageParaCut = Content.slice(PageParaStart);
PageParaStart = PageParaCut.search(/\w/);
PageParaStart = PageParaCut.search(/\w/);
PageParaCut = PageParaCut.slice(PageParaStart); //removes anything before the parameter that does not belong there, like = and \s
PageParaCut = PageParaCut.slice(PageParaStart); //removes anything before the parameter that does not belong there, like = and \s
var PageParaEnd = PageParaCut.search(/\||}}/); //finds the end of the parameter definition
var PageParaEnd = PageParaCut.search(/\||}}/); //finds the end of the parameter definition
if (PageParaEnd < 1) { //Para ends at para-end if it exists
if (PageConsumersEnd < 1) { //Para ends at para-end if it exists
PagePara = PageParaCut;
PagePara = PageParaCut;
} else {
} else {
PagePara = PageParaCut.slice(0, PageParaEnd);
PagePara = PageParaCut.slice(0, PagePara);
}
}
}
}
Line 45: Line 71:
};
};


 
var Summary = "";
function UpdatePara(Content, Para, PagePara, Name, NewPageParaStart, Length, ItemName) {  //also needs version, Summary, (NewContent!!)
function UpdatePara(Content, Para, PagePara, Name, NewPageParaStart, Length, ItemName) {  //also needs version, Summary
if (PagePara.length > 0) {
if (PagePara.length > 0) {
var NewPageParaCut = Content.slice(NewPageParaStart); //lets the string being after the parameter name
var NewPageParaCut = Content.slice(NewPageParaStart); //lets the string being after the parameter name
Line 157: Line 183:
//get page content of the item -> OldContent
//get page content of the item -> OldContent
$.ajax({
var OldContent = getPage(ItemName + "/infobox")
url: 'https://wiki.factorio.com/api.php',
data: {
format: 'json',
action: 'query',
titles: ItemName + '/infobox',
prop: 'revisions',
rvprop: 'content'
},
async: false,
dataType: 'json',
type: 'GET',
success: function( data ) {
var pages = data.query.pages;
var revisions = pages[Object.keys(pages)[0]].revisions[0];
OldContent = revisions[Object.keys(revisions)[2]];
var title = pages[Object.keys(pages)[0]].title;
},
error: function( xhr ) {
alert( 'Error: Request failed.' );
OldContent = "";
}
});
if (OldContent.length = 0) {
if (OldContent.length = 0) {
console.log("No " + ItemName + " page found.");
console.log("No " + ItemName + " page found.");
Line 188: Line 192:
//find recipes in page (OldContent)
//find recipes in page (OldContent)
var PageRecipeStart = OldContent.search(/(\s|\|)recipe/) + 7;
var PageRecipeStart = OldContent.search(/(\s|\|)recipe/) + 7;
var PageRecipe = getOldPara(PageRecipeStart, 7, "recipe", ItemName);
var PageRecipe = getOldPara(OldContent, PageRecipeStart, 7, "recipe", ItemName);


var PageTotalRawStart = OldContent.search(/(\s|\|)total-raw/) + 10;
var PageTotalRawStart = OldContent.search(/(\s|\|)total-raw/) + 10;
var PageTotalRaw = getOldPara(PageTotalRawStart, 10, "total-raw", ItemName);
var PageTotalRaw = getOldPara(OldContent, PageTotalRawStart, 10, "total-raw", ItemName);
var PageExpRecipeStart = OldContent.search(/(\s|\|)expensive-recipe/) + 17;
var PageExpRecipeStart = OldContent.search(/(\s|\|)expensive-recipe/) + 17;
var PageExpRecipe = getOldPara(PageExpRecipeStart, 17, "expensive-recipe", ItemName);
var PageExpRecipe = getOldPara(OldContent, PageExpRecipeStart, 17, "expensive-recipe", ItemName);


var PageExpTotalRawStart = OldContent.search(/(\s|\|)expensive-total-raw/) + 20;
var PageExpTotalRawStart = OldContent.search(/(\s|\|)expensive-total-raw/) + 20;
var PageExpTotalRaw = getOldPara(PageExpTotalRawStart, 20, "expensive-total-raw", ItemName);
var PageExpTotalRaw = getOldPara(OldContent, PageExpTotalRawStart, 20, "expensive-total-raw", ItemName);


Line 206: Line 210:
PageExpTotalRaw = PageExpTotalRaw.trim();
PageExpTotalRaw = PageExpTotalRaw.trim();
var Summary = "";
Summary = "";
//change page if anything is different (this INCLUDES different formatting)
//change page if anything is different (this INCLUDES different formatting)
Line 216: Line 220:
NewContent = OldContent;
NewContent = OldContent;
var NewPageRecipeStart = NewContent.search(/(\s|\|)recipe/) + 7;
var NewPageRecipeStart = NewContent.search(/(\s|\|)recipe/) + 7;
UpdatePara(Recipe, PageRecipe, "recipe", NewPageRecipeStart, 7, ItemName);
UpdatePara(NewContent, Recipe, PageRecipe, "recipe", NewPageRecipeStart, 7, ItemName);
}
}
if (PageTotalRaw != TotalRaw) {
if (PageTotalRaw != TotalRaw) {
Line 223: Line 227:
}
}
var NewPageTotalRawStart = NewContent.search(/(\s|\|)total-raw/) + 10;
var NewPageTotalRawStart = NewContent.search(/(\s|\|)total-raw/) + 10;
UpdatePara(TotalRaw, PageTotalRaw, "total-raw", NewPageTotalRawStart, 10, ItemName);
UpdatePara(NewContent, TotalRaw, PageTotalRaw, "total-raw", NewPageTotalRawStart, 10, ItemName);
}
}
if (PageExpRecipe != ExpRecipe) {
if (PageExpRecipe != ExpRecipe) {
Line 230: Line 234:
}
}
var NewPageExpRecipeStart = NewContent.search(/(\s|\|)expensive-recipe/) + 17;
var NewPageExpRecipeStart = NewContent.search(/(\s|\|)expensive-recipe/) + 17;
UpdatePara(ExpRecipe, PageExpRecipe, "expensive-recipe", NewPageExpRecipeStart, 17, ItemName);
UpdatePara(NewContent, ExpRecipe, PageExpRecipe, "expensive-recipe", NewPageExpRecipeStart, 17, ItemName);
}
}
if (PageExpTotalRaw != ExpTotalRaw) {
if (PageExpTotalRaw != ExpTotalRaw) {
Line 237: Line 241:
}
}
var NewPageExpTotalRawStart = NewContent.search(/(\s|\|)expensive-total-raw/) + 20;
var NewPageExpTotalRawStart = NewContent.search(/(\s|\|)expensive-total-raw/) + 20;
UpdatePara(ExpTotalRaw, PageExpTotalRaw, "expensive-total-raw", NewPageExpTotalRawStart, 20, ItemName);
UpdatePara(NewContent, ExpTotalRaw, PageExpTotalRaw, "expensive-total-raw", NewPageExpTotalRawStart, 20, ItemName);
}
}
}
}
Line 284: Line 288:
//get page content of the item -> OldContent
//get page content of the item -> OldContent
$.ajax({
var OldContent = getPage(ItemName + '/infobox')
url: 'https://wiki.factorio.com/api.php',
data: {
format: 'json',
action: 'query',
titles: ItemName + '/infobox',
prop: 'revisions',
rvprop: 'content'
},
async: false,
dataType: 'json',
type: 'GET',
success: function( data ) {
var pages = data.query.pages;
var revisions = pages[Object.keys(pages)[0]].revisions[0];
OldContent = revisions[Object.keys(revisions)[2]];
var title = pages[Object.keys(pages)[0]].title;
},
error: function( xhr ) {
alert( 'Error: Request failed.' );
OldContent = "";
}
});
if (OldContent.length = 0) {
if (OldContent.length = 0) {
console.log("No " + ItemName + " page found.");
console.log("No " + ItemName + " page found.");
Line 316: Line 297:
//find recipes in page (OldContent)
//find recipes in page (OldContent)
var PageConsumersStart = OldContent.search(/(\s|\|)consumers/) + 10;
var PageConsumersStart = OldContent.search(/(\s|\|)consumers/) + 10;
var PageConsumers = getOldPara(PageConsumersStart, 10, "consumers", ItemName);
var PageConsumers = getOldPara(OldContent, PageConsumersStart, 10, "consumers", ItemName);
var PageStackSizeStart = OldContent.search(/(\s|\|)stack-size/) + 11;
var PageStackSizeStart = OldContent.search(/(\s|\|)stack-size/) + 11;
var PageStackSize = getOldPara(PageStackSizeStart, 11, "stack-size", ItemName);
var PageStackSize = getOldPara(OldContent, PageStackSizeStart, 11, "stack-size", ItemName);
Line 325: Line 306:
PageStackSize = PageStackSize.trim();
PageStackSize = PageStackSize.trim();
var Summary = "";
Summary = "";
//change page if anything is different (this INCLUDES different formatting)
//change page if anything is different (this INCLUDES different formatting)
Line 333: Line 314:
} else {
} else {
if (PageConsumers != Consumers) {
if (PageConsumers != Consumers) {
var NewPageConsumersStart = OldContent.search(/(\s|\|)consumers/) + 10;
NewContent = OldContent;
UpdatePara(OldContent, Consumers, PageConsumers, "consumers", NewPageConsumersStart, 10, ItemName);
var NewPageConsumersStart = NewContent.search(/(\s|\|)consumers/) + 10;
UpdatePara(NewContent, Consumers, PageConsumers, "consumers", NewPageConsumersStart, 10, ItemName);
}
}
if (PageStackSize != StackSize) {
if (PageStackSize != StackSize) {
Line 392: Line 374:
//get page content of the tech -> OldContent
//get page content of the tech -> OldContent
$.ajax({
var OldContent = getPage(TechName + " (research)/infobox")
url: 'https://wiki.factorio.com/api.php',
data: {
format: 'json',
action: 'query',
titles: TechName + ' (research)/infobox',
prop: 'revisions',
rvprop: 'content'
},
async: false,
dataType: 'json',
type: 'GET',
success: function( data ) {
var pages = data.query.pages;
var revisions = pages[Object.keys(pages)[0]].revisions[0];
OldContent = revisions[Object.keys(revisions)[2]];
var title = pages[Object.keys(pages)[0]].title;
},
error: function( xhr ) {
alert( 'Error: Request failed.' );
OldContent = "";
}
});
if (OldContent.length = 0) {
if (OldContent.length = 0) {
console.log("No " + TechName + " page found.");
console.log("No " + TechName + " page found.");
Line 424: Line 383:
//find costs etc in page (OldContent)
//find costs etc in page (OldContent)
var PageCostStart = OldContent.search(/(\s|\|)cost(\s|=)/) + 6;
var PageCostStart = OldContent.search(/(\s|\|)cost(\s|=)/) + 6;
var PageCost = getOldPara(PageCostStart, 6, "cost", TechName);
var PageCost = getOldPara(OldContent, PageCostStart, 6, "cost", TechName);
var PageCostMultiStart = OldContent.search(/(\s|\|)cost-multiplier/) + 16;
var PageCostMultiStart = OldContent.search(/(\s|\|)cost-multiplier/) + 16;
var PageCostMulti = getOldPara(PageCostMultiStart, 16, "cost-multiplier", TechName);
var PageCostMulti = getOldPara(OldContent, PageCostMultiStart, 16, "cost-multiplier", TechName);
var PageExpCostMultiStart = OldContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
var PageExpCostMultiStart = OldContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
var PageExpCostMulti = getOldPara(PageExpCostMultiStart, 26, "expensive-cost-multiplier", TechName);
var PageExpCostMulti = getOldPara(OldContent, PageExpCostMultiStart, 26, "expensive-cost-multiplier", TechName);
var PageReqTechStart = OldContent.search(/(\s|\|)required-technologies/) + 22;
var PageReqTechStart = OldContent.search(/(\s|\|)required-technologies/) + 22;
var PageReqTech = getOldPara(PageReqTechStart, 22, "required-technologies", TechName);
var PageReqTech = getOldPara(OldContent, PageReqTechStart, 22, "required-technologies", TechName);
var PageAllowsStart = OldContent.search(/(\s|\|)allows/) + 7;
var PageAllowsStart = OldContent.search(/(\s|\|)allows/) + 7;
var PageAllows = getOldPara(PageAllowsStart, 7, "allows", TechName);
var PageAllows = getOldPara(OldContent, PageAllowsStart, 7, "allows", TechName);
var PageEffectsStart = OldContent.search(/(\s|\|)effects/) + 8;
var PageEffectsStart = OldContent.search(/(\s|\|)effects/) + 8;
var PageEffects = getOldPara(PageEffectsStart, 8, "effects", TechName);
var PageEffects = getOldPara(OldContent, PageEffectsStart, 8, "effects", TechName);


Line 450: Line 409:
var Summary = "";
Summary = "";
var NewContent = "";
var NewContent = "";
Line 460: Line 419:
NewContent = OldContent;
NewContent = OldContent;
var NewPageCostStart = NewContent.search(/(\s|\|)cost(\s|=)/) + 6;
var NewPageCostStart = NewContent.search(/(\s|\|)cost(\s|=)/) + 6;
UpdatePara(Cost, PageCost, "cost", NewPageCostStart, 6, TechName);
UpdatePara(NewContent, Cost, PageCost, "cost", NewPageCostStart, 6, TechName);
}
}
if (PageCostMulti != CostMulti) {
if (PageCostMulti != CostMulti) {
Line 467: Line 426:
}
}
var NewPageCostMultiStart = NewContent.search(/(\s|\|)cost-multiplier/) + 16;
var NewPageCostMultiStart = NewContent.search(/(\s|\|)cost-multiplier/) + 16;
UpdatePara(CostMulti, PageCostMulti, "cost-multiplier", NewPageCostMultiStart, 16, TechName);
UpdatePara(NewContent, CostMulti, PageCostMulti, "cost-multiplier", NewPageCostMultiStart, 16, TechName);
}
}
if (PageExpCostMulti != ExpCostMulti) {
if (PageExpCostMulti != ExpCostMulti) {
Line 474: Line 433:
}
}
var NewPageExpCostMultiStart = NewContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
var NewPageExpCostMultiStart = NewContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
UpdatePara(ExpCostMulti, PageExpCostMulti, "expensive-cost-multiplier", NewPageExpCostMultiStart, 26, TechName);
UpdatePara(NewContent, ExpCostMulti, PageExpCostMulti, "expensive-cost-multiplier", NewPageExpCostMultiStart, 26, TechName);
}
}
if (PageReqTech != ReqTech) {
if (PageReqTech != ReqTech) {
Line 481: Line 440:
}
}
var NewPageReqTechStart = NewContent.search(/(\s|\|)required-technologies/) + 22;
var NewPageReqTechStart = NewContent.search(/(\s|\|)required-technologies/) + 22;
UpdatePara(ReqTech, PageReqTech, "required-technologies", NewPageReqTechStart, 22, TechName);
UpdatePara(NewContent, ReqTech, PageReqTech, "required-technologies", NewPageReqTechStart, 22, TechName);
}
}
if (PageAllows != Allows) {
if (PageAllows != Allows) {
Line 488: Line 447:
}
}
var NewPageAllowsStart = NewContent.search(/(\s|\|)allows/) + 7;
var NewPageAllowsStart = NewContent.search(/(\s|\|)allows/) + 7;
UpdatePara(Allows, PageAllows, "allows", NewPageAllowsStart, 7, TechName);
UpdatePara(NewContent, Allows, PageAllows, "allows", NewPageAllowsStart, 7, TechName);
}
}
if (PageEffects != Effects) {
if (PageEffects != Effects) {
Line 495: Line 454:
}
}
var NewPageEffectsStart = NewContent.search(/(\s|\|)effects/) + 8;
var NewPageEffectsStart = NewContent.search(/(\s|\|)effects/) + 8;
UpdatePara(Effects, PageEffects, "effects", NewPageEffectsStart, 8, TechName);
UpdatePara(NewContent, Effects, PageEffects, "effects", NewPageEffectsStart, 8, TechName);
}
}
}
}

Revision as of 15:19, 20 May 2017

/* Any JavaScript here will be loaded for all users on every page load. */
	
/* Infobox updating */
var NoInfobox = ["Basic oil processing", "Advanced oil processing", "Coal liquefaction", "Empty barrel", "Heavy oil cracking", "Light oil cracking", "Solid fuel from heavy oil", "Solid fuel from light oil", "Solid fuel from petroleum gas"]
var version = "0.15.12";


var Para = "";
function getInputPara(Item, Search, Length, Name, ItemName) {
	var ParaStart = Item.search(Search) + Length; //finds the beginning of the para, is after para-name
	if (ParaStart < Length) {
		console.log(ItemName + ": No " + Name + " found.");
		Para = "";
	} else {
		var ParaCut = Item.slice(ParaStart);  //lets the string begin after the parameter name
		var ParaEnd = ParaCut.search(/\||}}/); //finds the end of the parameter definition
		if (ParaEnd < 1) { //Para ends at para-end if it exists
			Para = ParaCut;
		} else {
			Para = ParaCut.slice(0, ParaEnd);
		}
	}
	return Para;
};


function getPage(Title) { //returns content
	$.ajax({
		url: 'https://wiki.factorio.com/api.php',
		data: {
			format: 'json',
			action: 'query',
			titles: Title,
			prop: 'revisions',
			rvprop: 'content'
		},
		async: false,
		dataType: 'json',
		type: 'GET',
		success: function( data ) {
			var pages = data.query.pages;
			var revisions = pages[Object.keys(pages)[0]].revisions[0];
			var content = revisions[Object.keys(revisions)[2]];
			var title = pages[Object.keys(pages)[0]].title;
		},
		error: function( xhr ) {
			alert( 'Error: Request failed.' );
			content = "";
		}
	});
	return content;
};

var PagePara = "";
function getOldPara(Content, PageParaStart, Length, Name, ItemName) {
	if (PageParaStart < Length) { //if the start is less than the length of the para name (Name) then the search was unsuccessful
		console.log(ItemName + ": No " + Name + " found on page.");
		PagePara = "";
	} else {
		var PageParaCut = Content.slice(PageParaStart);
		PageParaStart = PageParaCut.search(/\w/);
		PageParaCut = PageParaCut.slice(PageParaStart); //removes anything before the parameter that does not belong there, like = and \s
		var PageParaEnd = PageParaCut.search(/\||}}/); //finds the end of the parameter definition
		if (PageConsumersEnd < 1) { //Para ends at para-end if it exists
			PagePara = PageParaCut;
		} else {
			PagePara = PageParaCut.slice(0, PagePara);
		}
	}
	return PagePara;
};

var Summary = "";
function UpdatePara(Content, Para, PagePara, Name, NewPageParaStart, Length, ItemName) {  //also needs version, Summary
	if (PagePara.length > 0) {
		var NewPageParaCut = Content.slice(NewPageParaStart); //lets the string being after the parameter name
		var NewPageParaEnd = NewPageParaCut.search(/\||}}/) + NewPageParaStart; //finds the end of the parameter definition, with added parastart so that it's relative to the start of the entire string, not the parameter string
		if (Para.length > 0) {
			NewContent = Content.slice(0, NewPageParaStart) + " = " + Para + "\n" + Content.slice(NewPageParaEnd);
			console.log("Replaced " + ItemName + " " + Name + ".");
			Summary = Summary + "Updated " + Name + " to " + version + ". ";
		} else {
			NewPageParaStart = NewPageParaStart - Length; //makes it so that the start of the para string if before the name, so that the name also gets deleted
			NewContent = Content.slice(0, NewPageParaStart) + Content.slice(NewPageParaEnd); //removes what is between parastart and paraend from newcontent
			console.log("Removed " + ItemName + " " + Name + ". ");
			Summary = Summary + "Removed " + Name + ". ";
		}
	} else if (Para.length > 0) {
		var InfoboxStart = Content.search(/{{Infobox/i) + 9; //finds the start of the infobox, excludes {{infobox from the resulting string
		NewContent = Content.slice(0, InfoboxStart) + "\n|" + Name + " = " + Para + Content.slice(InfoboxStart);
		console.log("Added " + ItemName + " " + Name + ". ");
		Summary = Summary + "Added " + Name + ". ";
	}
};


function EditPage(Title, ItemName) { //also uses Summary, globalToken, NewContent
	$.ajax({
		url: 'https://wiki.factorio.com/api.php',
		data: {
			format: 'json',
			action: 'edit',
			title: Title,
			text: NewContent,
			token: globalToken,
			summary: Summary,
			bot: true,
			nocreate: true
		},
		dataType: 'json',
		type: 'POST',
		success: function( data ) {
		   console.log("Updated " + ItemName);
		},
		error: function( xhr ) {
			console.log("Failed to update " + ItemName);
		}
	});
};


$("#RecipeUpdate").click(function(){
    getRecipes();
});

function getRecipes() {
	getUserGroup();
	if (UserGroup.some(isBot) == true) {
		var RecipeInput = prompt("Please enter the recipes");
		if (RecipeInput != null) {
			getToken();
			var OldContent = "";
			var Items = RecipeInput.split(/\s\s/g);
			console.log(Items.length + " Items detected");
			Items.forEach(RemoveDuplicateRecipesAndUpdateInfobox);
		}
	}
};


function RemoveDuplicateRecipesAndUpdateInfobox(Recipes) {
	var ItemNameEnd = Recipes.search("\\|");
	var ItemName = Recipes.slice(0, ItemNameEnd);
	ItemName = ItemName.trim();
	
	//Remove Itemnames if the item does not have a page on the wiki, so that the item is removed from the output
	NoInfobox.forEach(function(InfoboxName) {
	if (ItemName == InfoboxName) {
		console.log("Removed " + ItemName + " from output.");
		return;
	}
	})
	
	var Recipe = getInputPara(Recipes, "\\|recipe = ", 10, "recipe", ItemName);
	var TotalRaw = getInputPara(Recipes, "\\|total-raw = ", 13, "total-raw", ItemName);
	var ExpRecipe = getInputPara(Recipes, "\\|expensive-recipe = ", 20, "expensive-recipe", ItemName);
	var ExpTotalRaw = getInputPara(Recipes, "\\|expensive-total-raw = ", 23, "expensive-total-raw", ItemName);
	
	//remove whitespace
	Recipe = Recipe.trim();
	TotalRaw = TotalRaw.trim();
	ExpRecipe = ExpRecipe.trim();
	ExpTotalRaw = ExpTotalRaw.trim();	
	
	
	//remove duplicate recipes, but only if the recipe actually exists
	if ((ExpTotalRaw == ExpRecipe) && (ExpTotalRaw.length > 0)) {
		ExpTotalRaw = "";
		console.log(ItemName + ": Removed expensive-total-raw because it was a duplicate of expensive-recipe.");
	} else if ((ExpTotalRaw == TotalRaw) && (ExpTotalRaw.length > 0)) {
		ExpTotalRaw = "";
		console.log(ItemName + ": Removed expensive-total-raw because it was a duplicate of total-raw.");
	}
	if ((ExpRecipe == Recipe) && (ExpRecipe.length > 0)) {
		ExpRecipe = "";
		console.log(ItemName + ": Removed expensive-recipe because it was a duplicate of recipe.");
	}
	if ((TotalRaw == Recipe) && (TotalRaw.length > 0)) {
		TotalRaw = "";
		console.log(ItemName + ": Removed total-raw because it was a duplicate of recipe.");
	}
	
	
	//get page content of the item -> OldContent
	var OldContent = getPage(ItemName + "/infobox")
	if (OldContent.length = 0) {
		console.log("No " + ItemName + " page found.");
		return;
	}
	
	
	//find recipes in page (OldContent)
	var PageRecipeStart = OldContent.search(/(\s|\|)recipe/) + 7;
	var PageRecipe = getOldPara(OldContent, PageRecipeStart, 7, "recipe", ItemName);

	var PageTotalRawStart = OldContent.search(/(\s|\|)total-raw/) + 10;
	var PageTotalRaw = getOldPara(OldContent, PageTotalRawStart, 10, "total-raw", ItemName);
	
	var PageExpRecipeStart = OldContent.search(/(\s|\|)expensive-recipe/) + 17;
	var PageExpRecipe = getOldPara(OldContent, PageExpRecipeStart, 17, "expensive-recipe", ItemName);

	var PageExpTotalRawStart = OldContent.search(/(\s|\|)expensive-total-raw/) + 20;
	var PageExpTotalRaw = getOldPara(OldContent, PageExpTotalRawStart, 20, "expensive-total-raw", ItemName);

	
	//remove whitespace
	PageRecipe = PageRecipe.trim();
	PageTotalRaw = PageTotalRaw.trim();
	PageExpRecipe = PageExpRecipe.trim();
	PageExpTotalRaw = PageExpTotalRaw.trim();
	
	Summary = "";
	
	//change page if anything is different (this INCLUDES different formatting)
	var NewContent = "";
	if ((PageRecipe == Recipe) && (PageTotalRaw == TotalRaw) && (PageExpRecipe == ExpRecipe) && (PageExpTotalRaw == ExpTotalRaw)) {
		console.log(ItemName + " page was not changed.")
	} else {
		if (PageRecipe != Recipe) {
			NewContent = OldContent;
			var NewPageRecipeStart = NewContent.search(/(\s|\|)recipe/) + 7;
			UpdatePara(NewContent, Recipe, PageRecipe, "recipe", NewPageRecipeStart, 7, ItemName);
		}
		if (PageTotalRaw != TotalRaw) {
			if (NewContent.length == 0) {
				NewContent = OldContent
			}
			var NewPageTotalRawStart = NewContent.search(/(\s|\|)total-raw/) + 10;
			UpdatePara(NewContent, TotalRaw, PageTotalRaw, "total-raw", NewPageTotalRawStart, 10, ItemName);
		}
		if (PageExpRecipe != ExpRecipe) {
			if (NewContent.length == 0) {
				NewContent = OldContent
			}
			var NewPageExpRecipeStart = NewContent.search(/(\s|\|)expensive-recipe/) + 17;
			UpdatePara(NewContent, ExpRecipe, PageExpRecipe, "expensive-recipe", NewPageExpRecipeStart, 17, ItemName);
		}
		if (PageExpTotalRaw != ExpTotalRaw) {
			if (NewContent.length == 0) {
				NewContent = OldContent
			}
			var NewPageExpTotalRawStart = NewContent.search(/(\s|\|)expensive-total-raw/) + 20;
			UpdatePara(NewContent, ExpTotalRaw, PageExpTotalRaw, "expensive-total-raw", NewPageExpTotalRawStart, 20, ItemName);
		}
	}
	//alright, NewContent should be defined, change page:
	if (NewContent.length > 0) {
		EditPage(ItemName + "/infobox", ItemName);
	}	
}

$("#ConsumerUpdate").click(function(){
    getConsumersAndStackSize();
});

function getConsumersAndStackSize() {
	getUserGroup();
		if (UserGroup.some(isBot) == false) {
		return;
	}
	var ItemInput = prompt("Please enter the consumers and the stack-sizes");
	if (ItemInput != null) {
		getToken();
		var Items = ItemInput.split(/\s\s/g);
		console.log(Items.length + " Items detected");
		Items.forEach(UpdateInfoboxWithConsumersAndStackSize);
	}
};

function UpdateInfoboxWithConsumersAndStackSize(Item) {
	var ItemNameEnd = Item.search("\\|");
	var ItemName = Item.slice(0, ItemNameEnd);
	ItemName = ItemName.trim();
	
	//Remove Items that don't have Infoboxes on the wiki
	NoInfobox.forEach(function(InfoboxName) {
	if (ItemName == InfoboxName) {
		console.log("Removed " + ItemName + " from output.");
		return;
	}
	})
	
	var Consumers = getInputPara(Item, "\\|consumers = ", 13, "consumers", ItemName);
	var StackSize = getInputPara(Item, "\\|stack-size = ", 14, "stack-size", ItemName);

	Consumers = Consumers.trim();
	StackSize = StackSize.trim();
	
	
	//get page content of the item -> OldContent
	var OldContent = getPage(ItemName + '/infobox')
	if (OldContent.length = 0) {
		console.log("No " + ItemName + " page found.");
		return;
	}
	
	//find recipes in page (OldContent)
	var PageConsumersStart = OldContent.search(/(\s|\|)consumers/) + 10;
	var PageConsumers = getOldPara(OldContent, PageConsumersStart, 10, "consumers", ItemName);
	
	var PageStackSizeStart = OldContent.search(/(\s|\|)stack-size/) + 11;
	var PageStackSize = getOldPara(OldContent, PageStackSizeStart, 11, "stack-size", ItemName);
	
	
	PageConsumers = PageConsumers.trim();
	PageStackSize = PageStackSize.trim();
	
	Summary = "";
	
	//change page if anything is different (this INCLUDES different formatting)
	var NewContent = "";
	if ((PageConsumers == Consumers) && (PageStackSize == StackSize)) {
		console.log(ItemName + " page was not changed.")
	} else {
		if (PageConsumers != Consumers) {
			NewContent = OldContent;
			var NewPageConsumersStart = NewContent.search(/(\s|\|)consumers/) + 10;
			UpdatePara(NewContent, Consumers, PageConsumers, "consumers", NewPageConsumersStart, 10, ItemName);
		}
		if (PageStackSize != StackSize) {
			if (NewContent.length == 0) {
				NewContent = OldContent;
			}
			var NewPageStackSizeStart = NewContent.search(/(\s|\|)stack-size/) + 11;
			UpdatePara(NewContent, StackSize, PageStackSize, "stack-size", NewPageStackSizeStart, 11, ItemName);
		}
	}
	
	//alright, NewContent should be defined, change page:
	if (NewContent.length > 0) {
		EditPage(ItemName + "/infobox", ItemName);
	}
}

$("#TechUpdate").click(function(){
    getTechnologies();
});

function getTechnologies() {
	getUserGroup();
		if (UserGroup.some(isBot) == false) {
		return;
	}
	var TechInput = prompt("Please enter the technologies");
	if (TechInput != null) {
		getToken();
		var Techs = TechInput.split(/\s\s/g);
		console.log(Techs.length + " Techs detected");
		Techs.forEach(UpdateTechnologyInfobox);
	}
}

function UpdateTechnologyInfobox(Tech) {
	var TechNameEnd = Tech.search("\\|");
	var TechName = Tech.slice(0, TechNameEnd);
	TechName = TechName.trim();
	
	
	var Cost = getInputPara(Tech, "\\|cost = ", 8, "cost", TechName);
	var CostMulti = getInputPara(Tech, "\\|cost-multiplier = ", 19, "cost-multiplier", TechName);
	var ExpCostMulti = getInputPara(Tech, "\\|expensive-cost-multiplier = ", 29, "expensive-cost-multiplier", TechName);
	var ReqTech = getInputPara(Tech, "\\|required-technologies = ", 25, "required-technologies", TechName);
	var Allows = getInputPara(Tech, "\\|allows = ", 10, "allows", TechName);
	var Effects = getInputPara(Tech, "\\|effects = ", 11, "effects", TechName);

	
	Cost = Cost.trim();
	CostMulti = CostMulti.trim();
	ExpCostMulti = ExpCostMulti.trim();
	ReqTech = ReqTech.trim();
	Allows = Allows.trim();
	Effects = Effects.trim();
	
	
	//get page content of the tech -> OldContent
	var OldContent = getPage(TechName + " (research)/infobox")
	if (OldContent.length = 0) {
		console.log("No " + TechName + " page found.");
		return;
	}
	
	
	//find costs etc in page (OldContent)
	var PageCostStart = OldContent.search(/(\s|\|)cost(\s|=)/) + 6;
	var PageCost = getOldPara(OldContent, PageCostStart, 6, "cost", TechName);
	
	var PageCostMultiStart = OldContent.search(/(\s|\|)cost-multiplier/) + 16;
	var PageCostMulti = getOldPara(OldContent, PageCostMultiStart, 16, "cost-multiplier", TechName);
	
	var PageExpCostMultiStart = OldContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
	var PageExpCostMulti = getOldPara(OldContent, PageExpCostMultiStart, 26, "expensive-cost-multiplier", TechName);
	
	var PageReqTechStart = OldContent.search(/(\s|\|)required-technologies/) + 22;
	var PageReqTech = getOldPara(OldContent, PageReqTechStart, 22, "required-technologies", TechName);
	
	var PageAllowsStart = OldContent.search(/(\s|\|)allows/) + 7;
	var PageAllows = getOldPara(OldContent, PageAllowsStart, 7, "allows", TechName);
	
	var PageEffectsStart = OldContent.search(/(\s|\|)effects/) + 8;
	var PageEffects = getOldPara(OldContent, PageEffectsStart, 8, "effects", TechName);

	
	PageCost = PageCost.trim();
	PageCostMulti = PageCostMulti.trim();
	PageExpCostMulti = PageExpCostMulti.trim();
	PageReqTech = PageReqTech.trim();
	PageAllows = PageAllows.trim();
	PageEffects = PageEffects.trim();
	
	
	Summary = "";
	var NewContent = "";
	
	//change page if anything is different (this INCLUDES different formatting)
	if ((PageCost == Cost) && (PageCostMulti == CostMulti) && (PageExpCostMulti == ExpCostMulti) && (PageReqTech == ReqTech) && (PageAllows == Allows) && (PageEffects == Effects)) {
		console.log(TechName + " page was not changed.")
	} else {
		if (PageCost != Cost) {
			NewContent = OldContent;
			var NewPageCostStart = NewContent.search(/(\s|\|)cost(\s|=)/) + 6;
			UpdatePara(NewContent, Cost, PageCost, "cost", NewPageCostStart, 6, TechName);
		}
		if (PageCostMulti != CostMulti) {
			if (NewContent.length == 0) {
				NewContent = OldContent;
			}
			var NewPageCostMultiStart = NewContent.search(/(\s|\|)cost-multiplier/) + 16;
			UpdatePara(NewContent, CostMulti, PageCostMulti, "cost-multiplier", NewPageCostMultiStart, 16, TechName);
		}
		if (PageExpCostMulti != ExpCostMulti) {
			if (NewContent.length == 0) {
				NewContent = OldContent;
			}
			var NewPageExpCostMultiStart = NewContent.search(/(\s|\|)expensive-cost-multiplier/) + 26;
			UpdatePara(NewContent, ExpCostMulti, PageExpCostMulti, "expensive-cost-multiplier", NewPageExpCostMultiStart, 26, TechName);
		}
		if (PageReqTech != ReqTech) {
			if (NewContent.length == 0) {
				NewContent = OldContent;
			}
			var NewPageReqTechStart = NewContent.search(/(\s|\|)required-technologies/) + 22;
			UpdatePara(NewContent, ReqTech, PageReqTech, "required-technologies", NewPageReqTechStart, 22, TechName);
		}
		if (PageAllows != Allows) {
			if (NewContent.length == 0) {
				NewContent = OldContent;
			}
			var NewPageAllowsStart = NewContent.search(/(\s|\|)allows/) + 7;
			UpdatePara(NewContent, Allows, PageAllows, "allows", NewPageAllowsStart, 7, TechName);
		}
		if (PageEffects != Effects) {
			if (NewContent.length == 0) {
				NewContent = OldContent;
			}
			var NewPageEffectsStart = NewContent.search(/(\s|\|)effects/) + 8;
			UpdatePara(NewContent, Effects, PageEffects, "effects", NewPageEffectsStart, 8, TechName);
		}	
	}
	//alright, NewContent should be defined, change page:
	if (NewContent.length > 0) {
		EditPage(TechName + " (research)/infobox", TechName);
	}	
}



/* user is bot if UserGroup.some(isBot) == true */

var UserGroup = "";

function getUserGroup() {
	$.ajax({
		url: 'https://wiki.factorio.com/api.php',
		data: {
			format: 'json',
			action: 'query',
			meta: 'userinfo',
			uiprop: 'groups',
		},
		async: false,
		dataType: 'json',
		type: 'GET',
		success: function(data) {
			UserGroup = data.query.userinfo.groups
		},
	});
};

function isBot(group) {
	return group == "bot";
}

var globalToken;

function getToken() {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            meta: 'tokens',
            bot: true
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           globalToken = data.query.tokens.csrftoken;
        },
        error: function( xhr ) {
            console.log("Failed to perform null edit");
        }
    });
}

/*** Language template ***/
if($(".languages-flags .flag").length == 0) {
 console.log("Not showing languages bar because there's no other language's version of this page.");
 $(".languages-container").hide();
}

//Spoiler template JavaScript
$(".spoiler-container .button").click(function() {
  $(this).siblings(".text").toggle("slow");
});

var wantedPagesListsLocation = "User:TheWombatGuru/WantedPages"
$("#create-wanted-pages-list").click(function(){
    getToken();
    createWantedPagesLists();
});

function createWantedPagesLists() {
    getUserGroup();
    if (UserGroup.some(isBot) == false) {
       return;
    }
    var wantedPages = getWantedPages();
    wantedPages = wantedPages.sort(compare);
    splitWantedPagesIntoDifferentLanguages(wantedPages);
};

function splitWantedPagesIntoDifferentLanguages(wantedPages) {
  var czechWantedPages = []; 
  var germanWantedPages = [];
  var spanishWantedPages = [];
  var frenchWantedPages = [];
  var italianWantedPages = [];
  var japaneseWantedPages = [];
  var dutchWantedPages = [];
  var polishWantedPages = [];
  var portugueseWantedPages = [];
  var russianWantedPages = [];
  var swedishWantedPages = [];
  var ukrainianWantedPages = [];
  var chineseWantedPages = [];
  var turkishWantedPages = [];
  var wantedFiles = [];
  var wantedTemplates = [];
  var otherWantedPages = [];

  for (var i = 0; i < wantedPages.length; i++) {
    switch (wantedPages[i].title.slice(-3)) {//"/cs", "/de", "/es", "/fr", "/it", "/ja", "/nl", "/pl", "/-br", "/ru", "/sv", "/uk", "/zh", "/tr"
      case "/cs": czechWantedPages.push(wantedPages[i]); break;
      case "/de": germanWantedPages.push(wantedPages[i]); break;
      case "/es": spanishWantedPages.push(wantedPages[i]); break;
      case "/fr": frenchWantedPages.push(wantedPages[i]); break;
      case "/it": italianWantedPages.push(wantedPages[i]); break;
      case "/ja": japaneseWantedPages.push(wantedPages[i]); break;
      case "/nl": dutchWantedPages.push(wantedPages[i]); break;
      case "/pl": polishWantedPages.push(wantedPages[i]); break;
      case "-br": portugueseWantedPages.push(wantedPages[i]); break;
      case "/ru": russianWantedPages.push(wantedPages[i]); break;
      case "/sv": swedishWantedPages.push(wantedPages[i]); break;
      case "/uk": ukrainianWantedPages.push(wantedPages[i]); break;
      case "/zh": chineseWantedPages.push(wantedPages[i]); break;
      case "/tr": turkishWantedPages.push(wantedPages[i]); break;
      default: if (wantedPages[i].title.slice(0, 5) == "File:") {wantedFiles.push(wantedPages[i])} else if (wantedPages[i].title.slice(0, 9) == "Template:") {wantedTemplates.push(wantedPages[i])} else {otherWantedPages.push(wantedPages[i])}; break;
    }
  }

  createWantedPagesPage("cs", czechWantedPages, "Czech");
  createWantedPagesPage("de", germanWantedPages, "German");
  createWantedPagesPage("es", spanishWantedPages, "Spanish");
  createWantedPagesPage("fr", frenchWantedPages, "French");
  createWantedPagesPage("it", italianWantedPages, "Italian");
  createWantedPagesPage("ja", japaneseWantedPages, "Japanese");
  createWantedPagesPage("nl", dutchWantedPages, "Dutch");
  createWantedPagesPage("pl", polishWantedPages, "Polish");
  createWantedPagesPage("pt-br", portugueseWantedPages, "Portuguese");
  createWantedPagesPage("ru", russianWantedPages, "Russian");
  createWantedPagesPage("sv", swedishWantedPages, "Swedish");
  createWantedPagesPage("uk", ukrainianWantedPages, "Ukrainian");
  createWantedPagesPage("zh", chineseWantedPages, "Chinese");
  createWantedPagesPage("tr", turkishWantedPages, "Turkish");

  createWantedPagesPage("file", wantedFiles, "Files");
  createWantedPagesPage("template", wantedTemplates, "Templates");
  createWantedPagesPage("other", otherWantedPages, "Other");
}

function createWantedPagesPage(location, wantedPages, language) {
  var formattedWantedPages = "Number of wanted pages in " + language + ": " + wantedPages.length + "\n{|class=wikitable\n!#\n!Page\n!Links to this page";

  for (var i = 0; i < wantedPages.length; i++) {
    formattedWantedPages = formattedWantedPages.concat("\n|-\n|" + (i + 1) + "\n|[https://wiki.factorio.com/index.php?title=" + encodeURI(wantedPages[i].title) + " " + wantedPages[i].title + "]\n|[https://wiki.factorio.com/index.php?title=Special:WhatLinksHere/" + encodeURI(wantedPages[i].title) + " " + wantedPages[i].value + "]");
  }

  formattedWantedPages = formattedWantedPages.concat("\n|}");

  createPage(wantedPagesListsLocation + "/" + location, formattedWantedPages, "(BOT) - Update the list of wanted pages for " + language + ".");
}

function performNullEdit(pageTitle, summary) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            section: 0,
            text: "",
            token: globalToken,
            summary: summary,
            bot: true
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           console.log("Performed null edit");
        },
        error: function( xhr ) {
            console.log("Failed to perform null edit");
        }
    });
}

function purgeWhatLinksHere(pageTitle) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: "json",
            action: 'query',
            list: "backlinks",
            bltitle: pageTitle,
            bllimit: 500
        },
        async: true,
        type: 'GET',
        success: function( data ) {
            console.log(data);
            for (var i = 0; i < data.query.backlinks.length; i++) {
                purgePage(data.query.backlinks[i].title);
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
            console.log("Failed purging");
        }
    });
}

function purgePage(pageTitle) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            action: 'purge',
            forcelinkupdate: true,
            titles: pageTitle,
            prop: "info"
        },
        async: true,
        type: 'GET',
        success: function( data ) {
            console.log("purging " + pageTitle);
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
            console.log("Failed purging");
        }
    });
}

function compare(a,b) {
  if (parseInt(a.value) > parseInt(b.value))
    return -1;
  if (parseInt(a.value) < parseInt(b.value))
    return 1;
  if (a.title < b.title)
    return -1;
  if (a.title > b.title)
    return 1;
  return 0;
}

function createPage(pageTitle, content, summary) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            token: globalToken,
            summary: summary,
            bot: true
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           console.log("created page");
        },
        error: function( xhr ) {
            console.log("failed to create page");
        }
    });
}

function getWantedPages() {
   var wantedPages = [];

   $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            list: 'querypage',
            qppage: 'Wantedpages',
            qplimit: '5000',
        },
        async: false,
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var results = data.query.querypage.results;
            for (var i = 0; i < results.length; i++) {
               var pageObject = new WantedPage(results[i].title, results[i].value);
               var alreadyInArray = false;
               for (var j = 0; j < wantedPages.length; j++) {
                 if (wantedPages[j].title == pageObject.title) {
                    alreadyInArray = true;
                 }
               }
               if (!alreadyInArray) {
                 wantedPages.push(pageObject);
               }
               if (pageObject.title == "Rocket defense/it") {
               }
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed. Category' );
        }
  });

$.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            list: 'querypage',
            qppage: 'Wantedpages',
            qplimit: '5000',
            qpoffset: '3000',
        },
        async: false,
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var results = data.query.querypage.results;
            for (var i = 0; i < results.length; i++) {
               var pageObject = new WantedPage(results[i].title, results[i].value);
               var alreadyInArray = false;
               for (var j = 0; j < wantedPages.length; j++) {
                 if (wantedPages[j].title == pageObject.title) {
                    alreadyInArray = true;
                 }
               }
               if (!alreadyInArray) {
                 wantedPages.push(pageObject);
               }
               if (pageObject.title == "Rocket defense/it") {
               }
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed. Category' );
        }
  });
  return wantedPages;
};

function WantedPage(pageTitle, pageValue) {
   this.title = pageTitle;
   this.value = pageValue;
}


/* OLD INFOBOX CONVERSION TOOLS */
/*function targetAllPagesInCategory(category) {
    var languageSuffixes = ["/fr", "/ru", "/de"]; //, "/cs", "/de", "/es", "/fr", "/it", "/nl", "/pl", "/pt-br", "/ru", "/sv", "/uk", "/zh", ""];
    for (var j = 0; j < languageSuffixes.length; j++) {
      $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            list: 'categorymembers',
            cmtitle: (category + languageSuffixes[j]),
            cmlimit: 500
        },
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var pages = data.query.categorymembers;
            for (var i = 0; i < pages.length; i++) {
                    //purgePage(pages[i].title);
                    extractPageInfo(pages[i].title, "9c28a1344a20bf189fda7d58339e518257f2dd9b+\\");
                
            }

            if ( data && data.query && data.query.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info + 'Category' );
            } else {
                //alert( 'Error: Unknown result from API. Category' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed. Category' );
        }
    });
  }
}

function extractPageInfo(pageTitle, token) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            titles: pageTitle,
            prop: 'revisions',
            rvprop: 'content'
        },
        async: false,
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var pages = data.query.pages;
            var revisions = pages[Object.keys(pages)[0]].revisions[0];
            var content = revisions[Object.keys(revisions)[2]]
            var title = pages[Object.keys(pages)[0]].title;
            createNewInfoboxPage(title, content, token);
            if ( data && data.query && data.query.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    });
}

function createNewInfoboxPage(page, contentOfMainPage, token) {
    var infoboxText = getInfoboxFromFullPageContent(contentOfMainPage);

    var infoboxPageTitle = page.replace(/\/(de|fr|nl|it|es|ru|pt\-br|cs|pl|sv|uk|zh)/g, function(piece) {return "";}).concat("/infobox");
    var oldPageRevisedText = getOldPageRevisedText(page, contentOfMainPage, infoboxPageTitle);	
    removeInfoboxFromMain(page, oldPageRevisedText, token);

    if (infoboxText != null) {
      if (/\/(de|fr|nl|it|es|ru|pt\-br|cs|pl|sv|uk|zh)/g.test(page)) {
        return;
      }
      var newPageTitle = page.concat("/infobox");
      var convertedInfoboxText = convertInfobox(infoboxText, token);
      createPage(newPageTitle, convertedInfoboxText, token, page, contentOfMainPage);
    }
}

function getOldPageRevisedText(pageTitle, content, infoboxPageTitle) {
    content = content.replace(/{{\bCombat\b(\s+(\||{).+)+\s}}/gi, function (piece) {
        return "{{:" + infoboxPageTitle + "}}";
    });
    return content;
}

function removeInfoboxFromMain(pageTitle, content, token) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            bot: true,
            token: token,
            summary: "(BOT) - Replaced old infobox with a link to the /infobox subpage"
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
            if ( data && data.edit && data.edit.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    })
};

function getInfoboxFromFullPageContent(contentOfPage) {
    var matches = contentOfPage.match(/{{\bCombat\b(\s+\|.+)+\s}}/gi);
if (matches != null && matches.length > 0) {
 infoboxText = matches[0];
} else {
 infoboxText = null;
}
    return infoboxText;
}

function convertInfobox(text) {
    text = text.replace(/{{(\w+)/g, function (piece, $1) {
        var returnText = "{{Infobox\n| category = ";

        $1 = $1.toLowerCase();

        switch ($1) {
            case "item":
                returnText = returnText.concat("Items");
                break;
            case "machinery":
                returnText = returnText.concat("Machinery");
                break;
            case "combat":
                returnText = returnText.concat("Combat");
                break;
            case "technology":
                returnText = returnText.concat("Technology");
        }

        switch ($1) {
            case "machinery":
                returnText = returnText.concat("\n| category-name = Machine");
                break;
            case "item":
                returnText = returnText.concat("\n| category-name = Item");
                break;
        }

        return returnText;
    });

    text = text.replace("stack_size", "stack-size");
    text = text.replace("poweroutput", "power-output");
    text = text.replace("input", "recipe");
    text = text.replace("raw", "total-raw");
    text = text.replace("technologies", "required-technologies");
    text = text.replace("costmultiplier", "cost-multiplier");
    text = text.replace("requirements", "required-technologies");
    text = text.replace("walkingspeed", "walking-speed");
    text = text.replace("storagesize", "storage-size");
    text = text.replace("gridsize", "grid-size");
    text = text.replace("shootingspeed", "shooting-speed");
    text = text.replace("damagebonus", "damage-bonus");
    text = text.replace("clustersize", "cluster-size");
    text = text.replace("aoesize", "area-of-effect-size");
    text = text.replace("magazinesize", "magazine-size");
    text = text.replace("recharge", "robot-recharge-rate");
    text = text.replace("rechargebuffer", "internal-buffer-recharge-rate");
    text = text.replace("wirereach", "wire-reach");
    text = text.replace("craftingspeed", "crafting-speed");
    text = text.replace("smeltingspeed", "smelting-speed");
    text = text.replace("miningpower", "mining-power");
    text = text.replace("miningspeed", "mining-speed");
    text = text.replace("miningarea", "mining-area");
    text = text.replace("supplyarea", "supply-area");
    text = text.replace("constructionarea", "construction-area");
    text = text.replace("lifetime", "lifespan");
    text = text.replace("inventorysizebonus", "inventory-size-bonus");
    text = text.replace("gridsize", "grid-size");
    text = text.replace("boosttechs", "boosting-technologies");
    text = text.replace("allowstech", "allows");
    text = text.replace("storage", "storage-size");
    text = text.replace(/\|\s*\brecipe\b\s*=\s*(.+)\n\|\s*\boutput\b\s*=\s*(.+)/g, function (piece, $1, $2) {
        return "| recipe = " + $1 + " = " + $2;
    });

    text = text.concat("<noinclude>[[Category:Infobox page]]</noinclude>");

    return text;
}

function createPage(pageTitle, content, token, page, contentOfMainPage) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            bot: true,
            createonly: true,
            token: token,
            summary: "(BOT) - Created infobox sub page for " + page
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           
            if ( data && data.edit && data.edit.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    });
}*/
/* END OF OLD INFOBOX CONVERSION TOOL */