MediaWiki:Common.js: Difference between revisions

From Official Factorio Wiki
Jump to navigation Jump to search
No edit summary
(Collapsible prototype tree with indentation guides)
 
(397 intermediate revisions by 5 users not shown)
Line 1: Line 1:
/* Any JavaScript here will be loaded for all users on every page load. */
/* Any JavaScript here will be loaded for all users on every page load. */
/*$(".navbox").css("background", "red");*/


//Spoiler template JavaScript
var apiUrl = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + "/api.php"
 
/* Script in here will be executed when the page is "ready" */
$(document).ready(getNumberOfActiveUsers);
 
/* show correct number of active users on the main page */
 
function getNumberOfActiveUsers() {
if (document.getElementById("active-users")) {
$.ajax({
url: apiUrl,
data: {
format: 'json',
action: 'query',
list: 'allusers',
aulimit: 500,
auactiveusers: true
},
dataType: 'json',
type: 'GET',
success: function(data) {
document.getElementById("active-users").innerHTML = data.query.allusers.length.toString();
},
error: function(xhr) {
console.log( 'Error: Request failed.' );
}
});
}
};
 
/* Collapsible list on [[Prototype definitions]] */
 
$(".prototype-tree li").each(function (index, element) {
  if ( $( element ).children("ul").length > 0 ) {
    $( element ).addClass("prototype-tree-parent");
  };
});
 
$(".prototype-tree li.prototype-tree-parent").on("click", function(event) {
// only collapse if I clicked a li or the direct child of a li that is not another list or a link
  if ( $( event.currentTarget ).children("ul").length > 0 && $( event.target ).get(0).tagName != "UL" && $( event.target ).get(0).tagName != "A" && ($( event.target ).hasClass("prototype-tree-parent") || $( event.target ).parent().hasClass("prototype-tree-parent")) ) {
    $( event.currentTarget ).children("ul")[0].classList.toggle("hidden");
    $( event.currentTarget ).toggleClass("prototype-tree-parent-collapsed");
    return false; // prevents further event bubbling
  }
});
 
/* Evolution calc */
 
//values are in the form [evolution, weight]
const biterSpawner = [
["Small Biter",    [[0.0, 0.3], [0.6, 0.0]]],
["Medium Biter",  [[0.2, 0.0], [0.6, 0.3], [0.7, 0.1]]],
["Big Biter",      [[0.5, 0.0], [1.0, 0.4]]],
["Behemoth Biter", [[0.9, 0.0], [1.0, 0.3]]]
];
const spitterSpawner = [
["Small Biter",      [[0.0, 0.3], [0.35, 0.0]]],
["Small Spitter",    [[0.25, 0.0], [0.5, 0.3], [0.7, 0.0]]],
["Medium Spitter",  [[0.4, 0.0], [0.7, 0.3], [0.9, 0.1]]],
["Big Spitter",      [[0.5, 0.0], [1.0, 0.4]]],
["Behemoth Spitter", [[0.9, 0.0], [1.0, 0.3]]]
];
 
//calculates the interpolated value
function lerp(low, high, pos) {
const s = high[0] - low[0];
const l = (pos - low[0]) / s;
return (low[1] * (1-l)) + (high[1] * l);
};
 
//gets the weight list
function getValues(map, evo) {
var result = {};
var sum = 0;
map.forEach(function(data) {
const list = data[1];
var low = list[0];
var high = list[list.length-1];
list.forEach(function(val) {
if(val[0] <= evo && val[0] >  low[0])  low = val;
if(val[0] >= evo && val[0] < high[0]) high = val;
});
var val = null;
if(evo <= low[0]) val = low[1];
else if(evo >= high[0]) val = high[1];
else val = lerp(low, high, evo);
sum += val;
result[data[0]] = val;
});
Object.keys(result).forEach(function(data, index) {
result[data] = result[data] / sum;
});
return result;
};
 
function calcEvo() {
const evo = document.getElementById("evoInput").value;
genTable(getValues(biterSpawner, evo), document.getElementById("evoOutputBiter"), "Biter's Nest");
genTable(getValues(spitterSpawner, evo), document.getElementById("evoOutputSpitter"), "Spitter's Nest");
};
 
function percentile(value) {
return (value*100).toFixed(2) + "%";
};
 
function genTable(data, tableElem, title) {
var html = '<tr><th>'+title+'</th><th>Chance</th>';
Object.keys(data).forEach(function(value) {
html += '<tr><td>'+value+'</td><td>'+percentile(data[value])+'</td>';
});
tableElem.innerHTML = html;
};
 
