// v 0018 stable version
// ==UserScript==
// @name          pbtweet
// @namespace     http://t-trace.blogspot.com/
// @description   Expand conversation chains and twitPic.com thumbnails.
// @include       https://twitter.com/*
// @include       http://twitter.com/*
// ==/UserScript==
// UPDATE INFO http://web.me.com/t_trace/pbtweet.html

( function(){
var conv_chain_hash = new Array(0);
if(!document.getElementById('show')){

	// more button
	document.getElementById("timeline").addEventListener("DOMNodeInserted", 
		function (event){
		if(event.target.nodeName == "LI" ){setTimeout(init_autoPager(),1000);pbtweet_main([event.target])};
		}, false);
}

var insert_HTML = '';
var get_url = '';
var oLength = document.styleSheets[0].cssRules.length;
document.styleSheets[0].insertRule('div.conv_chain     {clear:both; text-align:left;min-height:32px;margin: -32px 5px 4px 40px; padding:2px 4px 2px 0px;}',oLength);
document.styleSheets[0].insertRule('div.conv_chain div.thumb{width: 34px !important; height: 34px !important; position:relative !important;max-width:100px;}',oLength+1);
document.styleSheets[0].insertRule('div.conv_chain div.thumb img{vertical-align:top; margin-right:4px !important;width:32px !important;height:32px !important;}',oLength+2);
document.styleSheets[0].insertRule('div.conv_chain span.icons{display:block;float:left;}',oLength+3);
document.styleSheets[0].insertRule('div.conv_chain span.entry-content{display:block;margin:0px 5px 5px 75px;min-height:32px;vertical-align:top;border:1px solid #cccccc; -webkit-border-radius: 4px;-webkit-box-shadow:0px 3px 5px rgba(0, 0, 0, 0.5);background:-webkit-gradient(linear, left top, left bottom, from(#fff), to(#ccc), color-stop(0.1, #fff));padding:2px 4px 2px 4px;}',oLength+4);
document.styleSheets[0].insertRule('div.conv_chain span.entry-meta{display:inline-block;width:350px;float: right;text-align:right}',oLength+5);
document.styleSheets[0].insertRule('img.twitpic_thumb {display:block;position:absolute;z-index:900;width:100px;heigt100px;border:7px solid white;-webkit-box-shadow:0px 3px 5px rgba(0, 0, 0, 0.7);-webkit-transform:translate(490px, -60px) scale(0.4) rotate(17deg); -webkit-transform-origin:50% 0%;-webkit-transition:-webkit-transform 0.15s ease-in;}',oLength+6);
document.styleSheets[0].insertRule('img.twitpic_thumb:hover {-webkit-transform: translate(490px, -60px) scale(1) rotate(0deg);}',oLength+7);
document.styleSheets[0].insertRule('div.conv_chain img.twitpic_thumb {-webkit-transform:translate(420px, -80px) scale(0.3) rotate(17deg);}',oLength+8);
document.styleSheets[0].insertRule('div.conv_chain img.twitpic_thumb:hover {-webkit-transform:translate(420px, -80px) scale(1) rotate(0deg);}',oLength+9);

function pbtweet_main(target){
    if(!document.getElementById('show')){
		var entry = target;
        for (i=0;i <= entry.length;i++){
			for(var j = 0; j <conv_chain_hash.length; j++){
				try{
					if(entry[i].id == conv_chain_hash[j]){
						remove_redundand(entry[i].id);
						}
				} catch(err) {
				}
			}
            try
            {
               if(entry[i].hasAttribute("id")){
					twitpic_thumb(entry[i].id,entry[i].innerHTML);
                }
                if(entry[i].childNodes[1].childNodes[1].nodeName == "IMG"){
					get_url = entry[i].childNodes[1].childNodes[3].childNodes[4].href;
                } else {
					get_url = entry[i].childNodes[1].childNodes[2].childNodes[4].href;
                }
                if(get_url)
                {
                    var my_node = entry[i].id;
                    retreve_data(get_url,my_node);
                }
            } 
            catch(err)
            {
            }
        }
    } else {
            try
            {
                var pic_entry = document.getElementsByClassName("status-body")[0];
                pic_entry.setAttribute("id",guid());
                twitpic_thumb(pic_entry.id,pic_entry.innerHTML);
                var entry = document.getElementsByClassName("entry-meta");
                get_url = entry[0].childNodes[4].href;
                if(document.getElementById("content").childElementCount == 1)
                {
                    retreve_data(get_url,"content");
                }
            } 
            catch(err)
            {
            }
    }
}

function retreve_data(get_url,my_node){
	var request = new XMLHttpRequest();
	request.onreadystatechange = function() {
		if(request.readyState == 4 && request.status == 200){
			var sent_responseText = this.responseText;
			var my_response = new Array();
			var capture_user = /<div\ class\=.thumb.+href.+<\/div>/;
			user_icon = sent_responseText.match(capture_user) + "";
			user_name = "<span>" + user_icon.replace(/.+<a\ href=\"http.*\:\/\/twitter\.com\/([^\"]+)\"\>\<img.+/,"$1") + "</span>";
			var capture_regex = /\<span\ class\=\"entry\-content\"\>[.\s\S]+\<\/span>/;
			var capture_url_regex = /span>\ <a\ href\=\"http.*\:\/\/twitter\.com\/[^\/]+\/status\/[0-9]+\">in\ reply\ to.+<\/a>/;
			var url_replace = /\:\/\/twitter\.com\/[^\/]+\/status\/[0-9]+\"\>in\ reply\ to/;
			my_response[0] = "<span class = \'icons\'>" + user_icon + user_name + "</span>" + sent_responseText.match(capture_regex);
			var url_base = sent_responseText.match(capture_url_regex) + "";
			my_response[1] = sent_responseText.match(url_replace)+"";
			if(my_response[1].match(url_replace)){
				if(location.href.match(/^https/)){
					var retreve_status = my_response[1].replace(/(\:\/\/twitter\.com\/.+\/status\/[0-9]+)\"\>in\ reply\ to/,"https$1");
				}
				if(location.href.match(/^http:/)){
					var retreve_status = my_response[1].replace(/(\:\/\/twitter\.com\/.+\/status\/[0-9]+)\"\>in\ reply\ to/,"http$1");
				}
				retreve_data(retreve_status,my_node);
			}
			var conv_chain = document.createElement('div');
			conv_chain.innerHTML = my_response[0];
			conv_chain.setAttribute("class","conv_chain");
			conv_chain.id = guid();
			conv_chain.setAttribute("id",guid());
			conv_chain.style.opacity = "0";
			conv_chain.style.marginTop = "-22px";
			conv_chain.style.webkitTransition = "opacity 1s ease-in, margin-top 0.25s ease-in";
			var conv_script = document.createElement('script');
			conv_script.innerHTML = "setTimeout(function(){document.getElementById('" + conv_chain.id + "').style.opacity = '1';document.getElementById('" + conv_chain.id + "').style.marginTop = '0px';},1)";
			conv_chain.appendChild(conv_script);
			var conv_devidor = document.createElement('div');
			conv_devidor.style.clear = "both";
			conv_devidor.style.marginBottom = "4px";
			conv_chain.appendChild(conv_devidor);
			try	{
			document.getElementById(my_node).appendChild(conv_chain);
			} catch(e){
			}
			var status_id = get_url.replace(/.+\:\/\/twitter\.com\/[^\/]+\/status\/([0-9]+)/,"status_$1");
			if(status_id != null){
				conv_chain_hash.push(status_id);
				setTimeout(remove_redundand(status_id),10);
			}
			
			twitpic_thumb(conv_chain.id,conv_chain.innerHTML);
		}
	};
	if (location.href.match(/^https/) && get_url.match(/^https/)){
	} else if (location.href.match(/^https/) && get_url.match(/^http\:/)) {
		get_url = get_url.replace(/^http\:/, "https:");
	} else if (location.href.match(/^http\:/) && get_url.match(/^https/)) {
		get_url = get_url.replace(/^https\:/, "http:");
	} else if (location.href.match(/^http\:/) && get_url.match(/^http\:/)) {
	}
	request.open('GET', get_url, true);
	request.send(null);
}

function remove_redundand(target_id){
	try	{
		var remove_target = document.getElementById(target_id);
		remove_target.parentNode.removeChild(remove_target);
	} catch(e) {
	}
}

function twitpic_thumb(id,html){
	var my_source = html;
	if(my_source == ""){
		my_source = document.getElementById(id).childNodes[0].childNodes[0].innerHTML;
	}
	var twitpic_carrier = />(http\:\/\/twitpic.com\/[^\<]+)<\/a>/;
	var bkite_carrier = /Photo\:\ \<a\ href\=\"http\:\/\/bkite.com\/([0-9a-zA-Z]+)\"/;
	if(my_source.match(twitpic_carrier)){
		var pic_thumb_src = my_source.match(twitpic_carrier)[1].replace(/http\:\/\/twitpic\.com\/([0-9a-zA-Z]+)/,"http://twitpic.com/show/thumb/$1");
		place_picture(id,pic_thumb_src);
	}
	// getting bkite.com image
	if (my_source.match(bkite_carrier)){
		var pic_thumb_query = my_source.replace(/.+<a\ href\=\"http\:\/\/bkite\.com\/([0-9a-zA-Z]+)\".+/,"http://bkite.com/objects/$1");
		var pic_thumb_loader = document.createElement('script');
		pic_thumb_loader.src = "http://pipes.yahoo.com/pipes/pipe.run?_id=WC_YK2IU3hGdr4ty6icw5g&_render=json&snipcode=" + pic_thumb_query + "&parentid=" + id + "&_callback=bkiteSrc";
		document.getElementsByTagName("head")[0].appendChild(pic_thumb_loader);
	}
		return;
}

function place_picture(id,pic_thumb_src){
	var pic_thumb = document.createElement('img');
	var pic_thumb_link = document.createElement('a');
	var pic_snip_code = pic_thumb_src.replace(/.+thumb\/([a-zA-Z0-9]+)$/,"$1");
	pic_thumb_link.setAttribute("href", "http://twitpic.com/" + pic_snip_code);
	pic_thumb_link.setAttribute("target", "_blank");
	var pic_thumb_id = guid();
	pic_thumb_link.setAttribute("id",pic_thumb_id);
	pic_thumb.setAttribute("class","twitpic_thumb");
	pic_thumb.setAttribute("src", pic_thumb_src);
	pic_thumb_link.appendChild(pic_thumb);
	document.getElementById(id).appendChild(pic_thumb_link);
}

function picture_server_url(){
	
}

function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

var bkite_processor = document.createElement('script');
bkite_processor.innerHTML = "var bkiteSrc = function(data){place_picture(data.value.items[1].content,data.value.items[0].content,data.value.items[2].content);}";
document.getElementsByTagName("head")[0].appendChild(bkite_processor);

pbtweet_main(document.getElementsByClassName('hentry')); //initial

//--autoScrolll--//
var during_pagination = true;
setTimeout(function(){if(!document.getElementById("autopagerize_style")){init_autoPager()}}, 1500);

function init_autoPager(){
during_pagination = false
	clickEvent = window.document.createEvent("MouseEvent"); 
	clickEvent.initEvent("click", false, true);
}

window.addEventListener("scroll", function(){add_scroll_event()}, false);

function add_scroll_event(){
	if(document.getElementById("content").clientHeight < (window.scrollY + window.innerHeight + 50) &&
		during_pagination == false){
		add_next_page();
	};
}

function add_next_page(){
	during_pagination = true;
	document.getElementById("more").dispatchEvent(clickEvent);
}

})();

place_picture = function(id,pic_thumb_src,snip_code){
	if(pic_thumb_src.match(/^http:\/\/s3\.amazonaws.com.+photo\-feed\.jpg$/)){
        	var pic_thumb = document.createElement('img');
        	var pic_thumb_link = document.createElement('a');
			pic_thumb_link.setAttribute("href", "http://bkite.com/" + snip_code);
			pic_thumb_link.setAttribute("target", "_blank");
        	var pic_thumb_id = guid();
			pic_thumb_link.setAttribute("id",pic_thumb_id);
			pic_thumb.setAttribute("class","twitpic_thumb");
			pic_thumb.setAttribute("src", pic_thumb_src);
			pic_thumb_link.appendChild(pic_thumb);
			document.getElementById(id).appendChild(pic_thumb_link);
	}
}

S4 = function() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
guid = function() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
