﻿// ==UserScript==
// @name        estseek autopager
// @namespace   http://ma.la/
// @include     http://athlon64.fsij.org:8080/wikipedia/estseek.cgi*
// @version     1.0.0
// ==/UserScript==
(function(){
	var enable = false;
	var request_url;
	var requested = "";
	var loading;
	var root = document.documentElement;
	var init = function(){
		var xpath_result = document.evaluate(
			'//a[@class="navi"][text()="NEXT"][last()]',
			 document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null
		);
		if(xpath_result.singleNodeValue){
			request_url = xpath_result.singleNodeValue.href;
		}else{
			return
		}
		document.body.addEventListener("dblclick", function(){
			enable = !enable;
			window.status = (enable) ? "Enabled" : "Disabled";
		},true);
		loading = document.createElement("div");
		loading.innerHTML = "Now Loading";
		with(loading.style){
			position = "fixed";
			top = "4px";
			right = "4px";
			padding = "0.3em";
			background = "#E00";
			color = "#FFF";
			visibility = "hidden";
		};
		document.body.appendChild(loading);
		watch_scroll();
	}
	var gid = function(id){
		return document.getElementById(id);
	};
	var fadeout = function(el,end,f){
		var cf = 0;
		var calc = f || function(pos){
			return (-Math.cos(pos * Math.PI) / 2) + 0.5;
		};
		(function(){
			var self = arguments.callee;
			var pos = cf / end;
			el.style.MozOpacity = 1 - calc(pos);
			if(cf >= end){
				el.style.MozOpacity = 0;
				el.style.visibility = "hidden";
			}else{
				cf++;
				setTimeout(self, 50)
			}
		})();
	}
	var busy = function(sw){
		if(sw){
			loading.style.visibility = "visible";
		}else{
			fadeout(loading,20)
		}
	}
	var Remain = {
		valueOf : function(){
			var total = root.scrollHeight - root.clientHeight;
			var sc = window.scrollY;
			// window.status = [total,sc];
			return total - sc;
		}
	};
	var watch_scroll = function(){
		var self = arguments.callee;
		if(enable && Remain < 500){
			do_request()
		}
		setTimeout(self,100);
	};
	var do_request = function(){
		if(requested == request_url){
			return
		};
		requested = request_url;
		busy(true);
		GM_xmlhttpRequest({
			method: 'get',
			url: request_url,
			onload: function(detail){
				var wp = new XPCNativeWrapper(window, "DOMParser()");
				var parser = new wp.DOMParser();
				var res = parser.parseFromString(detail.responseText, "text/xml");
				gid("estresult").parentNode.insertBefore(
					res.getElementById("estresult").cloneNode(true),
					gid("estresult").nextSibling
				);
				var links = res.getElementsByTagName("a");
				var item;
				for(var i=0;item = links[i];i++){
					if(item.className == "navi" && item.text == "NEXT"){
						request_url = item.href;
						break;
					}
				};
				busy(false);
				return;
			}
		});	
	};
	init();
})();