window.onload = function() {
var elem = document.getElementById("evoChecker");
if(elem != null) {
elem.innerHTML =
'Alternatively, enter an evolution factor below to see the chances.<br>' +
'<input style="margin-bottom:10px" type="number" id="evoInput" min=0 max=1 step=0.01 placeholder="Evolution" onchange="calcEvo()"></input><br>' +
'<table style="float:left;margin-right:10px" class="wikitable" id="evoOutputBiter"></table>' +
'<table class="wikitable" id="evoOutputSpitter"></table>';
calcEvo();
}
};
 
/* Template:Inventory tooltips */
 
var lastTouchTime = 0;
document.addEventListener('touchstart', updateLastTouchTime, true);
function updateLastTouchTime() {
  lastTouchTime = new Date();
}
 
$(".tab-head").mousemove(function(e) {
  if (e.buttons > 0) return;
  if (new Date() - lastTouchTime < 500) return;
  var countCssRules = document.styleSheets[0].cssRules.length;
  var newRule = '.tab-head:hover:after{display: block; left: ' + (e.offsetX + 20) + 'px; top: ' + (e.offsetY + 20) + 'px;}';
  document.styleSheets[0].insertRule(newRule, countCssRules);
});
 
$(".tab .factorio-icon").mousemove(function(e) {
  if (e.buttons > 0) return;
  if (new Date() - lastTouchTime < 500) return;
  var countCssRules = document.styleSheets[0].cssRules.length;
  $(e.currentTarget).children("a").attr("title", "");
  var text = $(e.currentTarget).children("a").children("img").attr("alt");
  var newRule = '.tab .factorio-icon:hover:after{display: block; ' + "content: '" + text + "'}";
  document.styleSheets[0].insertRule(newRule, countCssRules);
});
 
/* Template:BlueprintString */
 
$(".bps-box").click(function(event) {
var copyTarget = document.createElement("input");
copyTarget.setAttribute("value", $( event.target ).children("p").html());
document.body.appendChild(copyTarget);
copyTarget.select();
document.execCommand("copy");
document.body.removeChild(copyTarget);
});
 
/* Template:Inventory */
 
$(".tab-head-1").click(function() {
$(".tab-head").removeClass("tab-head-active");
$(this).addClass("tab-head-active");
$(".tab").hide();
$(".tab-1").show();
});
 
$(".tab-head-2").click(function() {
$(".tab-head").removeClass("tab-head-active");
$(this).addClass("tab-head-active");
$(".tab").hide();
$(".tab-2").show();
});
 
$(".tab-head-3").click(function() {
$(".tab-head").removeClass("tab-head-active");
$(this).addClass("tab-head-active");
$(".tab").hide();
$(".tab-3").show();
});
 
$(".tab-head-4").click(function() {
$(".tab-head").removeClass("tab-head-active");
$(this).addClass("tab-head-active");
$(".tab").hide();
$(".tab-4").show();
});
 
//*** 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
$(".spoiler-container .button").click(function() {
$(".spoiler-container .button").click(function() {
  $(this).siblings(".text").toggle("slow");
$(this).siblings(".text").toggle("slow");
});
});


$("#start-edit-test").click(function(){
//* General/generic functions *//
  extractPageInfo("Smart Chest");
 
});
/* User is bot if userGroup.some(isBot) == true */
 
var userGroup = "";
 
function getUserGroup() {
$.ajax({
url: apiUrl,
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";
}
 
/* Get token of this session */
 
var globalToken;


function extractPageInfo(pageTitle) {
function getToken() {
     $.ajax({
     $.ajax({
         url: 'https://wiki.factorio.com/api.php',
         url: apiUrl,
         data: {
         data: {
             format: 'json',
             format: 'json',
             action: 'query',
             action: 'query',
             titles: pageTitle,
             meta: 'tokens',
            prop: 'revisions',
             bot: true
             rvprop: 'content'
         },
         },
        async: false,
         dataType: 'json',
         dataType: 'json',
         type: 'GET',
         type: 'POST',
         success: function( data ) {
         success: function( data ) {
            console.log(data);
          globalToken = data.query.tokens.csrftoken;
            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);
            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 ) {
         error: function( xhr ) {
             alert( 'Error: Request failed.' );
             console.log("Failed to get token.");
         }
         }
     });
     });
}
}


function createNewInfoboxPage(page, contentOfMainPage) {
    var infoboxText = getInfoboxFromFullPageContent(contentOfMainPage);
    console.log(infoboxText);
    var newPageTitle = page + "/infobox";
    var convertedInfoboxText = convertInfobox(infoboxTest);
    console.log(convertedInfoboxText);
    createPage(newPageTitle, convertedInfoboxText);
}


var getInfoboxFromFullPageContent(contentOfPage) {
function genericEditPage(title, content, summary) {
    var infoboxText = contentOfPage.replace(/..\bMachinery\b(\s+\|.+)+\s}}/g, function (piece) {
$.ajax({
        return piece;
url: apiUrl,
data: {
format: 'json',
action: 'edit',
title: title,
text: content,
token: globalToken,
summary: summary,
bot: true,
nocreate: true
},
dataType: 'json',
type: 'POST',
success: function( data ) {
console.log("Edited " + title);
},
error: function( xhr ) {
alert("Failed to edit " + title);
}
});
};
 
 
function createPage(pageTitle, content, summary) {
    $.ajax({
        url: apiUrl,
        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: " + pageTitle);
        },
        error: function( xhr ) {
console.log("Failed to create page");
        }
     });
     });
    return infoboxText;
}
}


