/**
 * @author shom
 */

function AltIcons(e,cn,s){
	if(AltIcons._html){
		G.setStyleSheet(AltIcons._style);
		var div=document.createElement("div");
		div.id="icon_alt_box"; div.className="icon_alt";
		div.innerHTML=AltIcons._html;
		delete AltIcons._html;
		delete AltIcons._style;
		document.body.appendChild(div);
	}
	this.cn=cn; /* css classname */
	this.s=s; /* css styles */
	this.e=e;
}

AltIcons._html=
	'<div class="icon_alt_center"><span></span></div>'
	+'<div class="icon_alt_left"><span></span></div>'
	+'<div class="icon_alt_top"><span></span></div>'
	+'<div class="icon_alt_right"><span></span></div>'
	+'<div class="icon_alt_bottom"><span></span></div>';
	/*
	'<!-- '
	+'<div class="icon_alt_center" ontouchend="AltIcons.onAllFix(\'center\')" onmouseup="AltIcons.onAllFix(\'center\')"></div>'
	+'	-->'
	+'<div class="icon_alt_center" ></div>'
	+'<div class="icon_alt_left"   onmouseup="AltIcons.onAllFix(\'left\')"></div>'
	+'<div class="icon_alt_top"    onmouseup="AltIcons.onAllFix(\'top\')"></div>'
	+'<div class="icon_alt_right"  onmouseup="AltIcons.onAllFix(\'right\')"></div>'
	+'<div class="icon_alt_bottom" onmouseup="AltIcons.onAllFix(\'bottom\')"></div>';
	'<!-- '
	+'<div class="icon_alt_center" ontouchend="AltIcons.onAllFix(\'center\')" onmouseup="AltIcons.onAllFix(\'center\')"></div>'
	+'	-->'
	*/

AltIcons._style=
	"#icon_alt_box { position:absolute; padding:0; margin:0; border:none; z-index:10000; } "
	+"#icon_alt_box div { position:absolute; padding:0; margin:0; width:100%; height:100%; border:none; } "
	+"#icon_alt_box div.icon_alt_center { left:0; top:0; } "
	+"#icon_alt_box div.icon_alt_left { left:-100%; top:0; } " 
	+"#icon_alt_box div.icon_alt_top { left:0; top:-100%; } "
	+"#icon_alt_box div.icon_alt_right { left:100%; top:0;  } "
	+"#icon_alt_box div.icon_alt_bottom { left:0; top:100%; } ";

AltIcons.prototype.cancel=function(){
	clearTimeout(AltIcons._timer);
	delete AltIcons._timer;
	delete AltIcons._cur;
};

AltIcons.prototype.show=function(e,pos){
	//console.log("AltIcons._showing:"+AltIcons._showing);
	if(AltIcons._showing){return;}
	AltIcons._showing=(new Date()).valueOf();
	this.e=this.e||e;
	(function(pos){
		if(!pos&&this.e) {
			pos=G.pos(this.e);
		}
		/*
		AltIcons.s=G.setStyleSheet(G.tmpl("#icon_alt_box {top:${top}px;left:${left}px;width:${width}px;height:${height}px;}",pos),AltIcons.s);
		console.log(G.getSelectorPath(this.e)+":"+G.dump(pos));
		*/
		if(this.cn){G.$("icon_alt_box").className="icon_alt "+this.cn;}
		if(this.s){AltIcons.s2=G.setStyleSheet(this.s,AltIcons.s2);}
		pos.display="block";
		G.setStyles(G.$("icon_alt_box"),{
			display:"block",
			top:pos.top+"px",
			left:pos.left+"px",
			width:pos.width+"px",
			height:pos.height+"px"
		});
		AltIcons._cur=this;
	}).later(1,this,pos);
};

AltIcons.prototype.hide=function(){
	if(!AltIcons._showing){return;}
	delete AltIcons._showing;
	//AltIcons._showing=false;
	//console.log("AltIcons:hide");
	//AltIcons.s=G.setStyleSheet("#icon_alt_box { display:none; } ",AltIcons.s);
	//G.removeStyleSheet(AltIcons.s2);
	G.$("icon_alt_box").style.display="none";
	this.cancel();
};


AltIcons.onAllFix=function(dir){
	var c=AltIcons._cur;
	c.onFix(dir);
};

AltIcons.prototype.onFix=function(dir){
	this.hide.later(1,this);
	if(this["onfix"+dir]){this["onfix"+dir](this.e);}
	/*
	switch(dir){
		case "center":
		case "left":
		case "top":
		case "right":
		case "bottom":
	}*/
	//alert(dir);
	//console.log("AltIcons:onFix:"+dir);
};


