var nlMFL={
	/* popThumb_FAのような表示にする */
	use_ThumbData:true,
	
	cacheList:{},
	fetchList:{},
	makeFetchedList:function(){
		var T=this,d=document,cacheList=T.cacheList,fetchedList=T.fetchList;
		var E=[],fL=0,elem=p='';
		if((p=window.popThumb)&&popThumb.addEvent){
			if(T.use_ThumbData){
				d.getElementById('DisplayType').classList.add('ThumbDataType');
				d.getElementsByClassName('content_right')[0].classList.add('ThumbData');
			}
			for(var i in fetchedList){
				++fL;
				E.push('<div id="'+i+'" class="thumb_box">'+T.make(i)+(p.data['obj_'+i]?T.make_from_object(i):'')+'</div>');
			}
			d.getElementById('DisplaySwitchingTD').style.display='table-cell';
		}else{
			for(var i in fetchedList){
				++fL;
				E.push('<div id="'+i+'" class="thumb_box">'+T.make(i)+'</div>');
			}
		}
		d.getElementById('count').textContent=fL;
		d.getElementsByClassName('content_right')[0].insertAdjacentHTML('BeforeEnd',(fL?E.join(''):'<br /><div>未視聴の動画はありません</div>'));
	},
	make:function(smid){
		var T=this,cacheList=T.cacheList,fetchedList=T.fetchList;
		var title=fetchedList[smid],
			id=smid.substring(2),
			ecofetch=cachecolor=cacheicon='';
		if(cacheList[smid]){
			cachecolor=' style="color:#C00000;"';
			cacheicon='<div class="cacheIcon cacheIconImg"></div>';
		}else if(cacheList[smid+'low']){
			cachecolor=' style="color:#C08000;"';
			cacheicon='<div class="cacheIcon economyIconImg"></div>';
		}else{
			ecofetch='| <a href="javascript:void(0);" onclick="nicofetch(this,\''+smid+'\')" style="text-decoration:none; font-size:small; margin-left:5px;">fetch</a>';
		}
		return	'<div class="thumb_frm simple">'+
				'<div class="thumb_frm_left">'+
				'<a href="watch/'+smid+'" target="_blank" onclick="nlMFL.removeFetched(this)" class="thumb_img_"><span data-img-src="http://tn-skr1.smilevideo.jp/smile?i='+id+'" class="thumb_img"></span></a>'+
				cacheicon+
				'</div><div class="thumb_frm_right">'+
				'<a class="watch title" href="watch/'+smid+'" target="_blank" onclick="nlMFL.removeFetched(this)" onMouseOver="return popThumb2(\''+smid+'\',0,0)" onMouseOut="return nd()"'+cachecolor+'>'+title+'</a>'+
				'<div><input title="取得動画リストからこの動画を削除します" class="submit" type="submit" value="視聴済" onclick="nlMFL.removeFetched(this)" style="margin:2px 0px; padding:1px;">'+ecofetch+'</div>'+
				'<p class="font12" style=" margin:4px;"><a href="javascript:void(0);" onclick="nlMFL.getThumbData(\''+smid+'\')" style="text-decoration:none;" class="nl_Desc" nl-smid="'+smid+'">サムネイルデータ表示</a></p>'+
				'</div>'+
				'</div>';
	},
	make_from_object:function(pop_smid){
		var	T=this,popThumb=window.popThumb,
				object=popThumb.data['obj_'+pop_smid][1],
				HttpRequest=popThumb.HttpRequest,
				addFigure=T.addFigure,
				cacheList=T.cacheList;
		var isVideoArray=!!object.usingAPI.videoarray,
			isGetthumbinfo=!!object.usingAPI.getthumbinfo,
			thumb_url=object.thumbnail_url,
			title=object.title,
			desc=object.description,
			eachSmid=object.video_id,
			length_s=object.length_in_seconds,
			length=object.length,
			view=object.view_counter,
			mylist=object.mylist_counter,
			comment=object.comment_counter,
			movie_type=object.movie_type,
			tags_obj=object.tags,
			user_id=object.user_id,
			user_name=object.user_nickname,
			isDeleted = object.deleted>0;
		if (popThumb.use_cachedVideoArrayAPI && object.description_videoarray)desc=object.description_videoarray;
		if (popThumb.use_in_JS_to_link)desc=popThumb.desc_to_link(desc,'popThumb_FA_link',pop_smid);
		if (!eachSmid && /^[a-z]{2}/.test(pop_smid))eachSmid=pop_smid;
		var cache=object.cache=(cacheList[pop_smid]?'icon':cacheList[pop_smid+'low']?'economy':null);
			posting=object.first_retrieve.match(/20(\d{2})-(\d{2})-(\d{2})T(.{8}).+/),
			year =posting[1],
			month=posting[2],
			day  =posting[3],
			time =posting[4],
			size_high=((object.size_high/1024/1024*10)|0)/10,
			size_low =((object.size_low /1024/1024*10)|0)/10,
			bit_rate =size_high ?((object.size_high/1024*8/length_s)|0) :'(不明)';
		size_high=size_high||'(不明)';
		if(movie_type==='swf' && size_high===size_low)size_low=0;
		var tags=[],tags_obj_len=i=tags_obj.length;
		if(i){
			for(;i--;){
				var tag_obj=tags_obj[i],
					res=[],
					tag_encode=tag_obj.text,
					tag_text=tag_encode.replace(/<[^<>]+>/g,'');
				res.push('<span class="TagType'+(tag_obj.lock?' TagLock':'')+(tag_obj.category?' TagCategory':'')+'"></span>');
				if(popThumb.use_in_JS_to_link)tag_encode=popThumb.desc_to_link(tag_encode,'popThumb_FA_link',pop_smid);
				res.push(tag_encode.replace(/(^|<\/[^>]+>)([^<>]+)/,'$1<a href="http://www.nicovideo.jp/tag/'+tag_text+'">$2</a>'));
				if(tag_obj.dic||(popThumb.dic&&popThumb.dic[tag_encode]))res.push('<a href="http://dic.nicovideo.jp/a/'+tag_encode+'" class="TagDic"></a>');
				tags.unshift('<li class="TagItem">'+res.join('')+'</li>');
			}
		}else{tags.push('<li class="TagItem">タグがありません</li>')}
		tags.unshift('<li class="TagItem"><strong>TAG</strong>:[ jp:'+tags_obj_len+' ]</li>');
		var getTag=tags.join(''),
			owner_link='<span style="color:orange;">community !</span>';
		if(user_id){
			owner_link='<a onmouseover="return popThumb(\'thumb_user/'+user_id+'\', 0)" onmouseout="return nd();" title="プロフィールへ" href="http://www.nicovideo.jp/user/'+user_id+'">投稿者ID: '+user_id+'</a> ： <a title=ニコニコチャートへ href="http://www.nicochart.jp/name/?s='+encodeURIComponent(user_name)+'" style="color:#F30; font-weight: bold;">'+user_name+'</a>';
		}else if(isVideoArray && !isGetthumbinfo){
			owner_link='<span style="color:orange;">APIの仕様で投稿ユーザー不明</span>';
		}
		return	'<div class="thumb_frm custom">'+
				'<p class="font10">'+
				'<a href="http://www.nicochart.jp/watch/'+eachSmid+'" title="NicoChart : '+eachSmid+'">'+pop_smid+'</a>'+
				'<a style="margin-left:10px;" href="javascript:void(nlMFL.getThumbData(\''+pop_smid+'\'))" title="ThumbDataの更新">更新</a>'+
				'<a style="margin-left:10px;" href="http://www.nicovideo.jp/openlist/'+eachSmid+'" title="公開マイリストを検索">Op-ML</a>'+
				'<a style="margin-left:10px;" href="http://dic.nicovideo.jp/v/'+eachSmid+'" title="この動画の大百科">DIC</a>'+
				'<a style="margin-left:10px; color:red;" title="キャッシュを消します(NicoCache_nl)" href="http://www.nicovideo.jp/cache/rm?'+eachSmid+'" onclick="return popThumb.delCache(\''+eachSmid+'\', 0, this);">DEL</a>'+
				'<a style="margin-left:10px;" href="javascript:void(0);" title="クリックでキャッシュ移動用セレクトボックスが出ます(NicoCache_nl)" onclick="popThumb.cacheMove_init(this, \''+eachSmid+'\', \''+pop_smid+'\'); return false;">移動</a>'+
				'</p>'+
				'<p class="font10"> 再生：<strong>'+addFigure(view)+'</strong> コメント：<strong>'+addFigure(comment)+'</strong> マイリスト：<strong>'+addFigure(mylist)+'</strong>'+
				'</p>'+
				'<table border="0" cellpadding="0" cellspacing="0" summary="" style="margin-top:2px;"><tr valign="top">'+
				'<td class="font10"><p style="position:relative;">'+
				'<a href="http://www.nicovideo.jp/watch/'+pop_smid+'" target="_blank" onclick="nlMFL.removeFetched(this)" class="thumb_img_"><span data-img-src="'+thumb_url+'" class="thumb_img"></span></a>'+
				(cache?'<div class="cacheIcon '+(cache=='economy'?'economy':'cache')+'IconImg"></div>':'')+
				(isDeleted?'<div class="cacheIcon deleteIconImg"></div>':'')+
				'</p><strong style="line-height:1.5em;">'+length+'</strong>'+
				'<table border="0" cellpadding="0" cellspacing="0" class="movie_type font10"><tbody>'+
				(isGetthumbinfo?
					'<tr><td>通常画質</td><td>：</td><td>'+size_high+'MB</td></tr>'+
					'<tr><td>レート</td><td>：</td><td>'+bit_rate+'kbps</td></tr>':'')+
				'<tr style="color:'+(!size_low?'blue':'red')+'"><td>エコノミー</td>	<td>：</td><td>'+size_low+'MB</td></tr>'+
				'<tr><td>動画形式</td><td>：</td><td class="'+movie_type+'">'+movie_type+'</td></tr>'+
				'</tbody></table>'+
				'<td style="padding-left:4px; width:100%;">'+
				'<p class="font10">'+
				'<span style="display:inline-block;">'+
				'<span class="postTime" style="margin-right:5px;"><strong>'+year+'/'+month+'/'+day+' '+time+'</strong> 投稿</span>'+
				(cache?'':'<a href="javascript:void(0)" onclick="nicofetch(this,\''+pop_smid+'\',7)" style="margin-right:5px;">fetch</a>')+
				'<a href="javascript:void(0)" onclick="nlMFL.removeFetched(this)" title="取得動画リストからこの動画を削除します" style="margin-right:5px;">視聴済</a>'+
				'</span>'+
				'<span style="display:inline-block;">'+owner_link+'</span>'+
				'</p>'+
				'<p class="font12"><a href="http://www.nicovideo.jp/watch/'+pop_smid+'" class="title watch '+
				(!cache?'':cache=='economy'?'nico_economy':'nico_cache')+
				'" target="_blank" onclick="nlMFL.removeFetched(this)">'+title+'</a></p>'+
				'<ul class="TagList font12">'+getTag+'</ul>'+
				'<p class="font12 description">'+desc+'</p></td></tr></table>'+
				'</div>';
	},
	addFigure:function(str){return (str-0).toLocaleString()},
	getThumbData:function(smid){
		var T=this,p=window.popThumb,d=document;
		var elem=d.getElementById(smid);
		if(elem.lastChild.className=='custom'){
			var make=elem.firstChild.innerHTML.replace('simple"','simple hide"'),
				makeO=elem.lastChild.innerHTML.replace('custom"','custom block"');
			elem.innerHTML=make+makeO;
		}else{
			p.HttpRequest('http://'+location.host+'/pr_Redirect_ext.nicovideo.jp/api/getthumbinfo/'+smid+'?nlFilter',function(){
				var make=T.make(smid).replace('simple"','simple hide"'),
					makeO=T.make_from_object(smid).replace('custom"','custom block"').replace(/(data-img-src="([^"]+)")/,'$1 style="background-image:url($2);"');
				elem.innerHTML=make+makeO;
			},false,smid,['api',smid]);
		}
	},
	removeFetched:function(elem){
		var T=this,d=document;
		while(elem.className!='thumb_box')elem=elem.parentNode;
		var smid=elem.id;
		T.HttpRequest('/cache/fetch?rm='+smid,function(r){
			if(!r.responseText.indexOf('OK')){
				d.getElementById(smid).setAttribute('style','display:none;');
				--d.getElementById('count').textContent;
			}
		})
	},
	removeFetchedAll:function(input){
		var T=this;
		if(!confirm(input.title+'よ？'))return;
		T.HttpRequest('/cache/fetch?rm=all',function(r){
			if(!r.responseText.indexOf('OK')){
				var d=document;
				var fetchedList=T.fetchedList;
				for(var i in fetchedList)d.getElementById(i).setAttribute('style','display:none;');
				fetchedList={};
				d.getElementById('count').textContent=0;
			}
		})
	},
	cancelFetchRequest:function(smid){
		this.HttpRequest('/cache/fetch?cancel='+smid,function(r){
			if(smid=='all')alert('リクエストを全てキャンセルしました')}
		)
	},
	popFetchStatusList:function(param){
		var T=this,d=document;
		var pfs=d.getElementById('pop_fetch_status'),pfsPN=pfs.parentNode,p='';
		if(window.popThumb && popThumb.addEvent)p=window.popThumb;
		var C=0,
			LoadStatus=function(){
			T.HttpRequest('/cache/fetch?status=all',function(r){
				var Rsplit=r.responseText.split(/\r\n/),
					fetchingList={};
				for(var i=Rsplit.length;i--;){
					var RS=Rsplit[i];
					if(RS=='')continue;
					var RSsplit=RS.split(': '),
						id   =RSsplit[0],
						value=RSsplit[1];
					fetchingList[id]=value;
				}
				var fLen=Object.keys(fetchingList).length
				if(!fLen){
					d.getElementById('RequestCount').textContent=fLen;
					pfs.innerHTML='<div> no request.</div>';
				}else{
					var A=[];
					for(var id in fetchingList){
						var value=fetchingList[id];
						if(id!='updatelow'){
							if(~value.indexOf('done') && (!T.fetchList[id] || T.cacheList[id+'low'])){
								T.HttpRequest('/cache/ajax_info?'+id,function(r,id2){
									var rTsplit=r.responseText.split(','),
										cache=rTsplit[1],
										size =rTsplit[3],
										title=rTsplit[5],
										elem='';
									if(!T.fetchList[id2]){
										T.fetchList[id2]=title;
										T.cacheList[id2+cache]=[title,'',size,0];
										elem=('<div id="'+id2+'" class="thumb_box">'+T.make(id2)+((p&&p.data['obj_'+id2])?T.make_from_object(id2):'')+'</div>');
										d.getElementsByClassName('content_right')[0].insertAdjacentHTML('BeforeEnd',elem);
										++d.getElementById('count').textContent;
									}else if(!cache && (T.cacheList[id2]=T.cacheList[id2+'low'])){
										var node=d.getElementById(id2);
										node.parentNode.removeChild(node);
										delete T.cacheList[id2+'low'];
										elem=('<div id="'+id2+'" class="thumb_box">'+T.make(id2)+((p&&p.data['obj_'+id2])?T.make_from_object(id2):'')+'</div>');
										d.getElementsByClassName('content_right')[0].insertAdjacentHTML('BeforeEnd',elem);
									}
								},true,id);
							}
							id=('<a href="watch/'+id+'" onMouseOver="return popThumb(\'thumb/'+id+'\', 0)" onMouseOut="return nd()">'+id+'</a>');
						}
						A.unshift('<div>'+id+' : '+value+'</div>');
					}
					pfs.innerHTML=A.join('');
					if(C!=fLen){
						d.getElementById('RequestCount').textContent=fLen;
						C=fLen;
					}
					T.LStimeout=setTimeout(LoadStatus,1000);
				};
			},true)
		}
		var RI=d.getElementById('RequestInfo_TD');
		if(param=='updatelow'||!RI.classList.contains('pop_status')){
			if(param=='updatelow')T.HttpRequest('/cache/fetch?updatelow');
			LoadStatus();
			RI.classList.add('pop_status');
		}else{
			RI.classList.remove('pop_status');
			clearTimeout(T.LStimeout);
		}
	},
	DSwitch:function(){
		var T=this,d=document,p=window.popThumb;
		var Type=d.getElementById('DisplayType'),
			CR=d.getElementsByClassName('content_right')[0];
		Type.classList.toggle('ThumbDataType');
		CR.classList.toggle('ThumbData');
		if(d.getElementsByClassName('hide')){
			var elem=d.getElementsByClassName('thumb_frm');
			for(var i=elem.length;i--;){
				elem[i].classList.remove('hide','block');
				
			}
		}
	},
	LazyLoadImage:function(){
		var W=window,T=W.nlMFL,D=document;
		var LLI=function(){
			var bottom=W.scrollY+W.innerHeight;
			if((T.LLIoffset||0)>bottom)return;
			var i=(T.LLIcount||0),elem=D.getElementsByClassName('thumb_box');
			for(len=elem.length;i<len;i++){
				var elem2=elem[i],offset=elem2.offsetTop;
				if(offset<bottom){
					var elem3=elem2.getElementsByClassName('thumb_img');
					for(var i3=elem3.length; i3--;){
						var elem3i=elem3[i3];
						elem3i.setAttribute('style','background-image:url('+elem3i.getAttribute('data-img-src')+')')
					}
					if(!~(i-len)){
						window.removeEventListener('scroll',T.LazyLoadImage,false);
					}
				}else{
					T.LLIcount=i;
					T.LLIoffset=offset;
					return;
				}
			}
		}
		clearTimeout(T.LLItimeout);
		T.LLItimeout=setTimeout(LLI,200);
	},
	HttpRequest:function(url,func,Async,h){
		var httpObj=new XMLHttpRequest(),R='';
		httpObj.abort();
		httpObj.open('GET',url,!!Async);
		httpObj.setRequestHeader('If-Modified-Since','Thu, 01 Jun 1970 00:00:00 GMT');
		httpObj.onload=function(){if(typeof func=='function')R=func(httpObj,h)}
		httpObj.send(null);
		return R;
	},
	init:function(){
		var T=this;
		T.HttpRequest('/cache/fetch?list',function(r){eval(r.responseText);T.fetchList=fetchedList},true);
		T.HttpRequest('/cache/cachelist.json',
			function(r){
				T.cacheList=JSON.parse(r.responseText);
				T.makeFetchedList();
				T.popFetchStatusList();
				T.LazyLoadImage();
				window.addEventListener('scroll',T.LazyLoadImage,false);
			}
		,true);
	}
};
nlMFL.init();