function convertInfobox(text) {
function getBacklinks(page) {
    text = text.replace(/{{(\w+)/g, function (piece, $1) {
var backlinks = [];
        var returnText = "{{Infobox\n| category = ";
$.ajax({
url: apiUrl,
data: {
format: 'json',
action: 'query',
list: 'backlinks',
bltitle: page,
bllimit: 1000,
},
async: false,
type: 'GET',
success: function( data ) {
backlinks = data.query.backlinks;
},
error: function( xhr ) {
alert( 'Error: Backlinks request failed.' );
}
});
return backlinks;
};


        $1 = $1.toLowerCase();
function getFileUsage(file) {
var imageusage = [];
$.ajax({
url: apiUrl,
data: {
format: 'json',
action: 'query',
list: 'imageusage',
iutitle: file,
iulimit: 1000
},
async: false,
type: 'GET',
success: function( data ) {
imageusage = data.query.imageusage;
},
error: function( xhr ) {
alert( 'Error: Imageusage request failed.' );
}
});
return imageusage;
};


        switch ($1) {
function performNullEdit(pageTitle, summary) {
             case "item":
    $.ajax({
                returnText = returnText.concat("Items");
        url: apiUrl,
                break;
        data: {
             case "machinery":
             format: 'json',
                returnText = returnText.concat("Machinery");
            action: 'edit',
                break;
            title: pageTitle,
             case "combat":
             section: 0,
                returnText = returnText.concat("Combat");
            text: "",
                break;
            token: globalToken,
            case "technology":
            summary: summary,
                returnText = returnText.concat("Technology");
             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");
         }
         }
    });
}


        switch ($1) {
function purgeWhatLinksHere(pageTitle) {
             case "machinery":
    $.ajax({
                returnText = returnText.concat("\n| category-name = Machine");
        url: apiUrl,
                 break;
        data: {
             case "item":
             format: "json",
                returnText = returnText.concat("\n| category-name = Item");
            action: 'query',
                break;
            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");
         }
         }
        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("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) {
function purgePage(pageTitle) {
     $.ajax({
     $.ajax({
         url: 'https://wiki.factorio.com/api.php',
         url: apiUrl,
         data: {
         data: {
            format: 'json',
             action: 'purge',
             action: 'edit',
             forcelinkupdate: true,
             text: content,
             titles: pageTitle,
             titles: pageTitle,
             bot: true,
             prop: "info"
            token: '159d15f2706c7140ac229e91474d142e57ed8df4+\\'
         },
         },
         dataType: 'json',
         async: true,
         type: 'GET',
         type: 'GET',
         success: function( data ) {
         success: function( data ) {
             if ( data && data.edit && data.edit.result == 'Success' ) {
             console.log("purging " + pageTitle);
                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 ) {
         error: function( xhr ) {
             alert( 'Error: Request failed.' );
             //alert( 'Error: Request failed.' );
            console.log("Failed purging");
         }
         }
     });
     });
}
}

Latest revision as of 12:24, 20 February 2020

/* Any JavaScript here will be loaded for all users on every page load. */

var apiUrl = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + "/api.php"

/* Script in here will be executed when the page is "ready" */
$(document).ready(getNumberOfActiveUsers);

/* show correct number of active users on the main page */

function getNumberOfActiveUsers() {
	if (document.getElementById("active-users")) {
		$.ajax({
			url: apiUrl,
			data: {
				format: 'json',
				action: 'query',
				list: 'allusers',
				aulimit: 500,
				auactiveusers: true
			},
			dataType: 'json',
			type: 'GET',
			success: function(data) {
				document.getElementById("active-users").innerHTML = data.query.allusers.length.toString();
			},
			error: function(xhr) {
				console.log( 'Error: Request failed.' );
			}
		});
	}
};

/* Collapsible list on [[Prototype definitions]] */

$(".prototype-tree li").each(function (index, element) {
  if ( $( element ).children("ul").length > 0 ) {
    $( element ).addClass("prototype-tree-parent");
  };
});

$(".prototype-tree li.prototype-tree-parent").on("click", function(event) {
 // only collapse if I clicked a li or the direct child of a li that is not another list or a link
  if ( $( event.currentTarget ).children("ul").length > 0 && $( event.target ).get(0).tagName != "UL" && $( event.target ).get(0).tagName != "A" && ($( event.target ).hasClass("prototype-tree-parent") || $( event.target ).parent().hasClass("prototype-tree-parent")) ) {
    $( event.currentTarget ).children("ul")[0].classList.toggle("hidden");
    $( event.currentTarget ).toggleClass("prototype-tree-parent-collapsed");
    return false; // prevents further event bubbling
  }
});

/* Evolution calc */

//values are in the form [evolution, weight]
const biterSpawner = [
	["Small Biter",    [[0.0, 0.3], [0.6, 0.0]]],
	["Medium Biter",   [[0.2, 0.0], [0.6, 0.3], [0.7, 0.1]]],
	["Big Biter",      [[0.5, 0.0], [1.0, 0.4]]],
	["Behemoth Biter", [[0.9, 0.0], [1.0, 0.3]]]
];
const spitterSpawner = [
	["Small Biter",      [[0.0, 0.3], [0.35, 0.0]]],
	["Small Spitter",    [[0.25, 0.0], [0.5, 0.3], [0.7, 0.0]]],
	["Medium Spitter",   [[0.4, 0.0], [0.7, 0.3], [0.9, 0.1]]],
	["Big Spitter",      [[0.5, 0.0], [1.0, 0.4]]],
	["Behemoth Spitter", [[0.9, 0.0], [1.0, 0.3]]]
];

//calculates the interpolated value
function lerp(low, high, pos) {
	const s = high[0] - low[0];
	const l = (pos - low[0]) / s;
	return (low[1] * (1-l)) + (high[1] * l);
};

//gets the weight list
function getValues(map, evo) {
	var result = {};
	var sum = 0;
	map.forEach(function(data) {
		const list = data[1];
		var low = list[0];
		var high = list[list.length-1];
		list.forEach(function(val) {
			if(val[0] <= evo && val[0] >  low[0])  low = val;
			if(val[0] >= evo && val[0] < high[0]) high = val;
		});
		var val = null;
		if(evo <= low[0]) val = low[1];
		else if(evo >= high[0]) val = high[1];
		else val = lerp(low, high, evo);
		sum += val;
		result[data[0]] = val;
	});
	Object.keys(result).forEach(function(data, index) {
		result[data] = result[data] / sum;
	});
	return result;
};

function calcEvo() {
	const evo = document.getElementById("evoInput").value;
	genTable(getValues(biterSpawner, evo), document.getElementById("evoOutputBiter"), "Biter's Nest");
	genTable(getValues(spitterSpawner, evo), document.getElementById("evoOutputSpitter"), "Spitter's Nest");
};

function percentile(value) {
	return (value*100).toFixed(2) + "%";
};

function genTable(data, tableElem, title) {
	var html = '<tr><th>'+title+'</th><th>Chance</th>';
	Object.keys(data).forEach(function(value) {
		html += '<tr><td>'+value+'</td><td>'+percentile(data[value])+'</td>';
	});
	tableElem.innerHTML = html;
};

window.onload = function() {
	var elem = document.getElementById("evoChecker");
	if(elem != null) {
		elem.innerHTML =
		'Alternatively, enter an evolution factor below to see the chances.<br>' +
		'<input style="margin-bottom:10px" type="number" id="evoInput" min=0 max=1 step=0.01 placeholder="Evolution" onchange="calcEvo()"></input><br>' +
		'<table style="float:left;margin-right:10px" class="wikitable" id="evoOutputBiter"></table>' +
		'<table class="wikitable" id="evoOutputSpitter"></table>';
		calcEvo();
	}
};

/* Template:Inventory tooltips */

var lastTouchTime = 0;
document.addEventListener('touchstart', updateLastTouchTime, true);
function updateLastTouchTime() {
  lastTouchTime = new Date();
}

$(".tab-head").mousemove(function(e) {
  if (e.buttons > 0) return;
  if (new Date() - lastTouchTime < 500) return;
  var countCssRules = document.styleSheets[0].cssRules.length;
  var newRule = '.tab-head:hover:after{display: block; left: ' + (e.offsetX + 20) + 'px; top: ' + (e.offsetY + 20) + 'px;}';
  document.styleSheets[0].insertRule(newRule, countCssRules);
});

$(".tab .factorio-icon").mousemove(function(e) {
  if (e.buttons > 0) return;
  if (new Date() - lastTouchTime < 500) return;
  var countCssRules = document.styleSheets[0].cssRules.length;
  $(e.currentTarget).children("a").attr("title", "");
  var text = $(e.currentTarget).children("a").children("img").attr("alt");
  var newRule = '.tab .factorio-icon:hover:after{display: block; ' + "content: '" + text + "'}";
  document.styleSheets[0].insertRule(newRule, countCssRules);
});

/* Template:BlueprintString */

$(".bps-box").click(function(event) {
	var copyTarget = document.createElement("input");
	copyTarget.setAttribute("value", $( event.target ).children("p").html());
	document.body.appendChild(copyTarget);
	copyTarget.select();
	document.execCommand("copy");
	document.body.removeChild(copyTarget);
});

/* Template:Inventory */

$(".tab-head-1").click(function() {
	$(".tab-head").removeClass("tab-head-active");
	$(this).addClass("tab-head-active");
	$(".tab").hide();
	$(".tab-1").show();
});

$(".tab-head-2").click(function() {
	$(".tab-head").removeClass("tab-head-active");
	$(this).addClass("tab-head-active");
	$(".tab").hide();
	$(".tab-2").show();
});

$(".tab-head-3").click(function() {
	$(".tab-head").removeClass("tab-head-active");
	$(this).addClass("tab-head-active");
	$(".tab").hide();
	$(".tab-3").show();
});

$(".tab-head-4").click(function() {
	$(".tab-head").removeClass("tab-head-active");
	$(this).addClass("tab-head-active");
	$(".tab").hide();
	$(".tab-4").show();
});

//*** 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
$(".spoiler-container .button").click(function() {
	$(this).siblings(".text").toggle("slow");
});

//* General/generic functions *//

/* User is bot if userGroup.some(isBot) == true */

var userGroup = "";

function getUserGroup() {
	$.ajax({
		url: apiUrl,
		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";
}

/* Get token of this session */

var globalToken;

function getToken() {
    $.ajax({
        url: apiUrl,
        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 get token.");
        }
    });
}


function genericEditPage(title, content, summary) {
	$.ajax({
		url: apiUrl,
		data: {
			format: 'json',
			action: 'edit',
			title: title,
			text: content,
			token: globalToken,
			summary: summary,
			bot: true,
			nocreate: true
		},
		dataType: 'json',
		type: 'POST',
		success: function( data ) {
			console.log("Edited " + title);
		},
		error: function( xhr ) {
			alert("Failed to edit " + title);
		}
	});
};


function createPage(pageTitle, content, summary) {
    $.ajax({
        url: apiUrl,
        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: " + pageTitle);
        },
        error: function( xhr ) {
			console.log("Failed to create page");
        }
    });
}

function getBacklinks(page) {
	var backlinks = [];
	$.ajax({
		url: apiUrl,
		data: {
			format: 'json',
			action: 'query',
			list: 'backlinks',
			bltitle: page,
			bllimit: 1000,
		},
		async: false,
		type: 'GET',
		success: function( data ) {
			backlinks = data.query.backlinks;
		},
		error: function( xhr ) {
			alert( 'Error: Backlinks request failed.' );
		}
	});
	return backlinks;
};

function getFileUsage(file) {
	var imageusage = [];
	$.ajax({
		url: apiUrl,
		data: {
			format: 'json',
			action: 'query',
			list: 'imageusage',
			iutitle: file,
			iulimit: 1000
		},
		async: false,
		type: 'GET',
		success: function( data ) {
			imageusage = data.query.imageusage;
		},
		error: function( xhr ) {
			alert( 'Error: Imageusage request failed.' );
		}
	});
	return imageusage;
};

function performNullEdit(pageTitle, summary) {
    $.ajax({
        url: apiUrl,
        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: apiUrl,
        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: apiUrl,
        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");
        }
    });
}