// ==UserScript==
// @name                smile downloader user JavaScript
// @namespace           http://home.1555.info/nicopon/
// @description         add flv download button to nicovideo page.
// @include             http://www.nicovideo.jp/watch/*
// @include             http://*.youtube.com/watch*
// @include             http://youtube.com/watch*
// @include             http://www.dailymotion.com/*video*
// @exclude             http://*http://

(function() {
var thisVersion="[20080203-build32]";
var thisBuildNum="32";
var installMode="UserScript";

// replace Heading element to selectable text (with form)
function elementSelectable (_elem){
	var ct = false;
	try{
		ct = _elem.firstChild.firstChild.nodeValue;
	} catch(e){
		ct = _elem.firstChild.nodeValue;
	}
	var ft = document.createElement('input');
		ft.type="text";
		ft.name="m_title";
		ft.value=ct;
		ft.readonly="true";
		ft.title=ct;
		ft.style.font="large bold";
		ft.style.border="solid 1px #666";
		ft.style.width="22em";
		ft.style.height="1em";
		if(inUA('Opera')!=-1){
			ft.onclick="this.focus();this.select();";
		} else if (inUA('MSIE')!=-1){
			ft.onclick=function(){this.focus();this.select();};
		}else if(inUA('Gecko')!=1 || inUA('AppleWebKit')!=-1){
			ft.addEventListener('click',function(){this.focus();this.select();}, true);
		}
	_elem.replaceChild (ft, _elem.firstChild);
}

// create image link
function createImgElement(_src, _alt, _href) {
	if (_href){
		var ca = document.createElement('a');
			ca.href = _href;
	}
	var im = document.createElement('img');
		im.alt = _alt;
		im.src = _src;
		im.style.border = "none";
	if (ca) {
		ca.appendChild (im);
		return ca;
	} else {
		return im;
	}
}

// detect user agent
function inUA(_val){
	return navigator.userAgent.indexOf(_val);
}

// create XMLHttpRequest object
function createXMLHttpRequest(){
	var r = false;
	try{
		r = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e){
		try{
			r = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(f){
			r = false;
		}
	} if (!r && typeof XMLHttpRequest !="undefined"){
		r = new XMLHttpRequest();
	}
	return r;
}

var nicoponFn = function(){
	if (location.href.indexOf("http://www.nicovideo.jp/watch/")!=-1){
		//　find "watch/smXXX" style URI
		var forms=document.getElementsByTagName('form');
		var origURI="";
		for (var i=0; i<forms.length; i++){
			if (forms[i].name=="mylist_form"){
				origURI=forms[i].action;
			}
		}

		// replace H1 Tag
		elementSelectable(document.getElementsByTagName('h1')[0]);

		// collect file information
		var videoIdentifier = location.href.replace(/http.*?watch\/(.*)$/g,"$1");
		var xS = createXMLHttpRequest();
		if (xS){
			xS.onreadystatechange = function(){
				if (xS.readyState==4 && xS.status==200){
					var tid=unescape(/thread_id\=(.*?)\&l/.exec(xS.responseText)[1]);
					var vn=/watch\/(.*?)$/.exec(origURI)[1];
					var flvURL=unescape(/url\=(.*?)\&link/.exec(xS.responseText)[1]);
					var imgSrc="";
					imgSrc="http://nicopon.jp/images/flv_dl.png";
					var imgAlt="download FLV File";
					document.getElementsByTagName('h1')[0].appendChild(createImgElement(imgSrc, imgAlt, flvURL));
				}
			};
			xS.open("GET", "http://www.nicovideo.jp/api/getflv?v="+videoIdentifier, true);
			xS.send('');
		}

		// notify banner and SBM buttons
		function infoBanner(){
			var strSBM=decodeURIComponent("%E3%82%BD%E3%83%BC%E3%82%B7%E3%83%A3%E3%83%AB%E3%83%96%E3%83%83%E3%82%AF%E3%83%9E%E3%83%BC%E3%82%AF%3A");
			var iMsgH0=decodeURIComponent("%5B%E9%87%8D%E8%A6%81%5D"); //重要
			var iMsgH1=decodeURIComponent("%E3%83%8B%E3%82%B3%E3%83%8B%E3%82%B3%E3%83%9D%E3%83%B3%E3%81%AE%E3%82%B5%E3%83%BC%E3%83%93%E3%82%B9%E3%81%AF2008%E5%B9%B42%E6%9C%8828%E6%97%A5%E3%82%92%E3%82%82%E3%81%A3%E3%81%A6%E7%B5%82%E4%BA%86%E3%81%97%E3%81%BE%E3%81%99%E3%80%82%E8%A9%B3%E3%81%97%E3%81%8F%E3%81%AF"); //ニコニコポンのサービスは2008年2月28日をもって終了します。詳しくは
			var iMsgH2=decodeURIComponent("%E3%82%B5%E3%82%A4%E3%83%88%E3%81%AE%E3%81%8A%E7%9F%A5%E3%82%89%E3%81%9B"); //サイトのお知らせ
			var iMsgH3=decodeURIComponent("%E3%82%92%E3%81%94%E8%A6%A7%E3%81%8F%E3%81%A0%E3%81%95%E3%81%84%E3%80%82"); //をご覧ください
			var w_nbsp=decodeURIComponent("%E3%80%80");

			var nc = document.createElement('div');
				nc.style.font = "bold 12px arial,sans-serif";
				nc.appendChild(document.createTextNode(strSBM));
				nc.appendChild(createImgElement("http://d.hatena.ne.jp/images/b_entry.gif", "hatena bookmark counter", "http://b.hatena.ne.jp/entry/"+origURI));
				nc.appendChild(createImgElement("http://b.hatena.ne.jp/entry/image/"+origURI, "hatena bookmark counter", "http://b.hatena.ne.jp/entry/"+origURI));
				nc.appendChild(document.createTextNode(" "));
				nc.appendChild(createImgElement("http://parts.blog.livedoor.jp/img/cmn/clip_16_12_w.gif", "Livedoor Clip", "http://clip.livedoor.com/redirect?link="+origURI+"&title="+encodeURIComponent(document.title)));
				nc.appendChild(document.createTextNode(" "));			
				nc.appendChild(createImgElement("http://www.goodpic.com/mt/images/icons/delicious_s.gif", "add to del.icio.us", "http://del.icio.us/post?v=4;url="+encodeURIComponent(origURI)+";title="+encodeURIComponent(document.title)));
				nc.appendChild(document.createTextNode(w_nbsp));
				
				var cH0 = document.createElement('strong');
				cH0.style.color = "red";
				cH0.appendChild(document.createTextNode(iMsgH0));
				nc.appendChild(cH0);
				
				nc.appendChild(document.createTextNode(iMsgH1));				

				var cH1 = document.createElement('a');
				cH1.href = "http://nicopon.jp/info-20080130.html";
				cH1.appendChild(document.createTextNode(iMsgH2));
				nc.appendChild(cH1);

				nc.appendChild(document.createTextNode(iMsgH3));

				
				nc.appendChild(document.createTextNode(" "+thisVersion));
			return nc;
		}

		// hide the AD banner.
		var divs=document.getElementsByTagName('div');
		var adDiv;
		if (divs){
			for (var i=0; i<divs.length; i++){
				if (divs[i].id.indexOf('web_pc_watch')!=-1){
					adDiv = divs[i];
					break;
				}
			}
			for (var i=0; i<divs.length; i++){
				if (divs[i].className=="ads_728"){
					divs[i].style.height="1.2em";
					divs[i].removeChild(adDiv);
					divs[i].appendChild(infoBanner());
					break;
				}
			}
		}
	}


	if (location.href.indexOf("youtube.com/watch?v")!=-1){
		// replace H1 Tag
		var r=document.getElementById('vidTitle');
        var titleElement;
        for (var i=0; i<r.childNodes.length; i++){
            if (r.childNodes[i].tagName.indexOf('SPAN')!=-1){
                titleElement = r.childNodes[i];
                break;
            }
        }
		var title = titleElement.firstChild.nodeValue; 
		var _rh1 = document.createElement('h1');
		_rh1.appendChild(document.createTextNode(title));
		r.appendChild(_rh1);
		r.removeChild(titleElement);
		elementSelectable(_rh1);
//		_rh1.style.font = "sans-serif 16px #000";

		// collect file information
		var videoIdentifier = location.href.replace(/http.*?watch\?v=([A-z\d\_\-\;]+).*$/g,"$1");
        var playerVars;
        if (inUA('Opera')==-1 && inUA('MSIE')!=-1){
                var params=document.getElementById('movie_player').childNodes;
                if (params){
                        for (var i=0; i<params.length; i++){
                                if (params[i].getAttribute("name")=="flashvars"){
                                        playerVars=params[i].getAttribute("value");
                                }
                        }
                }
        }
        else {
                playerVars=document.getElementById('movie_player').getAttribute('flashvars');
        }

        var tid=unescape(playerVars.replace(/^.*\&t=([A-z\d\-\_]+).*$/g,"$1"));

		var flvURL="http://www.youtube.com/get_video?video_id="+videoIdentifier+"&t="+tid;
		var imgSrc="";
		if (installMode="Bookmarklet") { 		
			imgSrc="http://nicopon.jp/images/flv_dl.png";
		}
		else if (installMode="UserScript") {
			imgSrc="http://nicopon.jp/images/flv_dl.png";
		}
		var imgAlt="download FLV File";
		r.appendChild(createImgElement(imgSrc, imgAlt, flvURL));
	}

	if (location.href.indexOf("http://www.dailymotion.com/")!=-1){
		// replace H1 Tag
		var r=document.getElementsByTagName('h1')[0];
		elementSelectable(r);
		// collect file information
		var playerVars;
		if (inUA('Opera')==-1 && inUA('MSIE')!=-1){
			var params=document.getElementById('video_player').childNodes;
			if (params){
				for (var i=0; i<params.length; i++){
					if (params[i].getAttribute("name")=="flashvars"){
						playerVars=params[i].getAttribute("value");
					}
				}
			}
		}
		else {
			playerVars=document.getElementById('video_player').getAttribute('flashvars');
		}

		var flvURL=unescape(playerVars.replace(/^.*\&url=([A-z\d\%\.]+).*$/g,"$1"));
		var videoIdentifier = flvURL.replace(/^.*([\d]+\.flv).*$/g,"$1");
		var imgSrc="";
		if (installMode="Bookmarklet") { 		
			imgSrc="http://nicopon.jp/images/flv_dl.png";
		}
		else if (installMode="UserScript") {
			imgSrc="http://nicopon.jp/images/flv_dl.png";
		}
		var imgAlt="download FLV File";
		document.getElementsByTagName('h3')[0].appendChild(createImgElement(imgSrc, imgAlt, flvURL));
	}
};

// execute method

if(inUA('Opera')!=-1 || inUA('MSIE')!=-1 || installMode=="Bookmarklet" || inUA('AppleWebKit')!=-1){
	nicoponFn.apply();
} else if(inUA('Gecko')!=1){
	window.addEventListener('load',nicoponFn, true);
}
})();
