bobjoephil / MPV Links on Page Number

// ==UserScript==
// @name        MPV Links on Page Number
// @namespace   bobjoephil
// @description Leaves image as link to default type, changes number below to link to MPV, if available
// @include     *g.e-hentai.org/g/*
// @include     *exhentai.org/g/*
// @version     2
// @grant       none
// ==/UserScript==

window.addEventListener("load", function (e) {onxxload();}, false);
window.addEventListener("AutoPagerAfterInsert", function (e) {processLinks();}, false);

var MPVLink;
var MPVEnabled;

function onxxload() {
	var page = document.getElementsByTagName("html")[0].innerHTML;
	MPVEnabled = page.search("Multi-Page Viewer");
	if (MPVEnabled == -1)
		return;
	
	var links = document.getElementsByTagName("a");
	for (var i=0; i<links.length; i++) {
		if (links.item(i).getAttribute("href").contains("/mpv")) {
			MPVLink = links.item(i).getAttribute("href");
			break;
		}
	}
	
	processLinks();
}

function processLinks() {
	if (MPVEnabled == -1) {
		return;
	}
	var thumbs = document.getElementsByClassName("gdtl");
	for (var i=0; i<thumbs.length; i++) {
		var thumb = thumbs.item(i);
		if (!thumb.getAttribute("id")) {
			var link = thumb.children.item(0);
			var pageNum = link.getAttribute("href").split("-").pop();
			var mainLink = link.innerHTML.split("<br>")[0];
			var pageText = link.children.item(0).getAttribute("alt");
			thumbs.item(i).children.item(0).innerHTML = mainLink + "<br><a href=\"" + MPVLink + "#page" + pageNum + "\">" + pageText + "</a>"; 
			thumbs.item(i).setAttribute("id", pageNum);
		}
	}
}