var movemanip=(function(y){
	if(MP.tmpl.entries&&MP.tmpl.entries.busy){movemanip.later(200,this,y);return;}
	if(G.isClass(G.$("manip"),"opened")){return;}
	if(this.timer){clearInterval(this.timer);}
	var np=(y===undefined)?G.getPageYOffset()+10:y;
	np=Math.max(75,np);
	if(G.isSafari){
		//G.addClassName(G.$("manip"),"animate");
		//G.removeClassName($("manip"),"animate");
		//G.$("manip").style["-webkit-transform"]="translate(0,"+np+"px);";
		G.$("manip").style.cssText="-webkit-transform:translate(0,"+np+"px);";
		//CONSOLE.info(G.$("manip").style.cssText);
	}else{
		G.$("manip").style.top=np+"px";
	}
	this.op=np;
}).bindThis({op:0,timer:null});

MP._loginchecking=true;

function onlogin(){
	MP._loginchecking=false;
	/* for SMART */
	G.requireJs("http://smart4c.jp/smart/ip/js/smart.js");
	(function(){
		SMART.API = "http://smart4c.jp/sm/cmd/";
		SMART.doSLL("lifelog/session_check", null, function(r){
			if (r.RESULTS[0]) {
				G.addClassName(document.body,"smartlogined");
				G.requireCss("http://smart4c.jp/smart/ip/css/postbox.css");
			}
		}, function(e){
		});
	}).poll(function(){return typeof SMART != "undefined" });
	G.setElementValues(G.$("manip"),{member_id:MP.login.member_id});
	G.removeClassName(document.body,"notlogined");
	G.addClassName(document.body,"logined");
	genplaylists();
	dohash();
	initfill();
}

function onnotlogin(){
	MP._loginchecking=false;
	MP._waitonnotlogin&&MP._waitonnotlogin();
	dohash();
	initfill();
}

var oldhash=location.hash
setInterval(function(){
	if(MP._loginchecking){return;}
	if(oldhash!=location.hash){
		oldhash=location.hash;
		dohash();
	}
},500);

function genplaylists(){
	MP.playlists={};
	var tmpl=MP.tmpl.playlists,tmpl2=MP.tmpl.plfsin;
	if(!tmpl){
		MP.tmpl.playlists=tmpl=new G.HtmlElementTemplater(G.$("playlists"));
	}
	if(!tmpl2){
		MP.tmpl.plfsin=tmpl2=new G.HtmlElementTemplater(G.$("plfsin"));
	}
	tmpl.start(); tmpl2.start();
	G.each(MP.login.memo.mylists,function(v,i){
		if(v.id === undefined){v.id=i;}
		tmpl.apply(v); tmpl2.apply(v);
		v.channel_id=v.channel_id||[];
		if(!v.channel_id instanceof Array){v.channel_id=[v.channel_id];}
		MP.playlists[v.id]=v;
	});
	tmpl.complete(); tmpl2.complete();
	if(!G.$("plfsin-clone",true)){
		var div=tmpl2.e.cloneNode(true);
		div.id="plfsin-clone";
		G.each(G.$S(".template",div),function(e){G.removeElement(e)});
		tmpl2.e.parentNode.insertBefore(div,tmpl2.e);
	}else{
		var div=tmpl2.e.cloneNode(true);
		G.each(G.$S(".template",div),function(e){G.removeElement(e)});
		G.$("plfsin-clone").innerHTML=div.innerHTML;
	}
}

