// ==UserScript==
// @name           estimate next page url
// @namespace      fuba.s7.xrea.com
// @include        *
// ==/UserScript==

(function () {

var lossless_split = function (opt) {
	var array = opt.array;
	var seps = opt.sep;
	
	if (array.length == 'undefined') return;
	if (seps.length == 'undefined') return;
	
	for (var k=0;k<seps.length;k++) {
		var sep = seps[k];
		var splitted = new Array;
		for (var i=0;i<array.length;i++) {
			var s = array[i].split(sep);
			
			var s_restored = new Array;
			for (var j=0;j<s.length;j++) {
				s_restored.push(s[j]);
				if (j < s.length-1) s_restored.push(sep);
			}
			
			splitted = splitted.concat(s_restored);
		}
		array = splitted;
	}
	
	return array;
};


var SplittedURL = function (url) {
	var a = lossless_split({
		array: [url],
		sep: ['/', '?', '=', ';', '.', '&', ',', '-']}
	);
	
	return {
		array: a,
		diff: function (url_obj) {
			var diff = new Array;
			for (var i=0;i<url_obj.array.length;i++) {
				if (this.array[i] != url_obj.array[i]) {
					diff.push(i);
				}
			}
			return diff;
		},
		url: function () {
			return this.array.join('');
		}
	};
};


var previous_url = GM_getValue('previous_page');
if (previous_url == 'undefined') return;

var current_url = location.href;
GM_setValue('previous_page', current_url);

var curr = new SplittedURL(current_url);
var prev = new SplittedURL(previous_url);

var diff = curr.diff(prev);

if (diff.length == 1) {
	var index = diff[0];
	var progress = curr.array[index] - prev.array[index];
	var next_num = progress + parseInt(curr.array[index]);
	var next = new SplittedURL(current_url);
	next.array[index] = next_num;
	
	var nextlink = document.createElement('A');
	nextlink.innerHTML = 'Older »';
	nextlink.href = next.url();
	document.body.appendChild(nextlink);
}

})();

