// ==UserScript==
// @name           getreplytweet
// @namespace      http://blog.gifumaster.com
// @include        http://twitter.com/*
// ==/UserScript==
(function() {
	var d = document;
	var url;
	function getElement(xpath) {
		var result = d.evaluate(xpath, d, null, 7, null);
		return result;
	}
    function getReply(){
		var target = this;
		var url = this.getAttribute("href");

		from = target.innerHTML.match(/(.+)宛/);
		getReplyURL(url,target.parentNode.parentNode,from[1]);
		this.removeEventListener('mouseover',getReply,true);
	}

    function getReplyURL(url,target,name){

		var htmlObj   = document.createElement("div");
		var styleAttr = document.createAttribute("style");

		htmlObj.innerHTML = '<img alt="Loader" src="http://a0.twimg.com/a/1250809294/images/loader.gif" />';
		styleAttr.value    = "width:90%;border:1px solid #cccccc;background-color:#DDEEFF;padding:5px;font-size:10px;color:#999999;";
		htmlObj.setAttributeNode(styleAttr);

		target.parentNode.appendChild(htmlObj);

		GM_xmlhttpRequest({
			method : 'GET',
			url : url,
			onload : function(res){
				data = res.responseText;
				match = data.match(/<span class="entry-content">([\n\r]|.)+?<\/span>/);
				if(match == null){
					result ="非公開ユーザーです。";
				}else{
					result = match[0];
				}
				
				htmlObj.innerHTML = '<a href="'+ url +'">' + name +'</a>　<span>'+ result +'</span>';

				replyScr  = data.match(/<a href="[^"]+">[^<]+宛<\/a>/);
				if(replyScr != null){
					replyURL  = replyScr[0].match(/<a href="([^"]+)">([^<]+)宛<\/a>/);
					getReplyURL(replyURL[1],target,replyURL[2]);
				}
			}
		})
	}

	check();
	
    function check(){
		
		var url = location.href;
		
		//誰かここの正規表現おせーて。
		
		var s = getElement('//ol[@id="timeline"]//li//span[@class="status-body"]/span[@class="meta entry-meta"]/a[position()=last()]');
    	var c = s.snapshotLength;
    	for(i=0;i<c;i++){
    		var str = s.snapshotItem(i).innerHTML;
    		if(s.snapshotItem(i).getAttribute("class") != "checked"){
	    		if(str.match(/宛/)){
		            s.snapshotItem(i).setAttribute("class","checked")
		            s.snapshotItem(i).addEventListener('mouseover',getReply,true);
				}
			}
    	}
    }

	if(window.Autopagerize){
	    window.AutoPagerize.addFilter(function(doc) {
	        check();
		});
	}else{
	    d.addEventListener('scroll',check, false);
	}

})();

