// ==UserScript==
// @name           Vector Direct Download
// @namespace      com.appspot.final.gm.vector
// @include        http://www.vector.co.jp/*
// ==/UserScript==

(function(){
	var get_download_url = function(){
		if(0 == location.href.indexOf("http://www.vector.co.jp/download/file/")){
			var metas = document.getElementsByTagName("meta");
			for(var i = 0; i < metas.length; i++){
				var meta = metas[i];
				var equiv = meta.getAttribute("HTTP-EQUIV");
				if(!equiv || "REFRESH" != equiv.toUpperCase()){ continue; }
				var content = meta.getAttribute("content");
				if(!content){ continue; }
				var pos = content.indexOf("=");
				if(pos == -1){ continue; }
				return content.substring(pos + 1);
			}
		}
		return null;
	};
	if(0 == location.href.indexOf("http://www.vector.co.jp/download/file/")){
		document.body.style.paddingTop = "5em";
		document.body.style.textAlign = "center";
		document.body.style.fontSize = "200%";
		document.body.innerHTML = "<a href='" + get_download_url() + "'>Download</a>";
		return;
	}
	if(0 == location.href.indexOf("http://www.vector.co.jp/soft/")){
		var prefix = "http://www.vector.co.jp/soft/dl/";
		var pos = location.href.indexOf(prefix);
		if(pos == -1){
			prefix = "http://www.vector.co.jp/soft/";
			pos = location.href.indexOf(prefix);
		}
		var suffix = location.href.substring(pos + prefix.length);
		var pre_url = "http://www.vector.co.jp/soft/dl/" + suffix;
		var xhr = new XMLHttpRequest();
		xhr.open("get", pre_url, true);
		xhr.onreadystatechange = function(){
			if(4 != xhr.readyState){ return; }
			var html = xhr.responseText;
			var re = /href\s*=\s*["'](\/download\/file\/[^"']+?)["']/im;
			var ar = html.match(re);
			if(!ar || ar.length != 2){ return;}
			var dl_url = "http://www.vector.co.jp" + ar[1];
			xhr = new XMLHttpRequest();
			xhr.open("get", dl_url, true);
			xhr.onreadystatechange = function(){
				if(4 != xhr.readyState){ return; }
				var html = xhr.responseText;
				var re = /<META\s+HTTP\-EQUIV\s*=\s*"Refresh"\s+CONTENT\s*=\s*"\d+;URL=(.+?)"/im;
				var ar = html.match(re);
				if(!ar || ar.length != 2){ return;}
				var container = document.getElementById("download");
				if(!container){
					container = document.getElementById("detail");
				}
				if(!container){ return; }
				var a = document.createElement("a");
				a.setAttribute("href", ar[1]);
				a.style.display = "block";
				a.style.fontSize = "200%";
				a.style.paddingLeft = "5em";
				a.style.paddingBottom = "1em";
				a.innerHTML = "Direct Download";
				container.insertBefore(a, container.firstChild);
			}
			xhr.send(null);
		};
		xhr.send(null);
	}
})();