var title;
MP.setOnLoadHtml(function(){

	var uri=G.parseUri(location.href);
	G.requireCss("./skin/"+(uri.params.sk||"default")+"/skin.css");
	if(uri.params.css){
		G.requireCss(uri.params.css);
	}

	/*
	MP.tmpl.entries=new G.HtmlElementTemplaterSeq(G.$("entries"));
	MP.tmpl.entries.seq=new G.Seq(100);
	*/
	MP.tmpl.entries=new G.HtmlElementTemplater(G.$("entries"));
	MP.tmpl.entries.start();
	MP.cursors={};

/*
	MP.linkClickHandlersExtend("search",function(orgf,target,args,e,onapply,oncomp){
		// args=["descall"].concat(args);
		onapply=(onapply||function(v){return v}).hook(function(orgf,v){
			v._pub_date_jp=MP.getUserTZDate(v.pub_date).format("%Y年 %m月%d日 %H時%M分");
			return v;
		});
		return orgf(target,args,e,onapply,oncomp);
	});
*/
/*
	MP.linkClickHandlersExtend("entry",function(orgf,target,args,e,onapply,oncomp){
		onapply=(onapply||function(v){return v}).hook(function(orgf,v){
			//v._pub_date_jp=MP.getUserTZDate(v.pub_date).format("%Y年 %m月%d日 %H時%M分");
			return v;
		});
		return orgf(target,args,e,onapply,oncomp);
	});
*/

	MP.allClickHandler.block=function(){
		return (MP.tmpl.entries&&MP.tmpl.entries.busy) || (MP.tmpl.enntry&&MP.tmpl.entry.busy);
	};
	
	G.addEvent(document,"click",function(ev){
		ev=G.parseEvent(ev);
		//CONSOLE.log("click:"+G.getXPath(ev.target,document.body,["id","class","href"]));
	});
	
	G.addEvent(window,"scroll",(function(ev){
		if(this.timer_fill){clearTimeout(this.timer_fill);}
		this.timer_fill=(function(){
			clearTimeout(this.timer_fill);
			delete this.timer_fill;
			initfill();
		}).later(500,this);
		if(this.timer_manu) {clearTimeout(this.timer_manu);}
		this.timer_manu=(function(){
			clearTimeout(this.timer_manu);
			movemanip();
			delete this.timer_manu;
		}).later(2000,this);
	}).bindThis({}));

	G.addEvent(document,"keypress",function(ev){
		ev=G.parseEvent(ev);
		if(ev.target.tagName){
			switch(ev.target.tagName.toLowerCase()){
				case "input": case "textarea": case "select": case "option":
					return;
			}
		}
		if(ev.shiftKey||ev.ctrlKey||ev.altKey){return;}

		//CONSOLE.log(ev.type+":"+ev.keyAsc);

		var e,b,c;
		var entryshowing=G.isClass(G.$("entry"),"showing");
		var entryshowing=MP.cursors.entries&&G.isClass(MP.cursors.entries,"opened");
		//if(G.isClass(G.$("entry"),"showing")){
			b=G.$("entry");			
			e=G.$("entry");
			c="entries";
		//}
		switch(ev.keyAsc){
			case 78: case 110: // n
				cursornext(c);
				return G.stopBubble(ev,true);
				break;
			case 80: case 112: //p
			case 66: case 98: //b
				cursorprev(c);
				return G.stopBubble(ev,true);
				break;
			case 85: case 117: // u
				if(!entryshowing){return;}
				//MP.pseudoClick(G.$S("a.full",b)[0]);
				//window.open(G.$S("a.full",b)[0].href);
				//return G.stopBubble(ev,true);
				//break;
			case 81: case 113: //q
			case 27: // ESC
				if(!entryshowing){return;}
				MP.pseudoClick(G.$("entries-link-"+MP.showingEntry.item_id));
				//MP.pseudoClick(MP.cursor.entries.firstChild);
				return G.stopBubble(ev,true);
				break;
		}
	});
	
	/* iPhone */
	MP._ai=new AltIcons(null,"gesture_icon_html");
	MP._ai.onfixtop=function(e){
		MP._ai.hide();
		window.open("http://www.google.com/gwt/n?u="+G.esc(e.parentNode.href,"U"));
	};
	MP._ai.onfixcenter=function(e){
		MP._ai.hide();
		window.open(e.parentNode.href,"U");
	}
	
	MP._gi=new AltIcons(null,"gesture_icon_desc");
	MP._gi.onfixright=function(){
		MP._gi.hide();
		cursornext("entries");
	};
	MP._gi.onfixleft=function(){
		MP._gi.hide();
		MP.cursors.entries.scrollIntoView();
		window.scrollBy(0,-100);
		MP.pseudoClick(G.$S("a",MP.cursors.entries)[0]);
	};
	/*
	MP._gi.onfixbottom=function(){
		MP._gi.hide();
		MP.pseudoClick("#gtranslate-en-ja-append@body/#entry .template-gen .forgtrans");
	};
	*/
	MP.Gesturable.setOnGesture(function(e){
		return G.isClass(e,"icon_html");
	},{
		".?N+.?":function(e,mode){
			if(mode=="end") {
				MP._ai.onfixtop(MP.Gesturable._move_e);
				return true;
			}
		},
		".*":function(e,mode){
			if(mode=="end") {
				//console.log(lsd);
				MP._ai.hide();
				return true;
			}
		},
		"":function(e,mode){
			if(mode=="end") {
				MP._ai.onfixcenter(MP.Gesturable._move_e);
				return true;
			}
		}
	},function(e,evpos){
		//console.log("AltIcon.show");
		//console.log(G.getSelectorPath(MP._ai.e));
		MP._ai.show(e,G.pos(e));
	},function(){
		MP._ai.hide();
	});

if (false) {
	/* conflict with copy&past interface on iPhone OS 3.0 (Safari4) */
	MP.Gesturable.setOnGesture(function(e){
		//return (e.tagName&&e.tagName.toLowerCase()!="a")&&(G.$SA(e,".description")||G.$SA(e,".description_follow"));
		return G.$SA(e,".gesturable_ai");
	},{
		".?[39E]+.?":function(e,mode){
			if(mode=="end") {
				MP._gi.onfixright(e);
				return true;
			}
		},
		".?[17W]+.?":function(e,mode){
			if(mode=="end") {
				MP._gi.onfixleft(e);
				return true;
			}
		},
		/*
		".?[13S]+.?":function(e,mode){
			if(mode=="end") {
				MP._gi.onfixbottom(e);
				return true;
			}
		},
		*/
		".*":function(e,mode,lsd){
			if(mode=="end") {
				//console.log(lsd);
				MP._gi.hide();
				return true;
			}
		},
		"":function(e,mode){
			if(mode=="end") {
				MP._gi.hide();
				return true;
			}
		}
	},function(e,evpos){
		MP._gi.show(e,{top:evpos.pageY-24,left:evpos.pageX-24,width:48,height:48});
	},function(){
		MP._gi.hide();
	});
}

	logincheck(function onerror(type){
		G.removeClassName(document.body,"logined");
		G.addClassName(document.body,"notlogined");
		switch(type){
			case "notlogin":
			case "ng":
			case "error":
		}
		onnotlogin();
	});

});

