/*
 * ----アイディア
 * <a href="#cmd@target"></a> で動作？
 * #entry-<itemid>,#feed-<channelid>,#favsearch-?,#favfeed-?
 * #edit-<itemid>,#quote-<itemid>
 * 対象はどうする？
 * #entry-<itemid>@test -> id=testを対象にentryを表示?
 * 
 * お気に入りパーツ？タブにまでする？
 * <script id="hogehoge" src="parts.js?id=hogehoge&u=member_id&w=180&h=200&s=modiphi></script>
 * 
 * <a href="..." class="autodo"></a>をどこかのタイミングで自動展開する？
 * 
 * ------- 現仕様
 * 
 * <a href="#CMD-ARG@TARGETTMPL">some node</a>
 * TARGETTMPLのidを持つ要素に対して、CMD-ARGを実行し、テンプレート適用。
 *                       :
 *  <div id="TARGETTMPL">entry description:<div class="template">${description}</div></div>
 *                       :
 *                       
 * #entry-<entryid>@TMPL
 * #feed-<feedid>@TMPL
 * #feed-<feedid1,feedid2,...>@TMPL
 * #category-<CATEGORY>@TMPL
 * 
 * 
 */

if(typeof MP=="undefined"){

var MP={
	version:"$Revision: 1.14 $".split(":")[1].match(/^\s*(.*)\s*\$$/)[1],
	_loadstatus:"init",

	onload:function(f){
		if(MP.initialized){
			MP.setOnLoadHtml(f);
		}else{
			setTimeout(function(){
				MP.onload(f);
			},50);
		}
	},

	tmpl:{},          // templates[tmplid]
	search:{},        // 検索条件値  [tmplid]={offset,limit,cont,dq:{...},disp:{...}}

	feeds:{},         // channel/getFeeds results [channel_id]
	entries:{},       // item/search results [item_id]
	entries_full:{},  // item/getItem results [item_id]

	tabs:{__cnt:0},    // tabs[tabid]
	parts:{__cnt:0},   // parts[partsid]
	windows:{__cnt:0}, // windows[windowid]
	wizards:{__cnt:0}  // wizards[wizardid]
};

MP.setOnLoadHtml=function(f){

	if(MP.setOnLoadHtml._loaded){
		window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:already loaded:"+f);
		f();
		return;
	}

	var isWebkit=(navigator.appVersion.indexOf("AppleWebkit")>-1);
	var isMSIE=/*@cc_on!@*/false;
	if(document.readyState&&isWebkit){
		window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:Webkit:waiting readyState");
		function waitfunc(){
			switch(document.readyState){
				case "loaded": case "complete":
					CONSOLE.info("MP.setOnLoadHtml:DOM load complete:Webkit");
					f(); break;
				default:
					setTimeout(waitfunc,50);
			}
		}
		waitfunc();
	}else if(document.readyState&&isMSIE){
		/*
		window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:IE:waiting doScroll enable");
		(function(){
			try{
				// throws errors until after ondocumentready
				document.documentElement.doScroll('left');
			} catch (e) {
				setTimeout(arguments.callee, 50);
				return;
			}
			window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:DOM load complete:IE");
			f();
		})();
		*/
		
		window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:IE:waiting behavior");
		/* http://www.nabble.com/Re%3A-document.ready-firing-too-early-within-iframe-p13376590s27240.html */
		//MP._IECheck;
		function IEContentLoaded(w,f){
		    // document has loaded (IE method 2) using behavior
		    var load=false,d=w.document,s=d.createStyleSheet().owningElement;
		    s.styleSheet.cssText='body{behavior:expression(MP._IECheck(this));}';
		    var fire=function(e){
				if(!load){
					window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:IE:done");
					load=true;f.call(d,e);
					setTimeout(function(){
						s.parentNode.removeChild(s);
					},10);
				}
			};
			MP._IECheck=function(n){
				window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:IE:behavior enabled");
				try{
					d.documentElement.doScroll('left');
					n.runtimeStyle.behavior='none';
					window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:IE:doScroll enabled,disable behavior");
				}catch(e){return;}
				fire(null);
			};
			//d.attachEvent("onload",fire);
		}
		if(!MP.setOnLoadHtml._fs){
			MP.setOnLoadHtml._fs=[f];
			IEContentLoaded(window,function(){while(MP.setOnLoadHtml._fs[0]){
				(MP.setOnLoadHtml._fs.shift())();
			}});
		}else{
			MP.setOnLoadHtml._fs.push(f);
		}
	}else{
		if(window.addEventListener){
			window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:use DOMContentLoaded");
			window.addEventListener("DOMContentLoaded",f,false);
			//document.addEventListener("load",f,false);
		}else if(window.attachEvent){
			window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:use attachEvent onload");
			window.attachEvent("onload",f);
		}else{
			window.CONSOLE&&CONSOLE.info("MP.setOnLoadHtml:use window.onload");
			var f2=MP.setOnLoadHtml._f||(function(){MP.setOnLoadHtml._loaded;});
			window.onload=function(){
				f2();
				f&&f();
			}
		}
	}
};
MP.setOnLoadHtml._f=function(){};
MP.setOnLoadHtml(function(){
	MP.setOnLoadHtml._loaded=true;
});

(function (MP){

function each(o, func) { var i,l;
	if(o===null||o===undefined){return;}
	if ("length" in o && "item" in o) { for (i=0,l=o.length; i<l; i++){ if(func(o.item(i),i,o)){break;}} }
	else if ("length" in o) { for(i=0,l=o.length;i<l;i++) { if(func(o[i],i,o)){break;}} }
	else { for (var p in o) { if(func(o[p],p,o)){break;}} }
	return o;
}

function requireJs(p,c,f,onload,onerror,id) {
	if (requireJs._i===false){
		requireJs._i={}; var ss=document.getElementsByTagName("script");
		each(ss,function(s,i){if (s.src){/*CONSOLE.info(s.src + " is already preloaded")*/;requireJs._i[s.src]=true;}});
	}
	/*if(p.match(/^https?:/)||p.indexOf("/")===0) {} else {p=_BASEPATH+p;}*/
	if (!f&&(p in requireJs._i)){return;}
	var s=document.createElement("script"); s.type="text/javascript";s.charset=(c||"UTF-8");
	if(onload){
		s.onload=(function(s,onload){return function(){
//alert("requirejs onload")
			onload(s);
		}})(s,onload);
		s.onreadystatechange=(function(s,onload){
			return function(){
				if(s.readyState==4){
//alert("requirejs onload / readystatechante 4 ");
					try{onload(s);}finally{s.onreadystatechange=null;s.onload=null;s.parentNode.removeElement(s);}
				}
			};
		})(s,onload);
	}
	if(onerror){
		s.onabort=(function(s,onerror){return function(){onerror(s);}})(s,onerror);
		s.onerror=(function(s,onerror){return function(){onerror(s);}})(s,onerror);
	}
	s.src=p;
	if(!id===undefined){s.id=id;}
	requireJs._i[s.src]=true; /*CONSOLE.info(p+" required");*/
	document.getElementsByTagName("head")[0].appendChild(s);
	return s;
};
requireJs._i = false;

function requireBaseJs(){

	var me;
	var s=document.getElementsByTagName("script");
	for (var i=s.length-1; i>=0; i--){
		if(s[i].src){
			if (s[i].src.split("?")[0].split("/").pop()=="parts.js"){
				me=s[i]; break;
			}
		}
	}
	if (!me){throw new Error("<script src='base.js' /> is not found."+"\n"+document.getElementsByTagName("head")[0].innerHTML);}
	
	var m=me.src.match(/^(.*\/)?parts.js(\?.*)?$/);
	var _BASEPATH=m[1]||"";
	if (_BASEPATH!=""){_BASEPATH+="";}
	MP._BASEPATH=_BASEPATH;
	
	requireJs(_BASEPATH+"base.js","utf-8",true);
	
}

MP._loadstatus="waiting";

function waitinitmp(){
	switch(MP._loadstatus){
		case "waiting":
			if(typeof G=="undefined"){
				MP._loadstatus="waiting base.js";
				requireBaseJs();
				clearTimeout(MP._wait);
				MP._wait=setTimeout(function(){waitinitmp();},200);
				break;
			}
		case "waiting base.js":
			if(typeof G=="undefined"||!G.initialized){
				clearTimeout(MP._wait);
				MP._wait=setTimeout(function(){waitinitmp();},200);
				break;
			}
			MP._loadstatus="initializing";
			initmp(MP);
			MP._loadstatus="complete";
			delete MP._wait;
			break;
		default:
			clearTimeout(MP._wait);
			MP._wait=setTimeout(function(){waitinitmp();},200);
	}
}
waitinitmp();

function initmp(MP){

if(initmp._initializing){
	
	return;
}
initmp._initializing=true;

CONSOLE.log("parts.js:init:start");

/*
if(G.isMSIE){
	try{
		document.execCommand("BackgroundImageCache", false, true);
	}catch(ex){}
}
*/

var _API;
if (G._DEBUG) {
	_API="http://www.modiphi.com/mf/cmd/";
	var href=G.parseUri(location.href);
	if(href.params.api){
		_API=href.params.api;
	}
} else {
//	_API=G._BASEPATH+"../mf/cmd/";   // parts.js location
//	_API="/mf/cmd/";                 // html location

	var uri=G.parseUri(G._BASEPATH);
	uri.path="/mf/cmd/";
	_API=uri.toString();
}
var _API_HOSTNAME=G.parseUri(_API).hostname||location.hostname;

CONSOLE.info("parts.js:API:"+_API);

MP.API=_API;

var pk=G.parseUri(location.href).params["pk"]||G.getCookie("RK");
if(pk){
	MP.postkey=pk;
}
MP.lid=(G.getCookie("MF")||G.getCookie("MFS")||"").split("/")[0];

G.requireCss("parts.css");

function loginCheck(f,onnotlogin,onng,onerror){
	MP.doModiphi("member/loginCheck",null,function(r){
		if(r.isLogin){
			f&&f(r);
		}else{
			onnotlogin&&onnotlogin(r);
		}
	},function(err,mode){
		switch(mode){
			case "resultng": onng&&onng(err); break;
			case "resulterr": onerror&&onerror(err,mode); break;
			default:onerror&&onerror(err,mode);
		}
	},false);
}
MP.loginCheck=loginCheck;

var INITMEMO={
	//entriessort:"entries-date-desc",
	//entryImgOff:false,
	//entrymode:"entry-mode-nofollow",
	//fontsize:"fontsize-m",
	reader_init:"playlist-all",
	lastReadEntryTime:1,
	mylists:[]
};

function getUserInfo(f,notlogin,onng,onerror){
	//function loginCheck(f,onnotlogin,onng,onerror){
	MP.loginCheck(function(){
		MP.doModiphi("member/info",null,function(r){
			MP.login=r.RESULTS[0];
			MP.login.memo=MP.login.memo||INITMEMO;
			if(typeof MP.login.memo=="string"){
				try{
					MP.login.memo=eval("("+MP.login.memo+")");
				}catch(ex){
					CONSOLE.error("getUserInfo:memo:"+G.dump(ex));
					MP.login.memo=INITMEMO;
				}
			}
			MP.lastReadEntryTime=MP.login.memo.lastReadEntryTime;
			f(r.RESULTS[0]);
		},function(err,mode){
			switch(mode){
				case "resultng": onng&&onng(err); break;
				case "resulterr": onerror&&onerror(err,mode); break;
				default:onerror&&onerror(err,mode);
			}
		},false);
	},notlogin,onng,onerror);
}
MP.getUserInfo=getUserInfo;

function setMemberId(s){
	(function(){
		(G.$(s,true)||G.$S(s)[0]).innerHTML=G.esc(MP.login.member_id);
	}).poll(function(){
		return MP.login&&(G.$(s,true)||G.$S(s)[0]);
	},1000);
}
MP.setMemberId=setMemberId;

function saveUserMemo(f){
	if(!MP.login){return;}
	MP.doModiphi("member/updateMemo",{memo:G.toJSON(MP.login.memo)},f,null,false);
}
MP.saveUserMemo=saveUserMemo;

function doLogin(v,f,onng,onerror){
	MP.doModiphi("member/login",v,function(r){
		MP.postkey=r.postkey;
		G.setCookie("RK",r.postkey); // 別サイトでも通るけど…
		f();
	},function(err,mode){
		switch(mode){
			case "resultng": onng&&onng(err); break;
			case "resulterr": onerror&&onerror(err,mode); break;
			default: onerror&&onerror(err,mode);
		}
	},false);
}
MP.doLogin=doLogin;

function doLogout(f,onerror){
	MP.doModiphi("member/logout",null,function(){
		delete MP.postkey;
		delete MP.login;
		G.clearCookie("RK");
		f&&f();
	},onerror,false);
}
MP.doLogout=doLogout;

function getMyArchives(f,e,offset,limit){
	offset=offset||0;limit=limit||10;
	if(offset==0){MP.myarchives={"_initializing":true};}
	MP.doModiphi("channel/getMyChannelList",{offset:offset,limit:limit,channel_group:2},(function(r){
		if(r.NGS){
			CONSOLE.error("getMyArchives:"+G.dump(r.NGS));
			this.e&&this.e(r.NGS);
		}else if(r.ERR){
			CONSOLE.error("getMyArchives:"+G.dump(r.ERR));
			this.e&&this.e(r.ERR);
		}else{
			G.each(r.RESULTS,function(v){
				MP.myarchives[v.channel_id]=v;
			});
			if(r.RESULTS.length<this.limit||r.RESULTS.length==0){
				delete MP.myarchives._initializing;
				this.f&&this.f(MP.myarchives);
			}else{
				getMyArchives.later(100,this.f,this.e,this.offset+this.limit,this.limit);
			}
		}
	}).bindThis({offset:offset,limit:limit,f:f,e:e}),null,false);
}
MP.getMyArchives=getMyArchives;

function getMyChannels(offset,limit,f,e){
	offset=offset||0;limit=limit||10;
	if(offset==0){MP.mychannels={"_initializing":true};}
	MP.doModiphi("channel/getMyChannelList",{offset:offset,limit:limit},(function(r){
		if(r.NGS){
			CONSOLE.error("getMyChannels:"+G.dump(r.NGS));
			this.e&&this.e(r.NGS);
		}else if(r.ERR){
			CONSOLE.error("getMyChannels:"+G.dump(r.ERR));
			this.e&&this.e(r.ERR);
		}else{
			G.each(r.RESULTS,function(v){
				MP.mychannels[v.channel_id]=v;
			});
			if(r.RESULTS.length<this.limit||r.RESULTS.length==0){
				delete MP.mychannels._initializing;
				this.f&&this.f();
			}else{
				getMyChannels.later(100,this,this.offset+10,this.limit,this.f,this.e);
			}
		}
	}).bindThis({offset:offset,limit:lmit,f:f,e:e}),e,false);
}
MP.getMyChannels=getMyChannels;

function getMySubscribedChannels(offset,limit,f,e){
	offset=offset||0;limit=limit||10;
	if(offset==0){MP.mysubscribedchannels={"_initializing":true};}
	MP.doModiphi("subscribe/getSubscribeChannelList",{offset:offset,limit:limit},(function(r){
		if(r.NGS){
			CONSOLE.error("getMySubscribedChannels:"+G.dump(r.NGS));
			this.e&&this.e(r.NGS);
		}else if(r.ERR){
			CONSOLE.error("getMySubscribedChannels:"+G.dump(r.ERR));
			this.e&&this.e(r.ERR);
		}else{
			G.each(r.RESULTS,function(v){
				MP.mysubscribedchannels[v.channel_id]=v;
			});
			if(r.RESULTS.length<this.limit||r.RESULTS.length==0){
				delete MP.mysubscribedchannels._initializing;
				this.f&&this.f();
			}else{
				getMySubscribedChannels.later(100,this,this.offset+10,this.limit,this.f,this.e);
			}
		}
	}).bindThis({offset:offset,limit:limit,f:f,e:e}),e,false);
}
MP.getMySubscribedChannels=getMySubscribedChannels;

function subscribeChannel(url,f,e){
	MP.doModiphi("subscribe/registNewSubscribeChannel",{url:url},function(r){
		if(r.NGS){
			CONSOLE.error("subscribeChannel:"+url+":"+G.dump(r.NGS));
			alert(r.NGS.url);
			this.e&&this.e(r.NGS);
		}else if(r.ERR){
			CONSOLE.error("subscribeChannel:"+G.dump(r.ERR));
			alert("サーバエラー:\n"+G.dump(r.ERR));
			this.e&&this.e(r.ERR);
		}else{
			f&&f(r.RESULTS);
		}
	},e,false);
}
MP.subscribeChannel=subscribeChannel;

function unsubscribeChannel(channel_id,f,e){
	MP.doModiphi("subscribe/deleteSubscribeChannel",{channel_id:channel_id},function(r){
		if(r.NGS){
			CONSOLE.error("unsubscribeChannel:"+url+":"+G.dump(r.NGS));
			this.e&&this.e(r.NGS);
		}else if(r.ERR){
			CONSOLE.error("unsubscribeChannel:"+G.dump(r.ERR));
			this.e&&this.e(r.ERR);
		}else{
			f&&f(r.RESULTS);
		}
	},e,false);
}
MP.unsubscribeChannel;

function checkLastReadTime(date){
	if(!MP.login){return;}
	date=(date||new Date()).valueOf();
	if(MP.login.memo.lastReadEntryTime<date){
		MP.login.memo.lastReadEntryTime=date;
		saveUserMemo();
	}
}

/**
 * 
 * @param {Object} path
 * @param {Object} param array or object for post param
 * @param {function} f async func() (if null, sync)
 * @param {function} onerror func() : txt,"evalerror" / NGS,"resultng" / ERR,"reulterr" / txt,"connectionerror"
 * @param {boolean} uc use cache (default true)
 */
function doModiphi(path,param,f,onerror,uc){
	if(doModiphi._cnt>10){
		//doModiphi.bindArgs(path,param,f,onerror,uc).later(200);
		//doModiphi.later(200,this,path,param,f,onerror,uc);
		doModiphi.later.apply(this,[200,this].concat([].slice.apply(arguments)));
		//arguments.callee.later.apply(arguments.callee,[200,this].concat([].slice.apply(arguments)));
		return;
	}
	doModiphi._cnt++;

	if(uc===undefined){uc=true;}

	if(MP.postkey){
		if(param===undefined||param===null){param={}}
		if(param.push){param.push({"postkey":MP.postkey})}else{param["postkey"]=MP.postkey;}
	}

	if(!MP.netCache){MP.netCache=new G.Cache(10);}
	var cachekey,cached;
	if(uc){
		cachekey=path+"?"+G.toJSON(param);
		cached=MP.netCache.get(cachekey);
		if(cached!==undefined){
			doModiphi._cnt--;
			CONSOLE.log("doModiphi:use cached:"+cachekey);
			if(f){
				//f.bindArgs(cached).later();
				f.later(1,this,cached);
			}
			return cached;
		}
		//CONSOLE.log("doModiphi():cache not found:"+cachekey);
	}else{
		//path=path+"?"+(new Date()).valueOf(); // for Safari
	}
	
	var conerror=(function(v,httpst,reqorelm,ex){
		doModiphi._cnt--;
		CONSOLE.error("doModiphi:connection error:"+this.path+":"+v);
		this.e&&this.e(v,"connectionerror");
	}).bindThis({e:onerror,path:path});
	function doModiphiResult(txt,res){
		doModiphi._cnt--;
		var o;
		try{eval("var o="+txt)}
		catch(ex){
			CONSOLE.error("doModiphiResult:"+this.path+":eval:"+txt);
			alert("サーバー応答エラー:eval\n"+txt);
			this.onerror&&this.onerror(txt,"evalerror");
			return;
		};
		/*
		if(o.DENIAL){
			CONSOLE.error("doModiphiResult:DENIAL"+G.dump(o));
			//alert("ログイン状態が解除されました");
			//location.reload();
			//return;
		}*/
		if(o.NGS){
			CONSOLE.error("doModiphiResult:"+this.path+":"+G.dump(o.NGS));
			//alert("サーバー応答エラー:result\n"+G.dump(o.NGS));
			this.onerror&&this.onerror(o.NGS,"resultng");
			return;
		}
		if(o.ERR){
			CONSOLE.error("doModiphiResult:"+this.path+":"+G.dump(o.ERR));
			//alert("サーバー応答エラー:result\n"+G.dump(o.NGS));
			this.onerror&&this.onerror(o.ERR,"resulterr");
			return;
		}
		if(this.cachekey){
			//CONSOLE.log("doModiphiResult():set cache:"+this.cachekey);
			MP.netCache.set(this.cachekey,o);
		}
		if(this.lender){this.lender(o);}
	}
	var f1=doModiphiResult.bindThis({lender:f,cachekey:cachekey,onerror:onerror,path:path});
	
	function doModiphiJSONPResult(o){
		doModiphi._cnt--;
		if(this.cachekey){
			//CONSOLE.log("doModiphiResult():set cache:"+this.cachekey);
			MP.netCache.set(this.cachekey,o);
		}
		if(o.NGS){
			CONSOLE.error("doModiphiJSONPResult:"+G.dump(o.NGS));
			//alert("サーバー応答エラー:result\n"+.dump(o.NGS));
			this.onerror&&this.onerror(o.NGS,"resultng");
			return;
		}
		if(o.ERR){
			CONSOLE.error("doModiphiJSONPResult:"+this.path+":"+G.dump(o.ERR));
			//alert("サーバー応答エラー:result\n"+G.dump(o.NGS));
			this.onerror&&this.onerror(o.ERR,"resulterr");
			return;
		}
		if(this.lender){this.lender(o);}
	}
	var f2=doModiphiJSONPResult.bindThis({lender:f,cachekey:cachekey,onerror:onerror});
	
	var api=_API;
	/*
	 * http: and https: is other site for xhr
	 * idea... httpsなiframeを作って、ifr-xhrなhash connection?
	switch(path){
		case "member/login":
		//case "member/logout":
		//case "member/loginCheck":
		//case "member/info":
		case "member/update":
		case "member/updatePasswd":
		//case "member/updateMemo":
		case "member/passwdConfirm":
		case "member/contactTypeOrder":
			api=api.replace(/^http:/,"https:");
	}
	*/
	
	if(location.hostname==_API_HOSTNAME){
		var aj=new G.Ajax();
		return aj.post(api+path,param,f1,conerror);
	}else{
		var jp=new G.JSONPCall();
		jp.send(api+path+".jsonp?_callback=${callbackname}&${params}",param,f2,conerror);
	}
	
}
doModiphi._cnt=0;
MP.doModiphi=doModiphi;

function aod2research(){
	with (LXSAOD2) {
		while(feeders[0]){feeders.shift().remove();}
		var _self=LXSAOD2;
		if(_self._tpl===undefined){
			var tpl=false;
			var $$script=$$('#__lxs_aod2');
			if($$script.length){
				var src=$$script.attr('src');
				var ret=new RegExp('tpl=([^&]*)&').exec(src+'&');
				if(ret)tpl=RegExp.$1;
				var ret=new RegExp('plg=([^&]*)&').exec(src+'&');
				if(ret){
					var plugins=RegExp.$1.split(',');
					for(var i=0;i<plugins.length;i++){
						var plugin=$$.trim(plugins[i]).toLowerCase();
						if(plugin)LXSAOD2.loadScript('/js/'+plugin+'.js')
					}
				}
			}
			if(tpl){
				loadStyle('/feeder'+tpl+".css");
			}
			_self._tpl=tpl;
		}
		var tpl=_self._tpl;
		if(tpl){
			var template='feeder'+tpl;
			var url='/helper/gettemplate.php?template='+template;
			var jsr=new JSONScriptRequest();
			jsr.send(base_uri+url,function(json){
				if(json.status=='ok'){
					//loadStyle('/'+template+'.css');
					_self.html=json.html
				}
				$$('a.AOD2').each(function(){
					if(this.rev!='tag')return;
					feeders[feeders.length]=new Feeder(feeders.length,this)
				});
				$$('q.AOD2').each(function(){
					feeders[feeders.length]=new Feeder(feeders.length,this)
				})
			})
		}else{
			$$('a.AOD2').each(function(){
				if(this.rev!='tag')return;
				feeders[feeders.length]=new Feeder(feeders.length,this)
			});
			$$('q.AOD2').each(function(){
				feeders[feeders.length]=new Feeder(feeders.length,this)
			})
		}
		var url='/helper/load.php';
		var params={'url':document.location,'ref':document.referrer};
		var pos=getCookie(position);
		if(pos)params.pos=pos;
		var sess=getCookie(session);
		if(sess)params[session]=sess;
		url+='?'+$$.param(params);
		var jsr2=new JSONScriptRequest();
		jsr2.send(base_uri+url,function(json){
			if(json.status=='ok'){
				setCookie(_self.session,json.session,'','/')
			}
		});
	}
}

function getUserTZDate(pubdatestr){ /* "YYYY-MM-dd HH:mm:ss" UTC to Date()*/
	//var TZ=G.atoi("+9",0);
	var TZ=9;
	if(MP.login){
		TZ=G.atoi(MP.login.timezone,9);
	}
	return new Date((new Date(pubdatestr.split("-").join("/")).valueOf())+TZ*60*60*1000);
}
MP.getUserTZDate=getUserTZDate;

function getUserTZDateStr(orgstr,now){
	now=now||(new Date()).format("%Y/,%m/%d ,%H:%M").split(",");
	try{
		var pdl=getUserTZDate(orgstr).format("%Y/,%m/%d ,%H:%M").split(",");
		if(now[0]==pdl[0]){
			pdl[0]="";
			if(now[1]==pdl[1]){pdl[1]=""}
		}
		return pdl.join("");
	}catch(ex){
		CONSOLE.error("getUserTZDateStr():invalid datetime:"+orgstr);
		return orgstr;
	}
}
MP.getUserTZDateStr=getUserTZDateStr;

function getFeedsInfo(cid,f){
	if(! this.cid instanceof Array){
		this.cid=[cid];
	}
	MP.doModiphi("channel/search",{
		qj: G.toJSON({channel_id: cid})
	},(function(o){
		var ret=[],results=[];
		G.each(o.RESULTS,function(v){
			MP.feeds[v.channel_id]=v;
			ret.push(v.channel_id);
			results.push(v);
		});
		this.cid=this.cid.sort();
		ret=ret.sort();
		var i=0;
		while(ret[0]){
			if(ret[0]==this.cid[i]){
				ret.shift(); this.cid.splice(i,1);
			}else{
				i++;
			}
		}
		this.results=results;
		this.results._rest=this.cid.length;
		while(this.cid.length>0){
			var cid=this.cid.shift();
			MP.doModiphi("channel/getMyChannel",{channel_id: cid},(function(r){
				if(r.RESULTS.length==2){
					if(r.RESULTS[0].n2_flg==1){
						r.RESULTS[0]._channelobj_n2=r.RESULTS.pop();
					}else if(r.RESULTS[0].n3_flg==1){
						r.RESULTS[0]._channelobj_n3=r.RESULTS.pop();
					}
				}
				this.results.push(r.RESULTS[0]);
				this.results._rest--;
			}).bindThis(this),false);
		}
		(function(){
			delete this.results._rest;
			this.f&&this.f(results);
		}).bindThis(this).poll((function(){
			return this.results._rest==0;
		}).bindThis(this));
	}).bindThis({f:f,cid:cid}),false);
	/*
	doModiphi("channel/getChannelList",{channel_id:cid},(function(o){
		G.each(o.RESULTS,function(v){
			MP.feeds[v.channel_id]=v;
		});
		this.f&&this.f(o.RESULTS);
	}).bindThis({f:f}));
	*/
};
MP.getFeedsInfo=getFeedsInfo;

function getMyFeedsInfo(cid,f){
	if(cid instanceof Array){
		cid=cid.join(",");
	}
	doModiphi("channel/getMyChannel",{channel_id: cid},(function(o){
		/*
		 G.each(o.RESULTS,function(v){
			MP.feeds[v.channel_id]=v;
		});
		*/
		this.f&&this.f(o.RESULTS);
	}).bindThis({f:f}),false);
}
MP.getMyFeedsInfo=getMyFeedsInfo;

function getAllFeeds(dqf,oncomp,ret){ /* searchfeed-(title|etc)-<word>-<offset>,<limit>,c */
	ret=(ret===undefined)?[]:ret;
	dqf=(dqf===undefined)?{}:dqf;
	var q;
	if(!dqf._cloned){
		q=G.clone(dqf);
		q.offset=0; q.limit=50;
		q._cloned=true;
	}else{
		q=dqf;
	}
	function result(r){
		if(r.RESULTS.length>0){
			G.each(r.RESULTS,function(v,i){
				this.ret[this.ret.length]=v.channel_id;
			},this);
			if(this.q.limit==r.RESULTS.length){
				this.q.offset+=this.q.limit;
				//this.f.bindArgs(this.q,this.oncomp,this.ret).later();
				this.f.later(10,this,this.q,this.oncomp,this.ret);
				return;
			}
		}
		this.ret.complete=true;
		this.oncomp&&this.oncomp(this.ret);
	};
	var f=result.bindThis({q:q,oncomp:oncomp,ret:ret,f:getAllFeeds});
	var aj=doModiphi("channel/search",{qj:G.toJSON(q)},f);
}

function modifydesc(e){
	var all=e.getElementsByTagName("*"),l,i;
	for(i=0,l=all.length;i<l;i++){ all[i].id=""; all[i].style.cssText=""; all[i].className=""; }
	var a=e.getElementsByTagName("a"),l,i;
	for(i=0,l=a.length;i<l;i++){ a[i].target="_blank"; }
	var a=e.getElementsByTagName("table"),l,i;
	for(i=0,l=a.length;i<l;i++){ a[i].border="0"; }
}

var newentrywintmpl=
	"<div id=\"${id}\" class=\"entry-content-box\"><div class=\"entry-content\">"+
		"<div class=\"template\">"+
			"<div class=\"entry-head\">"+
				"<h2 class=\"entry-title\"><a title=\"HTMLページを別ウィンドウで開く\" __href=\"#{link}\" target=\"_blank\">#H{title}</a></h2>"+
				"<div class=\"entry-info\">"+
					"<ul>"+
						"<li>情報源： 【<a title=\"情報源のページを別ウィンドウで開く\" __href=\"#{channel_link}\" target=\"_blank\">#H{channel_title}</a>】"+
						" <a title=\"情報源のRSSをRSSリーダーで購読\" __href=\"#subscribe-#{channel_rss_url}\" class=\"icon\"><img src=\"img/rss.gif\" />　RSSリーダーで購読する</a>"+
						"</li>"+
						"<li>関連検索: "+
						" <a title=\"情報源で検索\" __href=\"#feed-#{channel_id}@${srtmplid}\">同じ情報源の記事を検索</a>"+
						" / 同じカテゴリの記事を検索： #{_category_links}"+
						"</li>"+
						"<li>発行日時: #H{pub_date_local}</li>"+
					"</ul>"+
				"</div>"+
			"</div>"+
			"<div class=\"fittarget\"><div class=\"entry-description\">#{description}</div></div>"+
			"<div class=\"bottomspacer\"></div>"
		"</div>"+
		"<div class=\"for-template-notfound\">No such entry</div>"+
		"<div class=\"for-template-processing\">Loading...</div>"+
		"<div class=\"for-template-processing\">Error</div>"+
	"</div></div>";

/*******/

function makesearchnavi(sc,len){
	var offset=sc.offset,limit=sc.limit;
	var tmplid=sc.tmplid;
	var tmpl=MP.tmpl[tmplid];
	var naviid=tmplid+"-navi";
	var hasprev=(offset!=0);
	var hasnext=(len==limit&&len!=0)/*&&(all&(offset+len)<all));*/
	if(tmpl._navitmpl){
		var all=sc.foundrows;
		var curpage=Math.floor(offset/limit)+1;
		var maxpage=Math.floor(all/limit)+2;
		var min=Math.max(1,curpage-3);
		var max=Math.min(min+7,maxpage);
		var p,htap=[];
		for(p=min;p<max;p++){
			if(curpage==p){
				htap.push("<span class=\"navi-page-cur\">"+p+"</span>");
			}else{
				htap.push(G.tmpl("<a href=\"#search-page-${p}@${tmplid}\" class=\"navi-page-notcur\">"+p+"</a>",{p:p,tmplid:tmplid}));
			}
		}
		var v={
			tmplid:tmplid,
			target:tmplid+(sc.append?("/append"):""),
			start:offset+1,end:offset+len,
			limit:limit,
			curpage:curpage,
			foundrows:all,
			paging:htap.join(" ")
		};
		var navi=G.$(naviid,true);
		G.removeClassName(navi,"hasprev");
		G.removeClassName(navi,"hasnext");
		navi.innerHTML=G.tmpl(tmpl._navitmpl,v).replace(/__href=/g,"href=");
		tmpl.hasprev&&G.addClassName(navi,"hasprev");
		tmpl.hasnext&&G.addClassName(navi,"hasnext");
		if(tmpl._navitmpl2){
			var navi=G.$(naviid+"-2",true);
			G.removeClassName(navi,"hasprev");
			G.removeClassName(navi,"hasnext");
			navi.innerHTML=G.tmpl(tmpl._navitmpl2,v).replace(/__href=/g,"href=");
			tmpl.hasprev&&G.addClassName(navi,"hasprev");
			tmpl.hasnext&&G.addClassName(navi,"hasnext");
		}
	}
}

function querybase(target,args,e,onapply,oncomp,parseArgs,buildQuery,onresult){ /* search-(global|h_card..etc)-<word>-<offset>,<limit>,c */
		/* onapply(v);
		 * oncomp(results,tmpl,offset,limit,len);
		 */
	/*
	 * @<targetid/navi-none>
	 * id=<target>をHtmlElementTemplaterSeqとし、search実行。
	 * G.$(<target>)があれば自動的にTemplaterを生成する。
	 * ただし、MP.tmpl[<target>]があればそちらを利用する。
	 * MP.tmpl[<target>].completeは(offset,lent,limit)と引数を渡す。
	 */
	
	var targetargs=(target||"").split("/"),target=targetargs.shift();
	args=args||[];
	
	function compfunc(orgf,r,tmpl,offset,len,limit){
		G.each(G.$S("a.oncomplete",tmpl.tmpl.e),function(e){
			//MP.pseudoClick.later(100,this,e);
			MP.pseudoClick(e);
		});
		return orgf(r,tmpl,offset,len,limit);
	}
	
	oncomp=oncomp?oncomp.hook(compfunc):(function(){}).hook(compfunc);
	
	var cond=MP.search[target]||{
		tmplid:target,
		offset:0, limit:10, 
		dq:{}, // default query
		cq:{}, // current query (for paging)
		append:false, // append (not clear)
		paging:false  // use cond.cq
	};
	while(targetargs.length>0){
		var ta=targetargs.shift();
		switch(ta){
			case "navi-none":
				cond.navi=false; break;
			case "append":
				cond.append=true; break; // 無視するかな…
		}
	}
	var pagingmode=args[0];
	switch(pagingmode){
		case "append":
			cond.offset+=cond.limit;
			cond.append=true;
			cond.paging=true;
			break;
		case "next":
			cond.offset+=cond.limit;
			cond.paging=true;
			delete cond.append;
			break;
		case "prev":
			cond.offset-=cond.limit;
			cond.offset=Math.max(0,cond.offset);
			cond.paging=true;
			delete cond.append;
			break;
		case "page":
			cond.offset=(G.atoi(args[1]-1))*cond.limit;
			cond.offset=Math.max(0,cond.offset);
			cond.paging=true;
			delete cond.append;
			break;
		case "reload":
			cond.offset=0;
			MP.netCache.clear();
			break;
		default:
			delete cond.foundrows;
			delete cond.append;
	}

	var cq=cond.cq;
	if(!cond.paging){
		delete cond._abort;
		var r=parseArgs(args,cond);
		args=r[0]; cond=r[1];
	}
	//delete cond.paging;
	MP.search[target]=cond;
	
	if(!MP.tmpl[target]){
		//var tmpl=new G.HtmlElementTemplaterSeq(G.$(target,true));
		var tmpl=new G.HtmlElementTemplater(G.$(target,true));
		tmpl.oncomplete=function(){
			G.each($S("a.templatecomplete",tmpl.e),function(a){
				MP.pseudoClick(a);
			});
		};
		MP.tmpl[target]=tmpl;
	} else {
		var tmpl=MP.tmpl[target];
	}

	if(!cond.append){tmpl.abort();}

	if(tmpl.busy){
		querybase.later.apply(this,[200,this].concat([].slice.apply(arguments)));
		//arguments.callee.later.apply(arguments.callee,[200,this].concat([].slice.apply(arguments)));
		return;
	}

	tmpl.busy=true;
	G.removeClassName(tmpl.e,"hasprev");
	G.removeClassName(tmpl.e,"hasnext");
	tmpl.start(!cond.append); 
	if(G.$(tmpl.tmpl.e.id+"-navi",true)){
		cond.navi=true;
		if(!tmpl._navitmpl){
			tmpl._navitmpl=G.$(tmpl.tmpl.e.id+"-navi").innerHTML;
		}
		G.$(tmpl.tmpl.e.id+"-navi").innerHTML="";
		if (G.$(tmpl.tmpl.e.id + "-navi-2",true)) {
			if(!tmpl._navitmpl2){
				tmpl._navitmpl2=G.$(tmpl.tmpl.e.id + "-navi-2").innerHTML;
			}
			G.$(tmpl.tmpl.e.id + "-navi-2").innerHTML = "";
		};
	}

	if(!cond.paging){
		if(cond._abort){
			tmpl.abort(function(tmpl){
				var e=G.$S(".for-template-abort .msg",tmpl.e);
				if(e[0]){e[0].innerHTML=G.esc(cond._abort);}
			});
			tmpl.busy=false;
			tmpl.aborted=true; // いつクリアするかな…
			//delete cond._abort;
			return;
		}
		delete tmpl.aborted;
	}else if(tmpl.aborted){
		return;
	}
	delete cond.paging;
	
	var lender=(function(cond,onapply,oncomp,onresult){
		return function(r){
			var tmpl=MP.tmpl[cond.tmplid];
			var offset=cond.offset, limit=cond.limit;
			if(cond.navi&&cond.foundrows===undefined){
				cond.foundrows=r.foundRows;
				CONSOLE.log("#querybase:foundrows="+r.foundRows);
			}
			r=onresult?onresult(r,cond):r;
			var idx=offset;
			if(r.RESULTS.length>0){
				G.each(r.RESULTS,function(v,i){
					// v._idx=i+offset+1;
					v=onapply?onapply(v,tmpl.tmpl._tmplvals,cond):v;
					if(v!==null){
						idx++;
						v._idx=idx;
						v._oddeven=(["odd","even"])[idx%2];
						tmpl.apply(v);
					}
				});
				if(limit==r.RESULTS.length){ // has next;
					tmpl.complete((function(cond,tmpl,len,oncomp,r){
						offset=G.atoi(cond.offset); limit=G.atoi(cond.limit);
						tmpl.hasprev=(offset!=0);
						tmpl.hasnext=(len==limit&&len!=0);
						tmpl.hasprev&&G.addClassName(tmpl.e,"hasprev");
						tmpl.hasnext&&G.addClassName(tmpl.e,"hasnext");
						cond.navi&&makesearchnavi(cond,len);
						//tmpl.oncomplete&&tmpl.oncomplete(offset,len,limit);
						oncomp&&oncomp(r,tmpl,offset,len,limit);
						G.refreshElement(tmpl.tmpl.e);
						tmpl.busy=false;
					}).bindArgs(cond,tmpl,r.RESULTS.length,oncomp,r));
					return;
				}
			}
			tmpl.complete((function(cond,tmpl,len,oncomp,r){
				offset=G.atoi(cond.offset); limit=G.atoi(cond.limit);
				tmpl.hasprev=(offset!=0);
				tmpl.hasnext=(len==limit&&len!=0);
				tmpl.hasprev&&G.addClassName(tmpl.e,"hasprev");
				tmpl.hasnext&&G.addClassName(tmpl.e,"hasnext");
				cond.navi&&makesearchnavi(cond,len);
				//tmpl.oncomplete&&tmpl.oncomplete(offset,len,limit);
				oncomp&&oncomp(r,tmpl,offset,len,limit);
				G.refreshElement(tmpl.tmpl.e);// refresh
				tmpl.busy=false;
			}).bindArgs(cond,tmpl,r.RESULTS.length,oncomp,r));
		};
	})(cond,onapply,oncomp,onresult);

	var onerr=(function(txt,hst,req,ex){
		//tmpl.abort(); エラーのときの表示
		if(tmpl){
			tmpl.abort(function(tmpl){
				var e=G.$S(".for-template-abort .msg",tmpl.e);
				if(e[0]){
					e[0].innerHTML="通信エラー";

				}
			});
			tmpl.busy=false;
		}else{alert("通信エラー");}
	}).bindArgs(tmpl);
	
	var r=buildQuery(cond);
	var aj=doModiphi(r[0],r[1],lender,onerr,!cond.nocache);
}

function searchParentChildren(target,e){
	// @this
	// @<id>
	// @<parentselector>
	// @<parentselector>/<childselector>
	// @<parentselector>/<childselector>[<idx>]
	// return [],[elm],[elm1,elm2,elm3]

	CONSOLE.info("searchParentChildren():"+target);

	var children=target.split("/");
	target=children.shift();

	var te=e;
	if(target!="this"){
		te=G.findAncestorBySelector(te,target);
	}
	if(G.$(target,true)){
		te=G.$(target);
	}
	if(!te){
		CONSOLE.error("searchParentChildren():"+target+" is not found.\n"+G.getXPath(te));
		return [];
	}
	
	if(children[0]){
		CONSOLE.log("searchParentChildren():search children:"+children[0]);
		var m=children[0].match(/^(.*)\[(\d+)\]$/);
		if(!m){
			children=children[0];
		}else{
			children=m[1];
		}
		var tes=G.$S(children,te);
		if(tes[0]==te){ tes.shift(); }
		if(m&&m[2]&&tes[m[2]]){tes=[tes[m[2]]];}
		te=tes;
		CONSOLE.log("searchParentChildren():found children:"+tes.length);
	}else{
		if(te){
			CONSOLE.log("searchParentChildren():found:"+target);
		}else{
			CONSOLE.log("searchParentChildren():not found:"+target);
		}
		te=[te];
	}
	return te;
}
MP.searchParentChildren=searchParentChildren;

/**
 * linkClickHandlers: <a href="#someargs>"> click handler
 * 
 *  #<cmd>-<args>....&&<cmd>-<args>... で連続実行
 * 
 *   #void : なにもしない
 *   #subscribe-<url> : RSS url 購読メニューを表示
 *   #sr-<site>-<url> : RSS urlを<site>で購読
 *   #tab-<tab>@<tabsid> : G.Tabs($(tabsid))のタブを有効にする
 *         <a href="#tab-maintab_0@maintab>#maintabの#maintab_0を有効にする</a>
 *         <a href="#tab-メイン@maintab>#maintabの「テキスト内容が「メイン」」のタブを有効にする</a>
 *   #toggle-<orgclass>-<toggleclass>@<target> : クラス名トグル。<target>=<this|parent selector>
 *  　　　　　　<a href="#toggle-open-close@this" class="open">class="open"とclass="close"をトグル</a>
 *         <parent class="target class1">
 *           <somechild>
 *             <a href="#toggle-class1-class2@paent.target">
 *               parent.targetのclass="class1"とclass="class2"をトグル
 *             </a>
 *           </somechild>
 *         </parent>
 *   
 *   #class-toggle-<class1>-<class2>@<<parent selector>[/all]|this>
 *   #class-cycle-<class1>-<class2>-<class3>-...@<<parent selector>[/children selector]|this>
 *   #class-set-<class1>@<parent selector[/children selector|]|this>
 *   #class-unset-<class1>@<parent selector[/children selector]|this>
 *   
 *     thisか、<parent selector>か、<parent selector>の子要素群<children slector>の
 *     classを、toggle,cycle,set,unsetする。
 *   
 *   #entry-<item_id>@<target>
 *       <target>=<targettmplid>|newentrywintmpl-<windowid>
 *         #<targettmplid>をG.HtmlElementTemplaterとしてitem_idの記事を適用
 *         newentrywintmpl-<windowid>の場合、#windowidのウィンドウを表示して適用
 *   
 *   #search-<searchcond>@<target>
 *   #searchfeed-<searchcond>@<target>
 *       <target>=<targettmplid>|<targettmplid>[/navi-none[/append]]
 *       #<targettmplid>をG.HtmlElementTemplaterとして<searchcond>の記事/フィードを適用
 *       #<targettmplid>-naviや#<targettmplid>-navi-2があったらナビ内容を生成して適用
 *         navi-none: ナビを使わない
 *         append: 消さずに続ける
 *       <searchcond>:APIのitem/searchとchannel/searchの検索条件
 *       -next,-prev,-page-<pageno(0 origin)>,-reload
 *       (*)MP.search[<tmplid>]に事前に条件設定できる
 *       (*)MP.tmpl[<tmplid>]にHtmlElementTemplater(or ...Seq)を設定できる
 *   #exec-<funcname>[-<arg1>[-<arg2>,..]]
 *   	funcname(arg1,arg2,...)実行
 *   <a href="#exec"><script type="text/javascript">function(){this is A}</script></a>
 *      <script>内関数実行
 *   #watch-...
 *   #wait-
 *   #cursor-set-<classname>-<cursorname>-<scrollselector>@<parentselector>[/<childselector>]
 *   	<parentselector>に<classname>をsetする。
 *   	MP.cursors[<cursorname>]に<parentselector>を設定する。
 *   	すでにMP.curosrs[<cursorname>]があったら<classname>を除去。
 */
var linkClickHandlers={
	"void":function(target,args,e,onapply,oncomp){},
	"feed":function(target,args,e,onapply,oncomp){ /* feed-<channel_id>,<channel_id>-<offset>,<limit>,c */
		args.unshift("feed");
		linkClickHandlers["search"](target,args,e,onapply,oncomp);
	},
	"category":function(target,args,e,onapply,oncomp){ /* category-<category>-<offset>,<limit>,c */
		args.unshift("category");
		linkClickHandlers["search"](target,args,e,onapply,oncomp);
	},
	"search":function(target,args,e,onapply,oncomp){
		if(target.match(/^msmp-\d-search-list$/)){
			var mpid=target.split("-")[1];
			MP.parts[mpid].tabs.enable(G.$("msmp-"+mpid+"-tabs_search"));
		}
		var parseArgs=function parseArgsFunc(args,cond){
			var cq=G.clone(cond.dq);
			while(args[0]){
				var cmd=args.shift();
				switch(cmd){
					case "form":
						var func=G.$C({t:"script"},e)[0];
						if(func){
							eval("func="+(func.text||func.innerText||func.textContent));
						}
						var form=args.shift()
						if(form=="here"){
							form=G.$SA(e,"form");
						}else{
							form=G.$(form);
						}
						var v=G.getElementValues(form);
						if(func){v=func(v);}
						var a=[];
						G.each(v,function(v,p){
							if(p.indexOf("_")==0){return;}
							a.push(p); a.push(v);
						});
						args=a.concat(args);
						break;
					case "feed": case "channel_id":
						cq.channel_id=(cq.channel_id||[]).concat(args.shift().split(",")); // dqに加える? 上書きでよさそうだが
						if(cq.channel_id.length==0
							||(cq.channel_id.length==1&&cq.channel_id[0]=="")){
							cond._abort = "フィードが指定されていません";
						}
						break;
					case "category":
						cq.category={query:(args.shift()||"").split(",")}; // dqあっても上書きすることにする(APIがorだから)
						break;
					case "global":
					case "h_card": case "h_review": case "h_resume": case "geo": case "adr": case "xfn":
						cq[cmd]={query:"*D+ "+args.shift()||""};　// dqあっても上書きすることにする
						break;
					case "h_calendar":
						var calarg=(args.shift()||"").split(",");
						cal={query:calarg[0]||"",dtstart:calarg[1]||"",dtend:calarg[2]||""}; 
						cq[cmd]=cal; // うーん
						break;
					case "descall":
						cq._descall=true;
						break;
					default:
						if(args.length==0){
							var m=cmd.match(/^(\d+),(\d+)$/);
							if(m){
								cond.offset=G.atoi(m[1]); cond.limit=G.atoi(m[2]);
								break;
							}
						}
						cq[cmd]=args.shift()||""; break;
				}
			}
			cond.cq=cq;
			return [args,cond];
		}

		function buildQuery(cond){
			MP.dupchecker=MP.dupchecker||{};
			var qj=G.clone(cond.cq);
			var descall=qj._descall; delete qj._descall;
			qj.offset=cond.offset; qj.limit=cond.limit;
			if(qj.offset==0){
				MP.dupchecker={};
			}
			var scope=qj.scope; delete qj.scope;
			var qj=G.toJSON(qj);
			var q={qj:qj}; if(scope){q.scope=scope;}
			if(descall){q.alltext=true;}
			if(cond.navi&&cond.foundrows==undefined){
				q.foundrows=true;
			}
			return ["item/search",q];
		}

		function onApply(v,vlist,cond){
			v._className=[];
			if(v.enclosure_url){v._className.push("hasenclosure");}
			G.each(["pub_date"],function(p){
				if(vlist[p+"_local"]){
					v[p+"_local"]=getUserTZDateStr(v[p]);
				}
			});
			if(vlist["_description_short"]){
				if(v.description=="no description"){
					v._className.push("nodescription");
					v._description_short="[内容は配信されていません]";
				} else {
					v._description_short=shorten_l(G.normalizeHtml(v.description,"text"),20);
				}
			}
			if(vlist["_description_middle"]){
				if(v.description=="no description"){
					v._className.push("nodescription");
					v._description_middle="[内容は配信されていません]";
				} else {
					v._description_middle=shorten_l(G.normalizeHtml(v.description,"text"),100);
				}
			}
			if(vlist["_description_all"]){
				if(v.description=="no description"){
					v._className.push("nodescription");
					v._description_all="<span class=\"nodesc\">内容は配信されていません。<a target=\"_blank\" href=\""+v.link+"\">オリジナルの内容はこちら</a></span>";
				} else {
					v._description_all=G.normalizeHtml(v.description,"html",modifydesc);
				}
			}
			if(vlist["description"]){
				if(v.description=="no description"){
					v._className.push("nodescription");
					v.description="[内容は配信されていません]";
				} else {
					v.description=G.normalizeHtml(v.description,"text");
				}
			}
			// リダイレクトされてないか調べる
			// んー、rssadはどっちも自分で持ってredirectするのか…
			/*
			var ch=(G.parseUri(v.channel_url).hostname||"").split(".").reverse().slice(0,2).join(".");
			var ih=(G.parseUri(v.item_link).hostname||"").split(".").reverse().slice(0,2).join(".");
			if(ch!=ih){
				v._className.push("redirected");
			}
			*/
			
			// 前に出てきたtitle/desc(200文字)かどうか調べる
			if(!MP.dupchecker){MP.dupchecker={}}
			if(!MP.dupchecker[v.item_title+v.description.substring(0,201)]){
				MP.dupchecker[v.item_title+v.description.substring(0,201)]=v.item_id;
			}else{
				v._className.push("duplicate");
			}

			//if(MP.lastReadEntryTime){
				if(MP.lastReadEntryTime>=MP.getUserTZDate(v.pub_date).valueOf()){
					v._className.push("read");
				}
			//}

			v._className=v._className.join(" ");
			MP.entries[v.item_id]=v;
			v=onapply?onapply(v,vlist,cond):v;
			return v;
		}
		
		querybase(target,args,e,onApply,oncomp,parseArgs,buildQuery);
	},
	"searchfeed":function(target,args,e,onapply,oncomp){ /* searchfeed-(title|etc)-<word>-<offset>,<limit>,c */
		function parseArgs(args,cond){
			var q=G.clone(cond.dq);
			while(args[0]){
				var cmd=args.shift();
				switch(cmd){
					case "form":
						var func=G.$C({t:"script"},e)[0];
						if(func){
							eval("func="+(func.text||func.innerText||func.textContent));
						}
						var form=args.shift()
						if(form=="here"){
							form=G.$SA(e,"form");
						}else{
							form=G.$(form);
						}
						var v=G.getElementValues(form);
						if(func){v=func(v);}
						var a=[];
						G.each(v,function(v,p){
							if(p.indexOf("_")==0){return;}
							a.push(p); a.push(v);
						});
						args=a.concat(args);
						break;
					case "feed":
						q["channel_id"]=args.shift()||""; break;
					case "category": case "system_category":
						q["system_category"]=(args.shift()||"").split(",")||""; break;
					default:
						if(args.length==0){
							var m=cmd.match(/^(\d+),(\d+)$/);
							if(m){
								cond.offset=G.atoi(m[1]); cond.limit=G.atoi(m[2]);
								break;
							}
						}
						q[cmd]=args.shift()||""; break;
				}
			}
			cond.cq=q;
			return [args,cond];
		}
		
		function buildQuery(cond){
			var cq=G.clone(cond.cq);
			cq.offset=cond.offset; cq.limit=cond.limit;
			var q={qj:G.toJSON(cq)};
			if(cond.navi&&cond.foundrows==undefined){
				q.foundrows=true;
			}
			return ["channel/search",q]; 
		}
		
		function onApply(v,vlist){
			G.each(["newest_item_pub_date","pub_date","regist_date","update_date"],function(p){
				if(vlist[p+"_local"]){
					v[p+"_local"]=getUserTZDateStr(v[p]);
				}
			});
			if(vlist["description"]){
				v.description=G.normalizeHtml(v.description,"text");
			}
			MP.feeds[v.channel_id]=v;
			return onapply?onapply(v):v;
		}

		querybase(target,args,e,onApply,oncomp,parseArgs,buildQuery);
	},
	
	"entry":function(target,args,e,onapply,oncomp){  /* entry-<item_id>,<item_id>@<target>/<searchtarget> */
		MP.showingEntry=undefined;
		// #entry-<entryid>@<targetid>/<searchtargettmplid>
		target=target.split("/");
		var srtmplid=target[1]||"searchresultstmpl";
		target=target[0];
		if(target&&target.match(/^newentrywintmpl-/)){
			// newentrywintmpl-<baseid> -> entrywin-<baseid>,entrywintmpl-<baseid>
			var t=target.split("-");
			var baseid=t[1];
			if(baseid=="_blank"){
				baseid=MP.windows.__cnt++;
			}
			var wid="entrywin-"+baseid;
			var tmplid="entrywintmpl-"+baseid;
			target=tmplid;
			var ew=MP.windows[wid];
			if(!ew){
				var stylepath="./widget/window/green-rss";
				var controls = "<a title=\"ウィンドウを閉じる\" href=\"#window-close@here\" class=\"icon\" \><img src=\"" + stylepath + "/img/closebutton.gif\" /></a>";
				var ew = new MP.Window(
					G.tmpl(newentrywintmpl,{id:tmplid,srtmplid:srtmplid}).replace(/#([HAJ]?)\{/g,"$$$1{"),
					{
						id:wid,
						stylepath:stylepath,
						html:{
							".window-controls-1": controls,
							".window-controls-2":"<div class=\"foot-notify\">コンテンツ取得は実験的なもので、内容取得に失敗している場合があります。</div>"
						}
					}
				);
				G.addClassName(ew.e, "msmp-entrywin");
				//ew.e.id=wid;
				
				ew.fitContent=function(){
					if(!this.fitContent._old){this.fitContent._old={ch:-1,bh:-1};}
					var ed=G.$S(".fittarget",this.c)[0];
					if (ed) {
						var orgh=ed.offsetHeight;
						ed.style.height="auto";
						var pbh = this.b.offsetHeight; //G.pos(this.b);
						var pch = this.b.scrollHeight;
						if(pch!=0&&pch==this.fitContent._old.ch&&pbh==this.fitContent._old.bh){
							ed.style.height=orgh+"px"; return;
						}
						this.fitContent._old={ch:pch,bh:pbh};
						var psh = ed.offsetHeight; //G.pos(ed);
						G.setStyles(ed,{
							height: Math.max(100, pbh - (pch - psh) - 0 ) + "px",
							position:"relative",
							overflow:"auto"
						});
						setTimeout(this.fitContent.bindThis(this),1000);
					}
				};
				
				ew.onSetpos=function(x,y,w,h){
					this.fitContent();
				};
				ew.setPos();
				MP.windows[wid]=ew;
				
				ew._show=ew.show;
				ew.show=function(){
					this._show.apply(this,arguments);
					this.moveIntoView.later(500,this);
				};
				
			}

			ew.setTitle("Loading...");
			ew.show();
			(function(){
				this.setTitle(MP.showingEntry.title);
				this.fitContent();
			}).bindThis(ew).poll(function(){return MP.showingEntry;});
			
		}
		function parseArgs(args,cond){
			cond.cq={item_id:args.shift()}; // item_id
			while(args[0]){
				switch(args[0]){
					case "nocache":
						args.shift(); cond.nocache=true; break;
					case "myentry":
						args.shift(); cond.nocache=true; cond.myentry=true; break;
				}
			}
			return [args,cond];
		}
		function buildQuery(cond){
			return [cond.myentry?"item/getMyItem":"item/getItem",cond.cq];
		}
		function onresult(r){
			// getMyItemのときは[item,channel,nchannel]
			if(r.RESULTS&&r.RESULTS[0]&&!r.RESULTS[0]._channelobj){
				if(r.RESULTS.length==3){
					if(r.RESULTS[1].n2_flg==1){
						r.RESULTS[0]._channelobj_n2=r.RESULTS.pop();
					}else if(r.RESULTS[1].n3_flg==1){
						r.RESULTS[0]._channelobj_n3=r.RESULTS.pop();
					}
				}
				r.RESULTS[0]._channelobj=r.RESULTS.pop();
			}
			return r;
		}
		function onApply(v,vlist){
			var ch=v._channelobj,classNames=[];
			G.each(["pub_date"],function(p){
				if(vlist[p+"_local"]){
					v[p+"_local"]=getUserTZDateStr(v[p]);
				}
			});
			if(vlist["description"]){
				if(v.description=="no description"){
					classNames.push("nodescription");
					v.description="<span class=\"nodesc\">内容は配信されていません。<a target=\"_blank\" href=\""+v.link+"\">オリジナルの内容はこちら</a></span>";
				} else {
					v.description=G.normalizeHtml(v.description,"html",modifydesc);
				}
			}
			if(vlist["description"]&&v.description_follow){
				v.description_follow=G.normalizeHtml(v.description_follow,"html",modifydesc);
				classNames.push("hasfollow");
			}else{
				v.description_follow="";
				classNames.push("nothasfollow");
			}
			if(vlist["_description_text"]){
				v._description_text=G.normalizeHtml(v.description,"text");
			}

			v.author=v.author||ch.member_id;
			v.member_id=ch.member_id;
			v.channel_title=ch.title;
			v.channel_rss_url=ch.channel_url;
			v.channel_link=ch.link;

			if(vlist["_category_links"]){
				v._category_links=(function(cats){
					var r=[];
					G.each(cats.split("\t"),function(v){
						switch(v){
							case "ユーザ購読": case "アーカイブ": case "道具箱":
							return;
						}
						r.push("<a title=\"このタグの記事を検索\" href=\"#category-"+G.esc(v,"A")+"-0,10@"+srtmplid+"\">"+G.esc(v)+"</a>");
					});
					return r.join(", ");
				})(v.categories);
			}
			if(vlist["_categories"]){
				v._categories=(function(cats){
					var r=[];
					G.each(cats.split("\t"),function(v){
						switch(v){
							case "ユーザ購読": case "アーカイブ":
							return;
						}
						r.push(v);
					});
					return r.join(", ");
				})(v.categories);
			}
			
			checkLastReadTime(MP.getUserTZDate(v.pub_date));
			
			if(MP.mysubscribedchannels&&MP.mysubscribedchannels[v.channel_id]){
				classNames.push("subscribed");
			}else{
				classNames.push("notsubscribed");
			}
			
			if (!MP.feeds[ch.channel_id]) {
				MP.feeds[ch.channel_id] = ch;
			}
			MP.entries_full[v.item_id]=v;
			v._className=classNames.join(" ");
			MP.showingEntry=v;

			return onapply?onapply(v,vlist):v;
		}
		querybase(target,args,e,onApply,oncomp,parseArgs,buildQuery,onresult);
	},

	"myarchive":function(target,args,e,onapply,oncomp){
		var func=(function (target,args,e,onapply,oncomp){
			var cid; // 複数アーカイブとかあるべき？
			G.each(MP.myarchives,function(v){
				cid=v.channel_id;
			});
			args.unshift(cid);
			args.unshift("channel_id");
			linkClickHandlers["myentries"](target,args,e,onapply,oncomp);
		}).bindArgs(target,args,e,onapply,oncomp);
		if(!MP.myarchives){
			MP.getMyArchives(func);
		}else{
			func();
		}
	},
	
	"myentries":function(target,args,e,onapply,oncomp){
		var parseArgs=function parseArgsFunc(args,cond){
			var cq=G.clone(cond.dq);
			while(args[0]){
				var cmd=args.shift();
				switch(cmd){
					case "feed": case "channel_id":
						cq.channel_id=args.shift();
						break;
					default:
						if(args.length==0){
							var m=cmd.match(/^(\d+),(\d+)$/);
							if(m){
								cond.offset=G.atoi(m[1]); cond.limit=G.atoi(m[2]);
								break;
							}
						}
						cq[cmd]=args.shift()||"";
						break;
				}
			}
			cond.cq=cq;
			cond.nocache=true;
			return [args,cond];
		}

		function buildQuery(cond){
			var q=G.clone(cond.cq);
			q.offset=cond.offset; q.limit=cond.limit;
			// var api="item/getChannelItem";
			// apps mearged item/getMyItems
			var api="item/getMyItems";
			return [api,q];
		}
		
		var now=new Date().valueOf();
		function onApply(v,vlist,cond){
			G.each(["pub_date"],function(p){
				if(vlist[p+"_local"]){
					v[p+"_local"]=MP.getUserTZDateStr(v[p]);
				}
			});
			// TODO: check expire
			// if(now>MP.getUserTZDate(v[""]))
			v=onapply?onapply(v,vlist,cond):v;
			return v;
		}
		
		querybase(target,args,e,onApply,oncomp,parseArgs,buildQuery);
	},
	
	"subscribe":function(target,args,e){
		var pm=MP.srpop;
		if(!args||args.length==0){
			MP.subscribe=e.href.replace(/#subscribe$/,"");
		}else{
			MP.subscribe=args.join("-");
		}
		if(!pm){
			var a={
				"<img src=\"favicon/feedicon.gif\"/> 利用中のブラウザ":"browser",
				"<img src=\"favicon/modiphi.gif\"/> MODIPHI":"modiphi",
				"<img src=\"favicon/ecreal.gif\"/> ECReal Reader":"ecreal",
				"<img src=\"favicon/googleReader.gif\" /> Google Reader":"google",
				"<img src=\"favicon/yahoo.gif\" /> My Yahoo!":"yahoo",
				"<img src=\"favicon/hatena.gif\" /> はてなRSS":"hatena",
				"<img src=\"favicon/livedoor.gif\" /> livedoorリーダー":"livedoor",
				"<img src=\"favicon/goo.gif\" /> goo RSSリーダー":"goo",
				//"<img src=\"favicon/feedpath.gif\" /> feedpath":"feedpath",
				"<img src=\"favicon/bloglines.gif\" /> Bloglines":"bloglines"
			};
			var pmd=[{l:"RSSを登録"}];
			var base=G._BASEPATH+"../";
			G.each(a,function(v,p){
				p=p.replace(" src=\""," src=\""+base);
				pmd.push({lh:p,f:(function(e){
					MP.srpop.hide();
					MP.linkClickHandlers["sr"]("",[this.t,MP.subscribe]);
				}).bindThis({t:v,url:args[0]})});
			});
			pm=new G.PopupMenu(pmd,"12em");
			MP.srpop=pm;
		};
		var pos=G.pos(e);
		pm.show(pos.left,pos.bottom);
	},
	"sr":function(target,args,e){ // #sr-<> : subscribe MP.showingEntry
		var cite=args.shift();
		var url=(args||"").join("-")||MP.subscribe||(MP.showingEntry&&MP.showingEntry.channel_rss_url);
		switch(cite){
			case "google":
				window.open("http://fusion.google.com/add?feedurl="+G.esc(url,"U"));
				break;
			case "yahoo":
				window.open("http://add.my.yahoo.co.jp/rss?url="+G.esc(url,"U"));
				break;
			case "hatena":
				window.open("http://r.hatena.ne.jp/append/"+G.esc(url,"U"));
				break;
			case "feedpath":
				window.open("http://feedpath.jp/reader/add/addFeed.do?url="+G.esc(url,"U"));
				break;
			case "livedoor":
				window.open("http://reader.livedoor.com/subscribe/"+url);
				break;
			case "ecreal":
				window.open("http://ecreal.jp/pcreader/subscribe?url="+G.esc(url,"U"));
				break;
			case "goo":
				window.open("http://reader.goo.ne.jp/web/bookmarklet.html?,,"+G.esc(url,"U"));
				break;
			case "bloglines":
				window.open("http://www.bloglines.com/sub/"+url);
				break;
			case "modiphi":
				if(MP.login){
					MP.subscribeChannel(url,function(){
						alert("登録しました");
					});
				}else{
					window.open("http://www.modiphi.com/mf/subscribe?url="+G.esc(url,"U"));
				}
				//addFavFeed(url);
				break;
			case "browser":
				window.open(url);
				break;
		};
	},
	"tab": function(target,args,e){ //  tab-(<tabid>|<tabtext>)@<tab var>
		if(!MP.tabs[target]){
			var enabler={
				"*:init":function(tc,te){
					var seq=new G.Seq();
					G.each(G.$S("a.tabinit",tc),function(e){
						seq.add((function(){
							e.innerHTML="initializing";
							MP.pseudoClick(e);
							G.removeElement(e);
						}).bindArgs(e));
					});
					seq.start();
				},
				"*":function(tc,te){
					var seq=new G.Seq();
					G.each(G.$S("a.tabenable",tc),function(e){
						seq.add((function(){
							MP.pseudoClick(e);
						}).bindArgs(e));
					});
					seq.start();
				}
			}
			MP.tabs[target]=new G.Tabs(G.$(target),enabler);
		}
		//CONSOLE.log("MP.tabs[\""+G.esc(target,"J")+"\"].enable(G.$(\""+G.esc(args[0],"J")+"\"))");
		//eval("MP.tabs[\""+G.esc(target,"J")+"\"].enable(G.$(\""+G.esc(args[0],"J")+"\"))");
		if(G.$(args[0])){
			MP.tabs[target].enable(G.$(args[0]));
		}else if(G.$(target+"_"+args[0])){
			MP.tabs[target].enable(G.$(target+"_"+args[0]));
		}else{
			var found=null;
			G.each(MP.tabs[target].tabs,function(elm){
				CONSOLE.log("#tab-"+args[0]+":check:\""+(elm.textContent||elm.innerText)+"\"");
				if(args[0]==(elm.textContent||elm.innerText)){
					MP.tabs[target].enable(elm);
					CONSOLE.log("#tab-"+args[0]+":found:\""+G.getSelectorPath(elm)+"\"");
					return true;
				};
			});
		}
	},

	// tagname#id.class

	"toggle": function(target,args,e){ // toggle-<initclass>-<toggleclass>@<(this|<selector for ancestor>)>
		args.unshift("toggle");
		MP.linkClickHandlers["class"](target,args,e);
	},
	"class": function(target,args,e){ // toggle-<initclass>-<toggleclass>@<(this|<selector for ancestor>)>
		var cmd=args.shift(); // toggle,cycle,set,unset

		var te=searchParentChildren(target,e);

		// te:[target1,target2,...], cmd, args[]
		
		var exec={
			"toggle":function(te,args){
				exec["cycle"](te,args);
			},
			"cycle":function(te,args){
				G.each(te,function(e){
					G.each(args,function(v,i){
						if(G.isClass(e,args[i])){
							G.removeClassName(e,args[i]);
							G.addClassName(e,args[(i+1)%args.length]);
							return true;
						}
					});
				});
			},
			"set":function(te,args){
				G.each(te,function(e){
					G.each(args,function(v,i){
						G.addClassName(e,args[i]);
					});
				});
			},
			"unset":function(te,args){
				G.each(te,function(e){
					G.each(args,function(v,i){
						G.removeClassName(e,args[i]);
					});
				});
			}
		}
		
		exec[cmd](te,args);
		
	},
	"fontsize": function(target, args, e,onapply,oncomp){
		target=G.$(target);
		if(!target){
			target=document.body;
		}
		var sp=G.$("fontsize-dummy");
		if(!sp){
			sp=document.createElement("div");
			sp.innerHTML="&nbsp;";
			sp.style.cssText="margin:0;padding:0;position:absolute;background:transparent;visibility:hidden;line-height:1;";
			document.body.appendChild(sp);
		}else{
			sp.style.display="block";
		}
		m=sp.offsetHeight;
		var ns=sp.offsetHeight;
		switch (args[0]) {
			case "up":
				ns += Math.max(Math.floor(ns*0.1),1);
				break;
			case "down":
				ns -= Math.max(Math.floor(ns*0.09),1);
				break;
		}
		target.style.fontSize = ns+"px";
		sp.style.display="none";
		return;

		if(!target){
			target=document.body;
		}
		var cs = G.currentStyle(target, "fontSize");
		var m = cs.match(/^(.*)(px|pt|em|%|cm|mm)$/);
		var ns = 0;
		switch (args[0]) {
			case "up":
				ns = G.atof(m[1], 14) * 1.1;
				break;
			case "down":
				ns = G.atof(m[1], 14) * 0.9;
				break;
		}
		target.style.fontSize = ns + m[2];
	},
	"window":function(target, args, e,onapply,oncomp){
		if(!target||target=="here"){
			target=G.$SA(e,".window-box").id;
		}
		switch(args[0]){
			case "close":MP.windows[target].hide();
		}
	},
	"create":function(target,args,e){
		var scr=G.$C({t:"script"},e)[0];
		if(scr){
			scr=(scr.text||scr.contentText||scr.innerText).replace(/\s*$/g,"").replace(/^\s*/g,"");
		}
		var obj=args.shift();
		if(G.$(target,true)){
			target="#"+target;
		}
		var targets=G.$S(target);
		var args2=[];
		while(args[0]){
			if(args[0].indexOf("[")==0){
				var params={};
				G.each(args.shift().replace(/^\[/,"").replace(/\]$/,"").split(","),function(v,i){
					v=v.split(":");
					params[v[0]]=v[1];
				});
				var csstmpl=args.join("-");
				break;
			}else{
				args2.push(args.shift());
			}
		}
		args=args2;

		switch(obj){
			case "tab":
				G.each(targets,function(e){
					if(!e.id){
						e.id="msmp-tab-"+MP.tabs._cnt++;
					}
					var enabler=eval(scr)||{};
					var f=enabler["*:init"]||function(){};
					enabler["*:init"]=f.hook(function(orgf,tc,te){
						var seq=new G.Seq();
						G.each(G.$S("a.tabinit",tc),function(e){
							seq.add((function(){
								//e.innerHTML="initializing";
								MP.pseudoClick(e);
								G.removeElement(e);
							}).bindArgs(e));
						});
						seq.start();
						orgf(tc,te);
					});
					var f=enabler["*"]||function(){};
					enabler["*"]=f.hook(function(orgf,tc,te){
						var seq=new G.Seq();
						G.each(G.$S("a.tabenable",tc),function(e){
							seq.add((function(){
								MP.pseudoClick(e);
							}).bindArgs(e));
						});
						seq.start();
						orgf(tc,te);
					});
					MP.tabs[e.id]=new G.Tabs(e,enabler);
					if(csstmpl){
						params.id=e.id;
						G.requireCssTmpl(csstmpl,params);
					}
					//e.parentNode.insertBefore(deco,e);
				});
				break;
			case "decorate":
				var isinner=(args[0]=="inner");
				MP.decorated=MP.decorated||{};
				G.each(targets,function(e){
					var deco=new MP.Decorate(e,null,isinner);
					if(csstmpl){
						var p=G.clone(params);
						p.id=deco.id;
						G.requireCssTmpl(csstmpl,p);
					}
					if(e.id){
						MP.decorated[e.id]=deco;
					}else{
						MP.decorated[deco.id]=deco;
					}
				});
				break;
			case "parts":
				G.each(targets,function(e){
					var def=eval(scr);
					var p=new MP.SmartParts(def,csstmpl)
					e.appendChild(p.e);
				});
				break;
			case "wizard":
				G.each(targets,function(e){
					var def=eval(scr)||{};
					var w=new G.Wizard(e);
					w.onEnable=function(idx,wiz){
						G.each(G.$S("a.wizenable",wiz.seq[idx]),function(e){
							MP.pseudoClick(e);
						});
					};
					G.each(["onEnable","onNext","onPrev","onCancel","onComplete"],function(p){
						if(def[p]){
							w[p]=w[p].chain(function(pret,idx,wiz,lastidx){
								def[p](idx,wiz,lastidx);
							},w);
						}
					});
					if(!e.id){e.id=MP.wizards._cnt++;}
					MP.wizards[e.id]=w;
				});
				break;
			case "template":
				G.each(targets,function(e){
					if(!e.id){return;}
					MP.tmpl[e.id]=new G.HtmlElementTemplater(e);
					MP.tmpl[e.id].reset();
				});
				break;
			case "window":
				G.each(targets,function(e){
					var stylepath="./widget/window/green-rss";
					//var controls = "<a title=\"ウィンドウを閉じる\" href=\"#window-close@here\" class=\"icon\" \><img src=\"" + stylepath + "/img/closebutton.gif\" /></a>";
					var controls = "<a title=\"ウィンドウを閉じる\" href=\"#window-close@here\" class=\"icon closebutton\" \>[x]</a>";
					var win=new MP.Window(e,{
						stylepath:csstmpl||stylepath,
						html:{
							".window-controls-1": controls
						}
					});
					if(e.id){
						MP.windows[e.id]=win;
					}
					MP.windows[win.wid]=win;
				});
				break;
			case "tree":break;
			case "dialog":break;
		}
		
	},
	"include":function(target,args,e){ // TODO
		/*
		 * <a href="#include-script-./path/jsfile.js@jsname1"></a>
		 * <a href="#include-css-./path/cssfile.css@cssname1"></a>
		 * <a href="#include-text-./path/textfile.txt@textareaid"></a>
		 * <a href="#include-text-./path/textfile.txt@preid"></a>
		 * <a href="#include-text-./path/textfile.txt@<target>">
		 *    <script type="text/javascript">
		 *    function(txt,targetelem){
		 *    	:
		 *    }
		 *    </script>
		 * </a>
		 * <a href="#include-htmlbody-./path/htmlfile@<target>"></a>
		 */
		if(!MP.include){MP.include={};}
		var type=args.shift();
		var url=args.join("-");
		target=G.$(target);
		switch(type){
			case "script":
				MP.include[target]=G.requireJs(url,"utf-8");
				break;
			case "css":
				MP.include[target]=G.requireCss(url,"utf-8");
				break;
			case "text":
				var aj=new G.Ajax();
				aj.get(url,null,(function(txt){
					var target=this.t,e=this.e;
					switch(target.tagName.toLowerCase()){
						case "textarea":
							target.value=txt;
							break;
						case "pre":
							target.innerHTML=G.esc(txt);
							break;
						default:
							var scr=G.$C({t:"script"},e)[0];
							if(scr){
								var func;
								eval("func="+scr);
								if(func){func(txt,target);}
							}else{
								target.innerHTML=txt;
							}
					}
				}).bindThis({t:target,e:e}));
				break;
			case "htmlbody":
				var ifr=new G.IFrame();
				ifr.load(url,function(w,d){
					target.innerHTML=d.body.innerHTML;
					CONSOLE.log("#include-htmlbody:"+G.getXPath(target)+"\n"+d.body.innerHTML);
					var links=G.$S("a.oninclude",target);
					CONSOLE.log("#include-htmlbody:found "+links.length+" a.oninclude in"+G.getXPath(target));
					G.each(links,function(e){
						MP.pseudoClick(e);
						G.removeElement.later(5000,this,e);
					});
					G.removeElement.later(20000,this,ifr.element);
				});
				break;
		}
	},
	"watch":function(target,args,e){
		MP.watchtimer=MP.watchtimer||{scrollbottom:{},exec:{}};
		var interval=G.atoi(args.shift(),200);
		var cmd=args.shift();
		switch(cmd){
			case "scrollbottom":
				var margin=args.shift();
				if(G.atoi(margin,-1)==-1){
					margin=30;args.unshift(margin);
				}else{
					margin=G.atoi(margin);
				}
				var screlm=G.$(args.shift());
				var appendcmd=args.join("-");
				var tmplid=target;
				MP.watchtimer.scrollbottom[e.href]=setInterval((function(p,tmplid,margin){
						if(p.offsetHeight==0){return;} // hidden
						if(!MP.tmpl[tmplid]||MP.tmpl[tmplid].busy||MP.tmpl[tmplid].aborted){return;}
						if(!MP.tmpl[tmplid].hasnext){return;}
						if(p.scrollHeight<=p.offsetHeight){
							MP.pseudoClick("#"+appendcmd+"-append@"+tmplid);
							return;
						}
						//CONSOLE.log([p.scrollTop,p.offsetHeight,p.scrollHeight-30]);
						if(p.scrollTop+p.offsetHeight>p.scrollHeight-margin){
							MP.pseudoClick("#"+appendcmd+"-append@"+tmplid);
							return;
						}
					}).bindArgs(screlm,tmplid,margin),interval);
				break;
			case "exec":
				var func;
				if(args[0]){
					eval("func="+args.shift());
				}else{
					var scr=G.$C({t:"script"},e)[0];
					if(scr){
						eval("func="+scr.text||scr.innerText||scr.textContent);
					}
				}
				if(func){
					func.apply(e,args);
					MP.watchtimer.exec[e.href]=setInterval((function(func){func();}).bindArgs(func),interval);
				}else{
					CONSOLE.error(e.href+":function not found");
				}
				break;
		}
	},
	"scrollintoview":function(target,args,e){
		// scrollintview-<elemsel>@<scrollelemsel>
		var elm=searchParentChildren(args.join("-"),e)[0];
		var scr=searchParentChildren(target,e)[0];
		if(!scr){
			scr=document.documentElement;
			if(e.scrollIntoView){
				e.scrollIntoView();
				return;
			}
		}
		var pos=G.pos(elm);
		var spos=G.pos(scr);
		if(pos.bottom>spos.bottom){
			scr.scrollTop+=pos.bottom-spos.bottom+10;
			pos.top-=pos.bottom-spos.bottom+10;
		}
		if (pos.top < spos.top) {
			scr.scrollTop-=spos.top-pos.top+10;
		}
	},
	"wizard":function(target,args,e){
		var cmd=args.shift();
		var func=args.shift();
		if(target=="here"||!target){
			target=G.$SA(e,".wizard").id;
		}
		var w=MP.wizards[target];
		if(!w){
			w=new G.Wizard(G.$(target));
			MP.wizards[target]=w;
		}
		if(func){
			eval("func="+func);
		}else{
			var scr=G.$C({t:"script"},e)[0];
			if(scr){
				try{
					eval("func="+(scr.text||scr.innerText||scr.textContent));
				}catch(ex){
					CONSOLE.error("#wizard:script:"+G.dump(ex));
				}
			}
		}
		switch(cmd){
			case "start": w.start(func); break;
			case "enable": w.enable(G.atoi(args[0]),func); break;
			case "next":  w.next(func); break;
			case "prev":  w.prev(func); break;
			case "cancel": w.cancel(func); break;
			case "complete": w.complete(func); break;
			default: CONSOLE.error("#wizard:unknown cmd:"+cmd);
		}
	},
	"wait":function(target,args,e){
		var seq=this;
		this.pause(G.atoi(args[0]));
	},
	"exec":function(target,args,e){
		var func;
		//var te=target?searchParentChildren(target,e):e;
		var te=e;
		if(args[0]){
			eval("func="+args.shift());
			if(func){
				func.apply(te,args);
			}
		}else{
			var scr=G.$C({t:"script"},e)[0];
			if(scr){
				scr=scr.text||scr.innerText||scr.textContent;
				var func;
				eval("func="+scr);
				if(func){func.call(te,e);}
			}
		}
	},
	"cursor":function(target,args,e){
		// #cursor-<set|unset>-<classname>-<cursorname>-<scrollselector>@<parentselector>[/<childselector>]
		MP.cursors=MP.cursors||{};
		var cmd=args.shift();
		var className=args.shift();
		var cname=args.shift();
		var scr=args.join("-");

		var te=searchParentChildren(target,e);

		if(MP.cursors[cname]){
			G.removeClassName(MP.cursors[cname],className);
		}
		if(cmd=="set"){
			MP.cursors[cname]=te[0];
			G.addClassName(MP.cursors[cname],className);
			if(scr){
				// scrollintoview
				scr=searchParentChildren(scr,e)[0];

				var pos=G.pos(te[0]);
				var spos=G.pos(scr);
				if(pos.bottom>spos.bottom){
					scr.scrollTop+=pos.bottom-spos.bottom+10;
					pos.top-=pos.bottom-spos.bottom+10;
				}
				if (pos.top < spos.top) {
					scr.scrollTop-=spos.top-pos.top+10;
				}
			}
		}
	},
	"form":function(target,args,e){
		if(target){
			target=G.$(target);
		}else{
			target=G.$SA(e,"form");
		}
		var scr=G.$C({t:"script"},e)[0];
		var cmd=args.shift();
		switch(cmd){
			case "submit":
				target.submit();
				break;
			case "reset":
				target.reset();
				break;
		}
	},
	"popupwin":function(target,args,e){
		//target=args.shift();
		var href=e.href.replace(/#popupwin-.*$/,"");
		if(href){
			window.open(href,target||e.target||"_blank",args[0]);
		}
	},
	"click":function(target,args,e){
		var notfoundmode=args.shift();
		switch(notfoundmode){
			case "wait":
				((function(target,e){
					var te=searchParentChildren(target,e);
					G.each(te,function(e){MP.pseudoClick(e);});
				}).bindArgs(target,e)).poll((function(target,e){
					var te=searchParentChildren(target,e);
					return te[0];
				}).bindArgs(target,e));
				break;
			case "ignore":
			default:
				var te=searchParentChildren(target,e);
				if(!te[0]){
					CONSOLE.warn("#click:notfound:"+target+" in "+G.getXPath(e));
				}
				G.each(te,function(e){MP.pseudoClick(e);});
				break;
		}
	},
	"moveelement":function(target,args,e){
		(function(){
			G.$(target,true).appendChild(G.$(args.join("-")));
		}).poll(function(){
			return G.$(target,true)&&G.$(args.join("-"));
		});
		return;
		
		// IE6 だとhrefに#を2個以上は変なことになるっぽいので注意
        (function(){
                var se=G.$(args.join("-"),true)?[G.$(args.join("-"),true)]:searchParentChildren(args.join("-"),e);
                var te=G.$(target,true)||searchParentChildren(target,e)[0];
                G.each(se,function(e){
                        try{
                                te.appendChild(e);
                        }catch(ex){}
                });
        }).poll(function(){return G.$(target,true)||MP.searchParentChildren(target,e)[0]});

		var se=searchParentChildren(args.join("-"),e);
		var te=searchParentChildren(target,e)[0];
		(function(){
			if(te){
				G.each(se,function(e){
					try{
						te.appendChild(e);
					}catch(ex){}
				});
	
			}else{
				setTimeout(arguments.callee, 50);
			}
		})()
	}
};
MP.linkClickHandlers=linkClickHandlers;

function linkClickHandlersExtend(cmd,f){
	/* usage:
	 * linkClickHandlersExtend(function(orgf,target,args,e,onapply,oncomp){
	 *    :
	 *   orgf(target,args,e,onapply,oncomp);
	 *    :
	 *  }
	 */
	if(MP.linkClickHandlers[cmd]){
		MP.linkClickHandlers[cmd]=MP.linkClickHandlers[cmd].hook(f);
	}else{
		MP.linkClickHandlers[cmd]=(function(){}).hook(f);
	}
}
MP.linkClickHandlersExtend=linkClickHandlersExtend;

function linkClickHandlersExec(hash,e,ev){
	if(!hash.replace(/^([^a-zA-Z0-9]*)([^a-zA-Z0-9].*)?$/,"$1") in linkClickHandlers){return false;}
	if(hash.indexOf("&&")>=0){ // 遅延実行のチェーンとかどうするかね。実装したいな。
		var haserror=false;
		var cmds=hash.split("&&");
		var seq=new G.Seq();
		seq.toString=function(){return "linkClickHandlersSeq:"+hash;};
		MP.lchs=MP.lchs||{};MP.lchs[hash]=seq;
		G.each(hash.split("&&"),function(v){
			v=v.replace(/^#/,"");
			var cmd=v.split("-")[0];
			if(MP.linkClickHandlers[cmd]){
				seq.add((function(v,e,ev,seq){
					var ret=linkClickHandlersExec.call(seq,v,e,ev);
					return !ret;
				}).bindArgs(v,e,ev,seq));
			}else{
				CONSOLE.error("linkClickHandlersExec:seq:unknown cmd:"+v);
				haserror=true;
			}
		});
		if(haserror){return false;}
		MP.lcks=MP.lcks||{_cnt:0};
		MP.lcks[MP.lcks._cnt]=seq;
		seq.start((function(c){delete MP.lcks[c]}).bindArgs(MP.lcks._cnt));
		MP.lcks._cnt++;
		//return !breaked;
		return true;
	}
	var m=hash.match(/^([^@]+)(@(.*))?$/);
	if(m&&m[1]){
		var c=m[1].split("-"),cmd=c.shift(),ret; // #aaa-bbb-ccc@ddd : cmd:aaa, args:[bbb,ccc], target:ddd
		if(!linkClickHandlers[cmd]){return false;}
		CONSOLE.log("linkClickHandlersExec:linkClickHandlers["+cmd+"]("+m[3]+",["+c.join(",")+"],"+G.getXPath(e,null,["id","class","href"])+")");
		if(e.onclick){
			ret=(false===e.onclick.call(e,ev)); // onclick="return false;" prevent #handler
		}
		if(ret){
			CONSOLE.log("linkClickClickHandlersExec:CANCEL by onclick return false");
		}else{
			(linkClickHandlers[cmd]).call(this,m[3],c,e);
			CONSOLE.log("linkClickHandlersExec:SUCCESS");
		}
		return true;
	}
	return false;
}
MP.linkClickHandlersExec=linkClickHandlersExec;

function allClickHandler(oev){
	var ev,a;
	if(oev&&oev._parsed){ev=oev;}else{ev=G.parseEvent(oev);}
	if(!ev.click.l){return;}
	// CONSOLE.info("allClickHandler:"+G.getSelectorPath(ev.target));
	if(ev.target.tagName&&ev.target.tagName.toLowerCase()=="a"){a=ev.target;}
	else{a=G.findAncestor(ev.target,{t:/^a$/i});}
	if(a){
		// CONSOLE.log("allClickHandler:a tag:"+G.getSelectorPath(a)+"\nhref:"+a.getAttribute("href",2));
		var hash=a.getAttribute("href",2);
		if(hash){
			hash=hash.replace(/^[^#]*/,"").replace(/^#/,"");
			CONSOLE.log("allClickHandler:hash:"+hash);
			//CONSOLE.info("allClickHandler:call linkClickHandlersExec:"+uri.hash);
			if(linkClickHandlersExec(hash,a,ev)){
				return G.stopDefault(ev,true);
			}
		}
	}
	//return G.stopBubble(ev,false);
}

/*
(function(){
	G.addEvent(document,"click",allClickHandler);
}).poll(function(){
	return MP.djinitialized
});
*/
G.addEvent(document,"click",allClickHandler);

function pseudoClick(elm,evparams){ 
	evparams=evparams==undefined?{}:evparams;
	if(typeof elm == "string"){
		var e=G.$("pseudo-click-elem",true);
		if(!e){
			e=document.createElement("A");
			e.id="pseudo-click-elem";
			e.style.cssText="position:absolute;font-size:0;line-height:0;height:0;width:0;left:-1000;top:-1000;";
			document.body.appendChild(e);
			e.target="_blank";
		}
		e.href=location.href.replace(/#.*$/,"")+elm;
		elm=e;
	}
	if(G.isMSIE){
		try{
			//elm.focus();
		}catch(ex){}
	}

//	if(!allClickHandler({target:elm,type:"click",click:{l:true},_parsed:true})){
	if(true){
		var type="click";
		if(!G.isMSIE){ 
			var evt = document.createEvent('MouseEvents');
			evt.initEvent( type, true, true );
			evt.element = function (){ return evt.target; }
			G.each(evparams,function(v,p){evt[p]=v;});
			elm.dispatchEvent(evt);
		}else if(document.createEventObject){ // IE
			var evt = document.createEventObject();
			evt.element = function (){ return evt.srcElement; }
			G.each(evparams,function(v,p){evt[p]=v;});
			elm.fireEvent('on'+type, evt);
		}else{
			// no idea
		}
	}
	
	//allClickHandler({target:elm,srcElement:elm,type:"click",button:1,which:1});
}
MP.pseudoClick=pseudoClick;

/**
 * same as <a href="#toggle-defclass-toggleclass@taget">...</a>
 * @param {Object} e
 * @param {Object} defclass
 * @param {Object} toggleclass
 * @param {Object} target
 */
function linkToggle(e,target,defclass,toggleclass){
	MP.linkClickHandlers["toggle"](target,[defclass,toggleclass],e);
}
MP.linkToggle=linkToggle; 


/**
 * generate html window
 * this.e : all div
 * this.b : content box ( size fixed on setpos)
 * this.c : contents in content box
 * @param {Object} contelem elements for window content
 * @param {Object} style {"id":"<windowid>","cssfile":"<style css file path>","style":"<css styles(with replace ${id})>", "html":{"<selector>":"<inner html(with replace ${id})>"}}
 */
function Window(contelem,style){
	var iselem=(typeof contelem=="string")?false:true;
	Window.windows.push(this);
	var e=document.createElement("div");
	this.e=e; // window outer box
	this.id=Window.cnt++;
	var wid=(style&&style.id)?style.id:"window-"+this.id;
	this.wid=wid;
	if(!Window._s){
		Window._s=G.setStyleSheet(
			".window-box { display:block; position:absolute; top:0; left:0; visibility:hidden; z-index:100;} "+
			".window { position:relative; z-index:101; border:none; width:100%; height:100%;  } "+
			".window-controls-1 { position:absolute; } "+
			".window-controls-2 { position:absolute; }"+
			".window-statusbar  { position:absolute; top:0; height:100%; } "+
			".window-resizer { cursor:se-resize; position:absolute; bottom:0; right:0; width:15px; height:15px; z-index:102; }  "+
			".window .draghandle { cursor:move; } "+
			".window .resizehandle-n { cursor:n-resize; }  "+
			".window .resizehandle-e { cursor:e-resize; }  "+
			".window .resizehandle-w { cursor:w-resize; }  "+
			".window .resizehandle-s { cursor:s-resize; }  "+
			".window .resizehandle-se { cursor:se-resize; }  "+
			".window .resizehandle-sw { cursor:sw-resize; }  "+
			".window .resizehandle-ne { cursor:ne-resize; }  "+
			".window .resizehandle-nw { cursor:nw-resize; }  "+
			".window-mask { position:absolute; top:0; left:0; width:100%; height:100%; border:none; /* z-index:99; */ } "
		);
	}
	e.innerHTML=G.tmpl(Window._html,{id:this.wid});
	e.className="resizetarget dragtarget window-box";
	//a.id="window-"+this.id+"-box";
	e.id=wid;
	document.body.appendChild(e);

	this.b=G.$(wid+"-cont-box");

	if(style){
		this.style={}
		if(style.cssfile){
			this.style.cssfile_style=G.requireCss(style.cssfile);
		}
		if(style.stylepath){
			G.requireCssTmpl(style.stylepath,{id:wid},(function(s,news){
				this.style.stylepath=s;
				this.resetMargins.later(100,this);
			}).bindThis(this));
		}
		if(style.css){
			this.style.css_style=G.setStyleSheet(G.tmpl(style.css,{id:wid}));
		}
		if(style.html){
			G.each(style.html,function(v,p){
				G.$S(p,e)[0].innerHTML=G.tmpl(v,{id:wid});
			});
		}
	}

	this.c=G.$(wid+"-cont"); // #<ID>-cont firstChild
	if (iselem) {this.c.appendChild(contelem);}
	else{this.c.innerHTML=contelem;}
	G.addClassName(this.c,"window-content");

	G.$(wid+"-title").innerHTML="&nbsp";
	this.t=G.$(wid+"-title");

	this.e.style.display = "none";
	this.e.style.visibility = "visible";
	
	this.m=document.createElement("iframe"); this.m.className="window-mask";
	this.e.insertBefore(this.m,this.e.firstChild);

	Draggable.setOnDrop(this.e,(function(pos,e){
		this.setPos(pos.left,pos.top,pos.width,pos.height);
		this.focus();
	}).bindThis(this));
	Resizable.setOnResize(this.e,(function(pos,e){
		this.setPos(pos.left,pos.top,pos.width,pos.height);
		this.focus();
	}).bindThis(this));

}
Window._html=
		"<div class=\"window tmpl-all\" id=\"${id}-inner\">"+
			"<div class=\"window-head tmpl-head\" id=\"${id}-head\">"+
				"<div class=\"tmpl-head-box\">"+
					"<div class=\"tmpl-head-cont draghandle\">"+
						"<div class=\"tmpl-head-title-box\">"+
							"<div class=\"tmpl-head-title window-title\" id=\"${id}-title\"></div>"+
							"<div class=\"tmpl-head-title-right\"><div></div></div>"+ // for IE6
						"</div></div></div>"+
				"<div class=\"tmpl-head-left resizehandle resizehandle-nw\"></div>"+
				"<div class=\"tmpl-head-right resizehandle resizehandle-ne\"></div></div>"+
				"<div class=\"window-controls-1\" id=\"${id}-controls-1\"></div>"+
				"<div class=\"window-controls-2\" id=\"${id}-controls-2\"></div>"+
			"<div class=\"window-body tmpl-body\" id=\"${id}-body\">"+
				"<div class=\"tmpl-body-box\" id=\"${id}-cont-box\">"+
					"<div class=\"tmpl-body-cont\" id=\"${id}-cont\">"+
					"</div></div>"+
				"<div class=\"tmpl-body-left  resizehandle resizehandle-w\" id=\"${id}-left\"></div>"+
				"<div class=\"tmpl-body-right resizehandle resizehandle-e\" id=\"${id}-right\"></div></div>"+
			"<div class=\"window-foot tmpl-foot\" id=\"${id}-foot\">"+
				"<div class=\"tmpl-foot-box\">"+
					"<div class=\"tmpl-foot-cont resizehandle resizehandle-s\">"+
						"<div class=\"window-satusbar\" id=\"${id}-statusbar\"></div>"+
					"</div></div>"+
				"<div class=\"tmpl-foot-left resizehandle resizehandle-sw\"></div>"+
				"<div class=\"tmpl-foot-right resizehandle resizehandle-se\"></div></div>"+
		"</div>"+
		"<div class=\"window-resizer resizehandle resizehandle-se\"></div>";

Window.cnt=0;
Window.windows=[];

Window.prototype.calcMargins=function(f,onset){
	if(f){
		this._margins=null;
	}
	try{
		if (!this._margins) {
			var pl = G.pos(G.$(this.wid+"-left"));
			var pr = G.pos(G.$(this.wid+"-right"));
			var ph = G.pos(G.$(this.wid+"-head"));
			var pf = G.pos(G.$(this.wid+"-foot"));
			this._margins = {
				w: pl.width+pr.width,
				h: ph.height+pf.height
			};
			if(isNaN(this._margins.w)||isNaN(this._margins.h)){
				this._margins=null;
				//this.calcMargins.bindThis(this).bindArgs(true,onset).later(100);
				this.calcMargins.later(100,this,true,onset);
			}
			onset&&onset.later();
		}
	}catch(ex){
		//this.calcMargins.bindThis(this).bindArgs(true,onset).later(100);
		this.calcMargins.later(100,this,true,onset);
	}
};

Window.prototype.resetMargins=function(){
	this.calcMargins(true,(function(){
		var pos=G.pos(this.e),w=pos.width,h=pos.height;
		G.setStyles(this.b,{width:(w-this._margins.w)+"px",height:(h-this._margins.h)+"px"});
	}).bindThis(this));
};

Window.prototype.setPos=function(x,y,w,h){
	if(x===undefined&&y===undefined&&w===undefined&&h===undefined){
		var cs=G.clientSize();
		x=(x===undefined)?Math.floor(cs.width*0.1):x;
		y=(y===undefined)?G.getPageYOffset()+Math.floor(cs.height*0.1):y;
		w=(w===undefined)?Math.floor(cs.width*0.8):w;
		h=(h===undefined)?Math.floor(cs.height*0.8):h;
		CONSOLE.log("MP.Window.setPos():default:"+[x,y,w,h].join(","));
	}
	var dosetpos=(function(x,y,w,h){
		G.setStyles(this.e,{top:y+"px",left:x+"px"});
		this.calcMargins(true,(function calcMarginsBound(w,h){
			if(w!==undefined){
				G.setStyles(this.e,{width:w+"px",height:h+"px"});
				G.setStyles(this.b,{width:(w-this._margins.w)+"px",height:(h-this._margins.h)+"px"});
				//this.onSetpos&&this.onSetpos.bindThis(this).bindArgs(x,y,w,h).later(100);
				this.onSetpos&&this.onSetpos.later(100,this,x,y,w,h);
			}
		}).bindThis(this).bindArgs(w,h));
	}).bindThis(this).bindArgs(x,y,w,h);
	if(G.currentStyle(this.e,"display")=="none"){
		this._onshow=dosetpos;
	}else{
		dosetpos();
	}
};
Window.prototype.show=function(){
	this.e.style.display="block";this.e.style.visibility="visible";
	if(this._onshow){ this._onshow(); this._onshow=null; }
};
Window.prototype.hide=function(){this.e.style.display="none";this.e.style.visibility="hidden";};
Window.prototype.close=function(){G.removeElement(this.m)};
Window.prototype.setTitle=function(str){this.t.innerHTML=G.esc(str);};
Window.prototype.focus=function(){
	G.$(this.wid+"-cont").focus();
	G.click.later(100,this,G.$(this.wid+"-cont"));
};
Window.prototype.moveIntoView=function(){
	var pos=G.pos(this.e);
	var cs=G.clientSize();
	var st=G.getPageYOffset();
	var sl=G.getPageXOffset();
	var x=pos.left,y=pos.top;
	x=Math.min(x,sl+cs.width-pos.width); x=Math.max(x,sl);
	y=Math.min(y,st+cs.height-pos.height);y=Math.max(y,st);
	CONSOLE.log("MP.Window.moveIntoView:"+[x,y].join(","));
	if(pos.x!=x||pos.y!=y){
		this.setPos(x,y);
	}
};
MP.Window=Window;

/* 
 * Draggable.add(element,ondragstart,ondragging(cx,cy),ondrop(cx,cy));
 * 
 */

var Draggable={ondragstarts:{},ondraggings:{},ondrops:{},_cnt:0};
var Droppable={};
var Resizable={onresizes:{},_cnt:0};

// f(ev),this=element
Draggable.setOnDragStart=function(e,f){
	if(!e.id){e.id="draggable-"+Draggable._cnt++;}
	Draggable.ondragstarts[e.id]=f;
};
// f(ev),this=element
Draggable.setOnDragging=function(e,f){
	if(!e.id){e.id="draggable-"+Draggable._cnt++;}
	Draggable.ondraggings[e.id]=f;
};
// f(pos),this=element
Draggable.setOnDrop=function(e,f){
	if(!e.id){e.id="draggable-"+Draggable._cnt++;}
	Draggable.ondrops[e.id]=f;
};

Resizable.setOnResize=function(e,f){
	if(!e.id){e.id="resizable-"+Resizable._cnt++;}
	Resizable.onresizes[e.id]=f;
};

Resizable.dirfuncs={
	"n":function(ev){
		Resizable.resizingElement.style.height
			= Math.max(10, Resizable.orgpos.height - (ev.pos.y - Resizable.resizestartpos.y)) + "px";
		Resizable.resizingElement.style.top
			= Math.max( 0, Math.min(
					Resizable.orgpos.top + Resizable.orgpos.height - 10,
					Resizable.orgpos.top + (ev.pos.y - Resizable.resizestartpos.y)
			)) + "px";
	},
	"s":function(ev){
		Resizable.resizingElement.style.height
			= Math.max(10, Resizable.orgpos.height + (ev.pos.y - Resizable.resizestartpos.y)) + "px";
	},
	"w":function(ev){
		Resizable.resizingElement.style.width
			= Math.max(10, Resizable.orgpos.width  - (ev.pos.x - Resizable.resizestartpos.x)) + "px";
		Resizable.resizingElement.style.left
			= Math.max( 0, Math.min(
					Resizable.orgpos.left + Resizable.orgpos.width -10,
					Resizable.orgpos.left + (ev.pos.x - Resizable.resizestartpos.x)
			)) + "px";
	},
	"e":function(ev){
		Resizable.resizingElement.style.width
			= Math.max(10,Resizable.orgpos.width   + (ev.pos.x - Resizable.resizestartpos.x)) + "px";
	},
	"ne":function(ev){Resizable.dirfuncs["n"](ev);Resizable.dirfuncs["e"](ev);},
	"nw":function(ev){Resizable.dirfuncs["n"](ev);Resizable.dirfuncs["w"](ev);},
	"se":function(ev){Resizable.dirfuncs["s"](ev);Resizable.dirfuncs["e"](ev);},
	"sw":function(ev){Resizable.dirfuncs["s"](ev);Resizable.dirfuncs["w"](ev);}
};

Draggable.dragStart=function(e,ev){
	Draggable.dragging=e;
	Draggable.dragstartpos=ev.pos;
	Draggable._s=G.setStyleSheet("* {cursor:move ! important;}");
	
	var region=G.findAncestor(ev.target,{c:"dragtarget"});
	Draggable.orgpos=G.pos(region||e);
	Draggable.orgpos.width-=2;
	Draggable.orgpos.height-=2;
	
	Draggable.handle=e;
	Draggable.target=region||e;
	
	var div=document.createElement("div");
	div.style.cssText="position:absolute;border:1px dashed black;z-index:1000;"+
		G.tmpl("top:${top}px;left:${left};width:${width}px;height:${height}px;",Draggable.orgpos);
	div.id="dragelement";
	document.body.appendChild(div);
	/*
	 // IEではWindow外mouseupを捕まえられない
	 // http://d.hatena.ne.jp/miya2000/20070306
	 // これではうまくいかん
	if(G.isMSIE){
		div.innerHTML="<img src=\"js/1x1.gif\" style=\"position:absolute;top:0;left:0;width:100%;height:100%;\" onmouseup=\"alert('up')\">"
	}*/
	Draggable.draggingElement=div;
	Draggable.draggingElement.style.top=Draggable.orgpos.top+(ev.pos.y-Draggable.dragstartpos.y)+"px";
	Draggable.draggingElement.style.left=Draggable.orgpos.left+(ev.pos.x-Draggable.dragstartpos.x)+"px";

	if(Draggable.ondragstarts[Draggable.target.id]){
		Draggable.ondragstarts[Draggable.target.id].call(Draggable.target,ev);
	}
};

function ondragstartfunc(ev){
	ev=G.parseEvent(ev);
	if(ev.click.l){
		var e=G.isClass(ev.target,"draghandle")?ev.target:G.findAncestor(ev.target,{c:"draghandle"});
		if(e){
			Draggable.dragStart(e,ev);
			return G.stopBubble(ev,true);
		}
		var e=G.isClass(ev.target,"resizehandle")?ev.target:G.findAncestor(ev.target,{c:"resizehandle"});
		if(e){
			var dir="se";
			G.each(Resizable.dirfuncs,function(v,p){
				if(G.isClass(e,"resizehandle-"+p)){ dir=p; return true; }
			});
			Resizable._dir=dir;
			var cursor=dir+"-resize";
			
			Resizable.resizing=e;
			Resizable.resizestartpos=ev.pos;
			Resizable._s=G.setStyleSheet("* {cursor:"+cursor+" ! important;}");
			
			var region=G.findAncestor(ev.target,{c:"resizetarget"});
			Resizable.orgpos=G.pos(region||e);
			Resizable.orgpos.width-=2;
			Resizable.orgpos.height-=2;
			
			Resizable.handle=e;
			Resizable.target=region||e;
			
			var div=document.createElement("div");
			div.style.cssText="position:absolute;border:1px dashed black;z-index:1000;"+
				G.tmpl("top:${top}px;left:${left}px;width:${width}px;height:${height}px;",Resizable.orgpos);
			div.id="resizeelement";
			document.body.appendChild(div);
			Resizable.resizingElement=div;
			Resizable.resizingElement.style.height=Resizable.orgpos.height+(ev.pos.y-Resizable.resizestartpos.y)+"px";
			Resizable.resizingElement.style.width=Resizable.orgpos.width+(ev.pos.x-Resizable.resizestartpos.x)+"px";

			return G.stopBubble(ev,true);
		}
	}
	//return G.stopBubble(ev,false);
}


function ondragfunc(ev){
	if(!Draggable.dragging&!Resizable.resizing){return;}
	ev=G.parseEvent(ev);
	if(Draggable.dragging){
		
		Draggable.draggingElement.style.top=Draggable.orgpos.top+(ev.pos.y-Draggable.dragstartpos.y)+"px";
		Draggable.draggingElement.style.left=Draggable.orgpos.left+(ev.pos.x-Draggable.dragstartpos.x)+"px";
		
		if(Draggable.ondraggings[Draggable.target.id]){
			Draggable.ondraggings[Draggable.target.id].call(Draggable.target,ev);
		}
		return G.stopBubble(ev,true);
	}
	if(Resizable.resizing){
		Resizable.dirfuncs[Resizable._dir](ev);
		return G.stopBubble(ev,true);
	}
	//return G.stopBubble(ev,false);
}

function ondropfunc(ev){
	if(Draggable.waitDragStart){clearTimeout(Draggable.waitDragStart);}
	if(!Draggable.dragging&!Resizable.resizing){return;}
	if(Draggable.dragging){
		var pos=G.pos(Draggable.draggingElement);
		G.removeStyleSheet(Draggable._s); delete Draggable._s;
		G.removeElement(Draggable.draggingElement);
		Draggable.dragging=false;
		Draggable.draggingElement=null;

		if(Draggable.ondrops[Draggable.target.id]){
			Draggable.ondrops[Draggable.target.id].call(Draggable.target,pos,Draggable.target);
		}else{
			Draggable.target.style.top=pos.top+"px";
			Draggable.target.style.left=pos.left+"px";
		}

		return G.stopBubble(ev,true);
	}
	if(Resizable.resizing){
		var pos=G.pos(Resizable.resizingElement);
		G.removeStyleSheet(Resizable._s); delete Resizable._s;
		G.removeElement(Resizable.resizingElement);
		Resizable.resizing=false;
		Resizable.resizingElement=null;
		if(Resizable.onresizes[Resizable.target.id]){
			Resizable.onresizes[Resizable.target.id](pos, Resizable.target);
		}else{
			Resizable.target.style.left=pos.left+"px";
			Resizable.target.style.top=pos.top+"px";
			Resizable.target.style.width=pos.width+"px";
			Resizable.target.style.height=pos.height+"px";
		}
		return G.stopBubble(ev,true);
	}
	//return G.stopBubble(ev,false);
}

G.addEvent(document,"mousedown",ondragstartfunc);
G.addEvent(document,"mousemove",ondragfunc);
G.addEvent(document,"mouseup",ondropfunc);

/*
G.addEvent(document,"dragstart",ondragstartfunc);
G.addEvent(document,"drag",ondragfunc);
G.addEvent(document,"dragend",ondropfunc);

G.addEvent(document,"selectstart",ondragstartfunc);
*/

MP.Resizable=Resizable;
MP.Draggable=Draggable;

function allEventHandler(ev){
	function rstr(str,len){var l=str.length;return (l-3>len?"..."+str.substring(l-len,l):str);}
	ev=G.parseEvent(ev);
	//console.log(ev.type+":"+rstr(G.getXPath(ev.target),60));
	return G.stopBubble(ev,false);
}
/*
G.each([
	"click","mousedown","mouseup",//"mousemove",
	"mouseover","mouseout",
	"keypress","keyup","keydown",
	"focus","blur","change","select","reset","submit"
],function(v){G.addEvent(document,v,allEventHandler);});
*/

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

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 Decorate(e,className,innerflg){
	var iselem=(typeof e=="string")?false:true;
	var id=Decorate._cnt++;
	this.id=id;
	var html1=G.tmpl(Decorate._html1,{id:id,"class":className||""});
	var html2=G.tmpl(Decorate._html2,{id:id,"class":className||""});

	var df=document.createDocumentFragment();
	if(!iselem){
		var ediv=document.createElement("div");
		ediv.innerHTML=e;
		e=ediv;
	}
	while(e.firstChild){
		df.appendChild(e.firstChild);
	}

	var div=document.createElement("div");
	div.className="decorated";
	div.id="decorated-"+id;
	div.innerHTML=html1+((iselem)?"":e)+html2;
	document.body.appendChild(div);
	
	if(innerflg){
		G.$("decorated-"+id+"-cont").appendChild(df);
		e.appendChild(div);
	}else{
		var p=e.parentNode,ns=e.nextSibling;
		G.$("decorated-"+id+"-cont").appendChild(e);
		e.appendChild(df);
		if(ns){p.insertBefore(div,ns);}else{p.appendChild(div);}
	}
	
	/*
	if(iselem){
		var p=e.parentNode,ns=e.nextSibling;
		G.$("decorated-"+id+"-cont").appendChild(e);
		if(ns){p.insertBefore(div,ns);}else{p.appendChild(div);}
	}
	*/
	return div;
}
Decorate._cnt=0;
Decorate._html1=""
	+"<div class=\"tmpl-head ${class}\">"
		+"<div class=\"tmpl-head-box\"><div class=\"tmpl-head-cont\">"
			+"<div class=\"tmpl-head-title-box\">"
				+"<div class=\"tmpl-head-title\" id=\"decorated-${id}-title\"></div>"
				+"<div class=\"tmpl-head-title-right\"><div></div></div>" // for IE6
			+"</div>"
		+"</div></div>"
		+"<div class=\"tmpl-head-left\"></div>"
		+"<div class=\"tmpl-head-right\"></div>"
	+"</div>"
	+"<div class=\"tmpl-controls-1\" id=\"decorated-${id}-controls-1\"></div>"
	+"<div class=\"tmpl-controls-2\" id=\"decorated-${id}-controls-2\"></div>"
	+"<div class=\"tmpl-body ${class}\">"
		+"<div class=\"tmpl-body-box\"><div class=\"tmpl-body-cont\" id=\"decorated-${id}-cont\">";
Decorate._html2=""
		+"</div></div>"
		+"<div class=\"tmpl-body-left\"></div>"
		+"<div class=\"tmpl-body-right\"></div>"
	+"</div>"
	+"<div class=\"tmpl-foot ${class}\">"
		+"<div class=\"tmpl-foot-box\"><div class=\"tmpl-foot-cont\"></div></div>"
		+"<div class=\"tmpl-foot-left\"></div>"
		+"<div class=\"tmpl-foot-right\"></div>"
	+"</div>";
MP.Decorate=Decorate;

/*
 * cfg: {
 * 	title:<title>,
 *  desc:<desc>,
 *  dqf:{<default feeds search query>( channel_id:[...]|words:{"category":[...],"global":[...],..}  )}
 * 	dqe:{<default entries search query>( system_category:[...],channel_id:[...]|words:{...} )},
 *  dqs:{<deafult search query>( channel_id:[],...,words:{query:"*D+ \"category\"}) }
 *  tabs:["newest","feeds","search"],
 *  tabs_init:"newest"
 * }
 */

function SmartParts(cfg, stylepath, cssparams){

	this.id = SmartParts._cnt++;
	this.stylepath=stylepath;
	
	cssparams=cssparams?cssparams:{};
	cssparams.id="msmp-"+this.id;
	G.requireCssTmpl(stylepath,cssparams,(function(linkelm,str){
		this._s=linkelm;
	}).bindThis(this));

	this.cfg = cfg;
	if(!cfg.tabs){cfg.tabs=["newest","feeds","search"];}
	if(!cfg.tabs_init){cfg.tabs_init="newest";}
	
	//this.channels=cfg._allchannels;
	var html = G.tmpl(SmartParts._htmltmpl["default"], {
		id: this.id
	}).replace(/#([HAJ]?)\{/g, "$$$1{");
	var div = document.createElement("div");
	div.className = "msmp";

	div.id = "msmp-" + this.id;
	div.innerHTML = html;
	
	if (!SmartParts._tmpdiv) {
		SmartParts._tmpdiv = document.createElement("div");
		SmartParts._tmpdiv.style.display = "none";
		document.body.appendChild(SmartParts._tmpdiv);
	}
	SmartParts._tmpdiv.innerHTML = "";
	SmartParts._tmpdiv.appendChild(div);
	//MP.Decorate(G.$("msmp-"+this.id+"-tabs-contbox"),"inner");
	//this.e = MP.Decorate(div, "outer");
	this.e = MP.Decorate(div);
	
	G.each(["-title", "-controls-1", "-controls-2"], function(v){
		$(this.e.id + v).id = "msmp-" + this.id + v
	}, this);
	
	this.e.id = "msmp-" + this.id;
	this.e.className = "msmp-box";
	
	this.tmpl = {};
	//G.each(["newest", "feeds", "search"], function(v){
	G.each(cfg.tabs, function(v){
		var tmplid = "msmp-" + this.id + "-" + v + "-list";

		//var tmpl = new G.HtmlElementTemplaterSeq(G.$(tmplid, true)/*,{vh:"#"}*/);
		var tmpl = new G.HtmlElementTemplater(G.$(tmplid, true)/*,{vh:"#"}*/);
		tmpl.seq={add:function(f){return f&&f();}};
		tmpl.tmpl=tmpl;
		this.tmpl[v] = tmpl;

		MP.tmpl[tmpl.tmpl.e.id] = tmpl;
		var dq=({newest:this.cfg.dqe,feeds:this.cfg.dqf,search:this.cfg.dqs})[v];
		MP.search[tmplid] = {
			tmplid:tmplid,
			offset: 0,
			limit: dq.limit||10,
			dq: dq,
			parts: this
		}
	}, this);
	
	G.$("msmp-"+this.id+"-title", true).innerHTML=G.esc(cfg.title);
	if(cfg.desc){
		G.$("msmp-"+this.id+"-desc", true).innerHTML=G.esc(cfg.desc);
	}else{
		G.$("msmp-"+this.id+"-desc").innerHTML="";
		G.$("msmp-"+this.id+"-desc").style.display="none";
	}
	
	SmartParts._tmpdiv.removeChild(this.e);

	if(false&&this.cfg.dqf){
		getAllFeeds(cfg.dqf,(function(cids){
			this._allChannels=cids;
			
			var handler = {};
			handler["msmp-" + this.id + "-tabs_newest:init"] = (function(cont, tab, obj){
				MP.linkClickHandlers["search"](this.tmpl.newest.tmpl.e.id, []);
			}).bindThis(this);
			handler["msmp-" + this.id + "-tabs_feeds:init"] = (function(cont, tab, obj){
				MP.linkClickHandlers["searchfeed"](this.tmpl.feeds.tmpl.e.id, []);
			}).bindThis(this);
			handler["msmp-" + this.id + "-tabs_search:init"] = (function(cont, tab, obj){
				MP.linkClickHandlers["search"](this.tmpl.search.tmpl.e.id, []);
			}).bindThis(this);
			
			this.tabs = new G.Tabs(G.$("msmp-" + this.id + "-tabs", true), handler);
	
			if(this.cfg.tabs_init){
				this.tabs.enable(G.$("msmp-"+this.id+"-tabs_"+cfg.tabs_init));
			}
	
		}).bindThis(this));

	}else{
			
			var handler = {};
			handler["msmp-" + this.id + "-tabs_newest:init"] = (function(cont, tab, obj){
				MP.linkClickHandlers["search"](this.tmpl.newest.tmpl.e.id, []);
			}).bindThis(this);

			handler["msmp-" + this.id + "-tabs_feeds:init"] = (function(cont, tab, obj){
				MP.linkClickHandlers["searchfeed"](this.tmpl.feeds.tmpl.e.id, []);
			}).bindThis(this);

			handler["msmp-" + this.id + "-tabs_search:init"] = (function(cont, tab, obj){
				MP.linkClickHandlers["search"](this.tmpl.search.tmpl.e.id, []);
			}).bindThis(this);
			
			(function initPartsTabHandlers(handler){
				this.tabs = new G.Tabs(G.$("msmp-" + this.id + "-tabs", true), handler);
				if(this.cfg.tabs_init){
					this.tabs.enable.later(500,this.tabs,G.$("msmp-"+this.id+"-tabs_"+cfg.tabs_init));
				}
			}).bindThis(this).bindArgs(handler).poll((function(){
				return G.$("msmp-" + this.id + "-tabs", true);
			}).bindThis(this));
	}

	MP.parts[this.id]=this;

}


SmartParts.prototype.search=function(form){
	var q=G.$("msmp-"+this.id+"-search-q").value||"";
	var arg=["global",q,"0,10"];
	MP.linkClickHandlers["search"]("msmp-"+this.id+"-search-list",arg);
}

SmartParts._cnt=0;
SmartParts._stylestmpl={};
SmartParts._htmltmpl={
	"default":
		"<div id=\"msmp-${id}-desc\">desc</div>"+
		"<div class=\"tabs\" id=\"msmp-${id}-tabs\">"+
			"<a class=\"tab\" id=\"msmp-${id}-tabs_newest\">最新</a>"+
			" | <a class=\"tab\" id=\"msmp-${id}-tabs_search\">検索</a>"+
			" | <a class=\"tab\" id=\"msmp-${id}-tabs_feeds\">情報源</a>"+
			//"<div class=\"tab\" id=\"msmp-${id}-tabs_newest\"><a href=\"#\">最新</a></div><span class=\"tabright\">&nbsp;</span>"+
			//"<div class=\"tab\" id=\"msmp-${id}-tabs_search\"><a href=\"#\">検索</a></div><span class=\"tabright\">&nbsp;</span>"+
			//"<div class=\"tab\" id=\"msmp-${id}-tabs_feeds\"><a href=\"#\">情報源</a></div><span class=\"tabright\">&nbsp;</span>"+
		"</div>"+
		"<div id=\"msmp-${id}-tabs-contbox\" class=\"msmp-tabconts\">"+
			"<div class=\"scrollarea\">"+
			"<div class=\"tabcont msmp-tabcont-newest\" id=\"msmp-${id}-tabs_newest_cont\">"+
				//"<div class=\"msmp-list-navi msmp-list-navi-top\" id=\"msmp-${id}-newest-list-navi\"></div>"+
				"<div id=\"msmp-${id}-newest-list-navi\" class=\"msmp-list-navi msmp-list-navi-top\">"+
					"<span class=\"for-navi-hasprev\">"+
						"<a __href=\"#search-prev@#{target}\">&laquo;前の#{limit}件</a>"+
						" | <a __href=\"#search-page-1@#{target}\">最初のページ</a>"+
					"</span>"+
					"<span> ${paging} </span>"+
					"<span class=\"for-navi-hasnext\">"+
						" <a class=\"for-navi-next\" __href=\"#search-next@#{target}\">次の#{limit}件&raquo;</a>"+
					"</span>"+
				"</div>"+
				"<ul class=\"msmp-entries\" id=\"msmp-${id}-newest-list\">"+
					"<li class=\"template\"><span class=\"#{_className}\">${_idx}. <a __href=\"#entry-#{item_id}@newentrywintmpl-allentrywin/msmp-${id}-search-list\" title=\"${pub_date_local} : #A{channel_title}より [${_description_short}]\">#H{item_title}</a></span></li>"+
					"<li class=\"for-template-notfound\">情報はありません</li>"+
					"<li class=\"for-template-processing\">Loading...</li>"+
					"<li class=\"for-template-abort\">Error</li>"+
				"</ul>"+
				"<div class=\"msmp-list-navi msmp-list-navi-bottom\" id=\"msmp-${id}-newest-list-navi-2\"></div>"+
			"</div>"+
			"<div class=\"tabcont msmp-tabcont-search\" id=\"msmp-${id}-tabs_search_cont\">"+
				"<form onsubmit=\"try{MP.parts[${id}].search(this)}catch(ex){CONSOLE.error(G.dump(ex))}finally{return false;}\" id=\"msmp-${id}-search\">"+
					"<input type=\"text\" name=\"q\" id=\"msmp-${id}-search-q\"/>"+
					" <input type=\"submit\" value=\"検索\"/>"+
					" <a href=\"#search@msmp-${id}-search-list\" onclick=\"this.parentNode.reset()\">リセット</a>"+
				"</form>"+
				//"<div class=\"msmp-list-navi msmp-list-navi-top\" id=\"msmp-${id}-search-list-navi\"></div>"+
				"<div id=\"msmp-${id}-search-list-navi\" class=\"msmp-list-navi msmp-list-navi-top\">"+
					"<span class=\"for-navi-hasprev\">"+
						"<a __href=\"#search-prev@#{target}\">&laquo;前の#{limit}件</a>"+
						" | <a __href=\"#search-page-1@#{target}\">最初のページ</a>"+
					"</span>"+
					"<span>${paging}</span>"+
					"<span class=\"for-navi-hasnext\">"+
						"<a class=\"for-navi-next\" __href=\"#search-next@#{target}\">次の#{limit}件</a>"+
					"</span>"+
				"</div>"+
				"<ul class=\"msmp-entries\" id=\"msmp-${id}-search-list\">"+
					"<li class=\"template\"><span class=\"#{_className}\">${_idx}. <a __href=\"#entry-#{item_id}@newentrywintmpl-allentry/msmp-${id}-search-list\" title=\"#A{channel_title}\">#H{item_title}</a> (${pub_date_local}) </span></li>"+
					"<li class=\"for-template-notfound\">検索結果はありません</li>"+
					"<li class=\"for-template-processing\">Loading...</li>"+
					"<li class=\"for-template-abort\">Error</li>"+
				"</ul>"+
				"<div class=\"msmp-list-navi msmp-list-navi-bottom\" id=\"msmp-${id}-search-list-navi-2\"></div>"+
			"</div>"+
			"<div class=\"tabcont msmp-tabcont-feeds\" id=\"msmp-${id}-tabs_feeds_cont\">"+
				//"<div class=\"msmp-list-navi msmp-list-navi-top\" id=\"msmp-${id}-feeds-list-navi\"></div>"+
				"<div id=\"msmp-${id}-feeds-list-navi\" class=\"msmp-list-navi msmp-list-navi-top\">"+
					"<span class=\"for-navi-hasprev\">"+
						"<a __href=\"#searchfeed-prev@#{target}\">&laquo;前の#{limit}件</a>"+
						" | <a __href=\"#searchfeed-page-1@#{target}\">最初のページ</a>"+
					"</span>"+
					"<span> ${paging} </span>"+
					"<span class=\"for-navi-hasnext\">"+
						" <a class=\"for-navi-next\" __href=\"#searchfeed-next@#{target}\">次の#{limit}件&raquo;</a>"+
					"</span>"+
				"</div>"+
				"<ul class=\"msmp-feeds\" id=\"msmp-${id}-feeds-list\">"+
					//"<li class=\"template\"><a __href=\"#feed-#{channel_id}\">#H{title}</a></li>"+
					"<li class=\"template\">"+
					  "<a title=\"情報源を新しいウィンドウで開く\" __href=\"#{link}\" target=\"_blank\">#H{title}</a>"+
					  " <a title=\"情報源のRSSをRSSリーダーで購読\" __href=\"#subscribe-#{channel_url}\" class=\"icon\"><img src=\"img/rss.gif\"/></a></li>"+
					"<li class=\"for-template-notfound\">情報源を検索できませんでした</li>"+
					"<li class=\"for-template-processing\">Loading...</li>"+
					"<li class=\"for-template-abort\">Error</li>"+
				"</ul>"+
				"<div class=\"msmp-list-navi msmp-list-navi-bottom\" id=\"msmp-${id}-feeds-list-navi-2\"></div>"+
			"</div>"+
		"</div>"
};
MP.SmartParts=SmartParts;

function processPageInit(e){
	e=e||document.body;
	var seq=new G.Seq(1);
	var a=G.$S("a.pageinit",e);
	CONSOLE.info("MP.processPageInit:found "+a.length+" a.pageinit");
	G.each(a,function(e){
		seq.add((function(e){
			//e.innerHTML="processing";
			MP.pseudoClick(e);
			G.removeElement(e);
		}).bindArgs(e));
	});
	seq.start();
}
MP.processPageInit=processPageInit;

/*
function setOnLoadHtml(f){
	if(setOnLoadHtml._loaded){return f();}
	if(document.readyState&&G.isSafari){
		f.poll(function(){
			return document.readyState == "loaded" || document.readyState == "complete";
		});
	}else if(document.readyState&&G.isMSIE){
		var script=document.createElement("script");
		script.src="javascript:void(0)";
		script.defer="defer";
		script.onreadystatechange = function() {
		  if (this.readyState == "complete") {
		    f(); // call the onload handler
		    this.onreadystatechange = null;
		  }
		};
	}else{
		if(window.addEventListener){
			G.addEvent(document,"DOMContentLoaded",f);
		}
		G.addEvent(window,"load",f);
	}
}
MP.setOnLoadHtml=setOnLoadHtml;
*/

MP.setOnLoadHtml(function(){
	MP.processPageInit();
});

// auto focus scrollable element
/*
G.addEvent(document,"mouseover",function(ev){
	ev=G.parseEvent(ev);
	var le=MP._lastFocusedScrollElement;
	var sce=G.hasScrollBar(ev.target,true)?
			ev.target:
			G.findAncestor(ev.target,{f:function(e){return G.hasScrollBar(e,true);}});
	if(sce&&sce!=document.body.parentNode&&le!=sce){
		if(le){
			G.removeClassName(le,"scrfocused");
		}
		MP._lastFocusedScrollElement=sce;
		G.addClassName(sce,"scrfocused");
		try{(sce.contentWindow||sce).focus()}catch(ex){}
	}
});
*/

MP._loadstatus="complete";
MP.initialized=true;
CONSOLE.log("parts.js:init:end");

} // function init()

})(MP);


}