function shorten_l(str,len){
	str=str.replace(/^\s+/,"").replace(/\s+/g," ");
	if(str.length+3>len){
		return str.substring(0,len)+"...";
	}
	return str;
}

function dohash(){
	if(MP._loginchecking){
		dohash.later(200);
		return;
	}
	top();
	G.removeClassName(G.$("manip"),"opened");
	G.addClassName(G.$("manip"),"closed");

	
	var bd=document.body,q="",uri=G.parseUri(location.href);

	G.removeClassName(bd,"myarchive");
	G.removeClassName(bd,"myentries");
	G.removeClassName(bd,"playlist");
	G.removeClassName(bd,"playlistall");
	if(location.hash.match("-playlist-")){
		G.addClassName(bd,"playlist");
		if(uri.hash.match(/-playlist-([^-]+)/)[1]=="all"){
			G.addClassName(bd,"playlistall");
		}
	}
	
	var qs=[],m,title;
	if(uri.hash.match(/^#?myarchive/)){
		if(!MP.login){
			login();
			return;
		}
		G.addClassName(bd,"myarchive");
		MP.pseudoClick("#myarchive-0,10@entries");
		qs=["アーカイブ"];
		G.setElementValues(G.$("title"),{title:qs.join(" - ")});
		qs.push("MODIPHI");
		document.title=qs.join(" - ");
		initfill();
		return;
	}else if(uri.hash.match(/^#?search-/)){
		q=G.unesc(uri.hash.match(/^#?search(.*)/)[1],"U");
		q=q.replace(/(#|%23)DEBUG$/,"");
		if(q.match(/-playlist-/)&&!MP.login){
			login();
			return;
		}
	}else if(uri.hash.match(/^#?myentries-/)){
			if(!MP.login){
				login();
				return;
			}
			G.addClassName(bd,"myentries"); // TODO
			var qt=uri.hash.match(/^#?myentries-(.*)(-title-(.*))?$/);
			q=G.unesc(qt[1],"U");
			//q=G.unesc(uri.hash.match(/^#?myentries-(.*)-title-(.*)/)[1],"U");
			q=q.replace(/(#|%23)DEBUG$/,"");
			//var t=uri.hash.match(/^#?myentries-(.*)-title-(.*)/)[2],"U");
			MP.pseudoClick("#myentries-"+q+"-0,10@entries");
			t=G.unesc(qt[3]||"","U");
			if(t){gs=[t];}// TODO title とってくる
			qs.push("作成したフィード");
			G.setElementValues(G.$("title"),{title:qs.join(" - ")});
			qs.push("MODIPHI");
			document.title=qs.join(" - ");
			initfill();
			return;
	}else{
		if(MP.login){
			location.hash="search-playlist-all";
			return;
		}else{
			if(G._DEBUG){
				q="";
			}else{
				location.href="index.html";
				return;
			}
		}
		//return;
	}

	MP.pseudoClick("#search"+q.replace(/-title-(.*)$/,"")+"-0,10@entries");

	if(m=q.match(/-title-(.*)$/)){
		qs.push(m[1]);
		G.setElementValues(G.$("title"),{title:qs.join(" - ")});
		qs.push("MODIPHI");
		document.title=qs.join(" - ");
		initfill();
		return;
	}
	if(m=q.match(/-global-(.*)/)){
		qs.push(m[1]);
		if(q.match(/-scope-subscribe-/)){
			qs.push("登録から検索");
		}else{
			qs.push("検索");
		}
	}
	if(m=q.match(/-playlist-([^\-]+)/)){
		var plid=m[1];
		switch(m[1]){
			case "all": qs.push("登録フィードすべて"); break;
			case "allwopl": qs.push("プレイリスト以外の登録フィード"); break;
			default: qs.push(MP.playlists[m[1]].name); qs.push("プレイリスト");
		}
		MP.style_plsb=G.setStyleSheet(".plsb-"+m[1]+",#playlist-"+m[1]+" { opacity:0.3; filter:alpha(opacity=30); } ",MP.style_plsb);
	}else{
		G.setStyleSheet("",MP.style_plsb);
	}
	if(m=q.match(/-category-([^-]+)/)){
		qs.push(m[1]); qs.push("タグ");
	}
	if(m=q.match(/-feed-([0-9,]+)/)){
		MP.getFeedsInfo(m[1].split(","), function(r){
			var titles = [];
			G.each(r, function(v){
				titles.push(v.title);
			});
			qs.push(shorten_l(titles.join(","),30));
			G.setElementValues(G.$("title"),{title:qs.join(" - ")});
			qs.push("MODIPHI");
			document.title=qs.join(" - ");
			MP.entries_full={};
			MP.feeds={};
			MP.cache.feeds.clear();
			MP.cache.entries.clear();
			MP.cache.entries_full.clear();
			initfill();
		});
	}else{
		G.setElementValues(G.$("title"),{title:qs.join(" - ")});
		qs.push("MODIPHI");
		document.title=qs.join(" - ");
		MP.entries_full={};
		MP.feeds={};
		MP.cache.feeds.clear();
		MP.cache.entries.clear();
		MP.cache.entries_full.clear();
		initfill();
	}
}


/*
setInterval(function(){
	if(!G.("manip")){return;}
	//G.("manip").style.top=document.documentElement.scrollTop+"px";
	G.("manip").style.top=window.scrollY+"px";
},100);
*/

function urlToLink(e){
	(function cl(e,dp){
		var c=e.firstChild;
		while(c){
			if(c.nodeType!=3){
				switch(c.tagName){
					case "A": case "a": case "IMG": case "img": case "FORM": case "form": case "INPUT": case "input":
						break;
					default:
						//arguments.callee.later(1,this,c);
						arguments.callee.call(this,c,dp+1);
				}
			}else{
				c.nodeValue=c.nodeValue.replace(/(^|[^a-z])(h?ttp)(s?)(:\/\/[-_.!~*a-zA-Z0-9;/?:@&=+$,%#]+)/gm,'$1___http$3$4___');
			}
			c=c.nextSibling
		}
		if(dp==0){
			e.innerHTML=e.innerHTML.replace(/___(https?:\/\/[-_.!~*a-zA-Z0-9;/?:@&=+$,%#]+)___/gm,"<a href=\"$1\" target=\"_blank\">$1</a>");
		}
	})(e,0);
}

function checkdescs(){
	if(G.isClass(document.body,"myarchive")||G.isClass(document.body,"myentries")){
		return;
	}
	//var li=MP.searchParentChildren(".entries",this)[0];
	var li=G.$SA(this,"li.entries");
	var d0=G.$S("div.descall",li)[0];
	var d1=G.$S("div.description",G.$("entry"))[0];
	var d2=G.$S("div.desc_follow_cont",G.$("entry"))[0];
	var df=d2,d=d1;
	d0=(d0.textContent||d0.innerText||"").replace(/\s+/g,"");
	d1=(d1.textContent||d1.innerText||"").replace(/\s+/g,"");
	d2=(d2.textContent||d2.innerText||"").replace(/\s+/g,"");
	
	G.addClassName(li,"processed");

	if(d2==""){
		G.addClassName(li,"nodescriptionfollow");
	}else{
		//urlToLink(df);
	}
	if(d1!=""){
		urlToLink(d);
		if(d2.indexOf(d1.substring(0,20))>=0){
			G.addClassName(li,"nodescription");
		}
	}else{
		G.addClassName(li,"nodescription");
	}
	//MP.entries_full={};
}

function cursornext(cname,e,f){
	f=f||function(e){MP.pseudoClick(e);}
	var e=e||MP.cursors[cname];
	if(!e||!e.parentNode){return;}
	e=e.nextSibling;
	while(e&&!G.isClass(e,"template-gen")){e=e.nextSibling;}
	if(!e){return;}
	if(G.isClass(e,"duplicate")){cursornext(cname,e,f);return;}
	f(G.$S(".entries-title a",e)[0]);
}

function cursorprev(cname,e){
	var e=e||MP.cursors[cname];
	if(!e||!e.parentNode){return;}
	e=e.previousSibling;
	while(e&&!G.isClass(e,"template-gen")){e=e.previousSibling;}
	if(!e){return;}
	if(G.isClass(e,"duplicate")){cursorprev(cname,e);return;}
	var n=G.$S(".entries-title a",e)[0];
	MP.pseudoClick(n);
}

var adjusttop=function(){
	adjusttop=function(){};
	if(window.scrollTop==0){
		window.scrollTo(1,0);window.scrollBy(-1,0);
	}
}

var checkLastShownEntry=function (){
	var lse=G.getCookie("LSE");
	if(lse){
		lse=lse.split("\t");
		if(lse[1]!=location.hash){G.clearCookie("LSE");checkLastShownEntry=function(){};}
		else if(G.$("entries-link-"+lse[0],true)){
			checkLastShownEntry=function(){};
			showentry.call(G.$("entries-link-"+lse[0]),lse[0],true);
		}
	}
}

function showentry(id,isSciv){
	MP.entries_full= {};
	MP.cache.entries_full.clear();
	G.setCookie("LSE",id+"\t"+location.hash);
	var cursor=MP.cursors["entries"];
	if(cursor&&cursor==this.parentNode){
		if(G.isClass(cursor,"opened")){
			G.removeClassName(cursor,"opened");
			G.addClassName(cursor,"closed");
			G.clearCookie("LSE");
		}else{
			G.removeClassName(cursor,"closed");
			G.addClassName(cursor,"opened");
		}
		return;
	}
	
	var orghref=this.href;
	
	var p1 = G.pos(cursor);
	G.removeClassName(cursor,"opened");
	G.addClassName(cursor,"closed");
	if(p1.top < G.getPageYOffset()) {
		var p2 = G.pos(cursor);
		//window.scrollBy(0,(p2.height-p1.height));
		(function(){
			window.scrollBy(0,(p2.height-p1.height));
		}).later();
	}
	
	G.$("entry-desc-out").innerHTML=G.$("entries-desc-"+id).innerHTML;
	
	MP.tmpl.entry&&MP.tmpl.entry.start();
	G.$S(".description",this.parentNode)[0].appendChild(G.$("entry"));
	
	var t=(G.isClass(document.body,"myarchive")||G.isClass(document.body,"myentries"))?"-myentry":"";
	this.href="#cursor-set-focused-entries@li&&entry-"+id+t+"@entry"+(!isSciv?"&&scrollintoview-.entries&&exec-movemanip":"");
	MP.pseudoClick(this);
	
	if(MP.login){
		G.$S(".plfs",G.$("entry"))[0].appendChild(G.$("plfsin-clone"));
	}
	
	G.removeClassName(this.parentNode,"closed");
	G.addClassName(this.parentNode,"opened");
	//movemanip.later(1000);
	(function(){this.href = orghref;}).later(1,this);
}

function reload(){
	window.scrollTo(0,0);
	//document.body.scrollIntoView();
	location.reload();
}

function top(){
	//G.$("head").scrollIntoView();
	window.scrollTo(0,0);
	movemanip.later(500);
}

function login(){
	location.href = MP.API+"../loginp?rt="+G.esc(location.href,"U")+"&mode=iphone";
}

function logout(){
	location.hash="";
	MP.doLogout(function(){
		location.reload();
	});
}

function feed(id){
	location.hash="search-feed-"+id;
	//document.title=MP.feeds[id].title+" - フィード - MODIPHI";
};

function playlist(id){
	location.hash="search-playlist-"+id;
	//document.title=MP.login.memo.mylists[id].name+" - プレイリスト - MODIPHI";
}

function myarchive(){
	location.hash="myarchive";
}

function search(q,sc){
	if(this.tagName&&this.tagName.match(/^(a|form)$/i)){
		var a=Array.prototype.slice.call(arguments,0);
		var w=G.esc(G.$("search-global").value,"U");
		a.push("global"); a.push(w);
		q=a.join("-");
	}else{
		var w=q;
		q="global-"+G.esc(q,"U")+(sc?("-"+sc):"");
	}
	location.hash="search-"+q;
	/*
	if(!w||w==""){
		document.title="すべて - MODIPHI";
	}
	document.title=w+" - 検索 - MODIPHI";
	*/
}

function initfill(){
	var timer=setInterval(function(){
		if(!MP.tmpl.entries||MP.tmpl.entries.busy){return;}
		//if(G.isClass(G.$("entries"),"hasnext")&&(G.getPageYOffset()+G.clientSize().height+400>G.pos(G.$("footer")).bottom)){
		if(G.isClass(G.$("entries"),"hasnext")&&(G.getPageYOffset()+G.clientSize().height+100>G.pos(G.$("footer")).bottom)){
			if(G.isClass(document.body,"myarchive")||G.isClass(document.body,"myentries")){
				MP.pseudoClick("#myentries-append@entries");
			}else{
				MP.pseudoClick("#search-append@entries");
			}
		}else{
			clearInterval(timer);
		}
	},100);
}

// function initfill() {}

function archiveentry(id){
	if(!MP.myarchives){MP.getMyArchives();}
	if(!MP.entries_full[id]){
		/* 想定としてはここにはこないはず */
		archiveentry.bindArgs(id).poll(function(){
			return MP.entries_full[id];
		});
		MP.pseudoClick("#entry-"+id+"@fordescread");
		return;
	}/*else if(MP.cache.entries_full.get(id)){
		archiveentry.bindArgs(id).poll(function(){
			return MP.cache.entries_full.get(id);
		});
		MP.pseudoClick("#entry-"+id+"@fordescread");
		return;
	}*/
	G.setwait();
	(function(){
		var entry=MP.entries_full[id] || MP.cache.entries_full.get(id);
		var newentry={};
		newentry.title=entry.title;
		newentry.category=entry.categories.split("\t");
		newentry.expire_date="2050-01-01 00:00:00";
		newentry.source=entry.title;
		newentry.source_url=entry.link;
		newentry.author=entry.author;
		var d=entry.description;
		if(entry.description_follow){
			d="<blockquote>"+entry.description+"</blockquote>" + entry.description_follow;
		}
		var memo=prompt("アーカイブ用のメモ");
		if(memo){memo="<p>"+G.esc(memo)+"</p>"}else{memo=""}
		newentry.description=
			memo
			+"<h3><a href=\""+G.esc(entry.link,"A")+"\">"
			+G.esc(entry.title)
			+"</a> からアーカイブ</h3>"
			+"<blockquote>"+d+"</blockquote>";
		G.each(MP.myarchives,function(v,p){
			newentry.channel_id=p;
		});
		MP.doModiphi("item/registNewItem",newentry,function(r){
			if(r.ERR){
				CONSOLE.error("#archive:"+G.dump(r.ERR));
				alert("サーバーエラー\n"+G.dump(r.ERR));
				G.clearwait();
				return;
			}
			if(r.NGS){
				CONSOLE.error("#archive:"+G.dump(r.NGS));
				alert("エラー\n"+G.dump(r.NGS));
				G.clearwait();
				return;
			}
			//onupdatearchive();
			alert("アーカイブに保存しました");
			G.clearwait();
		},function(){
			alert("サーバーエラー");
			G.clearwait();
		},false);
	}).poll(function(){return !MP.myarchives._initializing;});
}

function plsb(plid,url){
	url=url||MP.showingEntry.channel_rss_url;
	
	if(plid=="delete"){
		var plid=location.href.match("-playlist-([^-]+)")[1];
		var cid=MP.showingEntry.channel_id;
		if(plid=="all"){
			if(confirm("「"+MP.showingEntry.channel_title+"」を登録フィードとすべてのプレイリストから削除しますか？")){
				MP.unsubscribeChannel(cid,function(msg){
					alert("削除しました");
					location.reload();
					// reload?
				},function(msg){
					alert(msg);
				});
			}
		}else{
			var list=null;
			G.each(MP.login.memo.mylists,function(v,i){
				if(v.id==plid){list=v;return true;}
			});
			if(!list){alert("プレイリストが見つかりません");return}
			if(confirm("「"+MP.showingEntry.channel_title+"」をプレイリスト「"+list.name+"」から削除しますか？")){
				MP.unsubscribeFromPl(plid,cid,function(msg){alert(msg)},function(msg){alert(msg);});
			}
		}
		return;
	}
	
	MP.subscribeChannelAndPl(url,plid,function(msg){
		genplaylists(); alert(msg);
	},function(msg){
		alert(msg);
	});
	return;
	
	MP.subscribeChannel(url,function(r){
		var cid=r[0].channel_id;
		if(plid=="new"){
			var np=prompt("新規プレイリスト名");
			if(!np){return;}
			var nid=0;
			G.each(MP.login.memo.mylists,function(v){
				nid=Math.max(nid,G.atoi(v.id)+1);
			});
			MP.login.memo.mylists.push({id:nid,name:np,channel_id:[cid]});
			MP.saveUserMemo();
			genplaylists();
			alert("プレイリスト「"+np+"」に登録しました");
			return;
		}
		if(plid!="all"){
			var pl=MP.playlists[plid];
			if(pl===undefined){
				alert("プレイリストがありません");
			}else{
				if(!pl.channel_id instanceof Array){
					pl.channel_id=[pl.channel_id];
				}
				if((" "+pl.channel_id.join(" ")+" ").indexOf(" "+cid+" ")<0){
					pl.channel_id.push(cid);
					MP.saveUserMemo();
					genplaylists();
					alert("プレイリスト「"+pl.name+"」に登録しました");
					return;
				}else{
					alert("プレイリスト「"+pl.name+"」に登録済みです");
					return;
				}
			}
		}
		alert("登録フィードに登録しました");
	},function err(e,type,r){
		switch(type){
			case "notavailable":
			case "connectionerror":
			case "evalerror":
			case "resulterr":
				break;
			case "resultng":
				if(r.RESULTS&&r.RESULTS[0].channel_id){
					if(plid!="all"&&plid!="allwopl"){
						var cid=r.RESULTS[0].channel_id,pl=MP.playlists[plid];
						if(plid=="new"){
							var np=prompt("新規プレイリスト名");
							if(!np){return;}
							var nid=0;
							G.each(MP.login.memo.mylists,function(v){
								nid=Math.max(nid,G.atoi(v.id)+1);
							});
							MP.login.memo.mylists.push({id:nid,name:np,channel_id:[cid]});
							MP.saveUserMemo();
							genplaylists();
							alert("プレイリスト「"+np+"」に登録しました");
							return;
						}
						if(pl===undefined){
							alert("プレイリストがありません");
						}else{
							if(!pl.channel_id instanceof Array){
								pl.channel_id=[pl.channel_id];
							}
							if((" "+pl.channel_id.join(" ")+" ").indexOf(" "+cid+" ")<0){
								pl.channel_id.push(cid);
								MP.saveUserMemo();
								genplaylists();
								alert("プレイリスト「"+pl.name+"」に登録しました");
								return;
							}else{
								alert("プレイリスト「"+pl.name+"」に登録済みです");
								return;
							}
						}
					}
					//alert("登録フィードに登録しました");
					return;
				}
		}
		alert(G.dump(e));
	});
}

/* for SMART : see smart/ip/js/postbox.js */
function sm_doPostLog(form, override){
	if(!form){ return; }
	var v;
	if (form.appendChild){
		v = G.getElementValues(form);
	} else {
		v = form;
	}
	if(override){
		G.each(override, function(p,v){
			v[p] = v;
		});
	}
	if(v.dest == ""){
		return;
	}
	if(v.log_text && v.log_text.length >= 140){
		alert("140文字までです");
		return;
	}
	SMART.post(form, function(){
		if (form.appendChild){
			form.parentNode.style.display="none";
			form.reset();
		}
		//location.reload();
		alert("投稿しました");
	});
}
function sm_popupPost(name, defvalues){
	var elem = G.$(name);
	if(defvalues){
		G.setElementValues(elem, defvalues);
	}
	sm_popupPost._evs = sm_popupPost._evs || {}
	if (!sm_popupPost._evs[name]) {
		G.each(["textInput", "keypress"],function(evname){
			G.addEvent(elem, evname, function(ev){
				ev = G.parseEvent(ev);
				G.$S(".count", ev.target.parentNode)[0].innerHTML = 140 - ev.target.value.length;
			});
		});
		sm_popupPost._evs[name] = true;
	}
	elem.style.display="block";
	elem.style.top = G.getPageYOffset() + "px";
	G.$S("textarea", elem)[0].focus.later(100);
}
function do_smart(mode, ref, title) {
	if (typeof SMART == "undefined") {
		do_smart.later(100,null,mode,ref,title);
		return;
	}
	if (mode=="good") {
		SMART.post({log_type:"comment", ref:ref, dest:"__my_sphere"}, function(){
			alert("SMARTに評価ログを追加しました");
		});
	} else if (mode=="comment") {
		sm_popupPost("smart_postbox",{message:"SMARTにコメントを追加：", log_type:"comment", ref:ref, dest:"__my_sphere"});
	}
}
