/////////////////////////////////////////////////////////////////////////////////////
// global
var
 g_cats
,g_ext=external
,$$=document.getElementById
,g_setting=g_ext.setting
,g_app=g_ext.app
,g_initBookmark=false
,g_defBookmarkGuid=""
,g_initToolbar=false
,g_initAccel=false
,g_initSearch=false
,g_initUserAgent=false
,g_initMouseAction=false
,g_initScriptSetting=false
,g_initUrlAction=false
,g_urlAction
,g_initProxy=false
,g_proxyList
,g_defaultTabFont=true
,g_settings=[
	  ["main","startSetting",null]
	, ["main,tab","appStyleSetting",null] 
	, ["main,style","viewStyleSetting",null] 
	, ["main","instanceSetting",null]
	, ["reg","assocSetting",function(){initAssocSetting()}]
	, ["mouse","dropActionSetting",null]
	, ["mouse","mouseGestureSetting",null]
	, ["mouse","mousePlusSetting",null]
	, ["main","pageSetting",null]
	, ["main","jumpListSetting",null]
	, ["main","taskBarSetting",null]
	, ["main","exitSetting",null]
	, ["main","memorySetting",null]
	, ["main","crashSetting",null]
	, ["bookmark,sidebar","bookmarkSetting",function(){initBookmark()}]
	, ["bookmark,sidebar","addBookmarkSetting",null] 
	, ["trident","renderingSetting",null]
	, ["trident","securitySetting",null]
	, ["trident","securityControlSetting",null]
	, ["trident","proxySetting",function(){initProxy()}]
	, ["trident","userAgentSetting",function(){initUserAgent()}]
	, ["trident","featureSetting",null]
	, ["script","scriptSetting",function(){initScriptSetting()}]
	, ["trident,script","pageScriptSetting",null]
	, ["trident","tridentEtcSetting",null]
	, ["tab","newUrlSetting",null]
	, ["tab,search","searchNewTabSetting",null]
	, ["tab","tabStyleSetting",null]
	, ["tab","tabFontSetting",null]
	, ["tab","tabPosSetting",null]
	, ["tab","newTabPositionSetting",null]
	, ["tab","newTabActivateSetting",null]
	, ["tab","closeActiveTabSetting",null]
	, ["tab","selectTabSetting",null]
	, ["tab","lastTabCmdSetting",null]
	, ["tab","tabOptionSetting",null]
	, ["urlaction","urlActionSetting",function(){initUrlAction()}]
	, ["mouse","actionXButtonSetting",function(){initMouseAction()}]
	, ["mouse","actionWithButtonSetting",function(){initMouseAction()}]
	, ["tab,mouse","actionTabItemSetting",function(){initMouseAction()}]
	, ["tab,mouse","actionTabBkgdSetting",function(){initMouseAction()}]
	, ["tab","tabWidthSetting",null]
	, ["tab","tabClosedSetting",null]
	, ["tab","lastTabSetting",null]
	, ["tab","travelLogSetting",null]
	, ["toolbar","toolbarSetting",null]
	, ["toolbar","addToolbarSetting",function(){initToolbar()}]
	, ["toolbar","hilitePosSetting",null]
	, ["toolbar","isearchPosSetting",null]
	, ["accel","accelSetting",function(){initAccel()}]
	, ["search","searchEngineSetting",function(){initSearch()}]
	, ["search","hiliteSetting",null]
	, ["search","maxSearchHistorySetting",null]
	, ["main,sidebar","EBPlusSetting",null]
	, ["script","activeScriptSetting",null]
	, ["cache","faviconCacheSetting",null]
	, ["cache","thumbnailCacheSetting",null]
]
,g_cmdFlags=[
	// [setting name, addCmdFlags]
	 ["X1Click",0]
	,["X2Click",0]
	,["X1DblClick",0]
	,["X2DblClick",0]
	,["tabItemLClick",0]
	,["tabItemRClick",0]
	,["tabItemMClick",0]
	,["tabItemLDblClick",0]
	,["tabItemRDblClick",0]
	,["tabItemMDblClick",0]
	,["tabBkgdLClick",0]
	,["tabBkgdRClick",0]
	,["tabBkgdMClick",0]
	,["tabBkgdLDblClick",0]
	,["tabBkgdRDblClick",0]
	,["tabBkgdMDblClick",0]
]
,g_view=""
,g_txtScript=g_app.getCmdText("script")
,g_txtSearch=g_app.getCmdText("search")
,C_SELECTED="cSelected"
,C_UNHOVER=["cUnhover","cUnhover2"]
,g_fso
,g_scriptList
,g_searchList
,g_scriptDetails
,g_initAssoc=false
,g_assoc
,g_cueBannerTxt={
	 idAppAccelInput:"ショートカットキーを入力"
	,idUrlActionBeforeInput:"URLのパターンを入力"
	,idUrlActionCompleteInput:"URLのパターンを入力"
	,idProxyNameInput:"設定の名前を入力"
	,idProxyServerInput:"プロキシサーバ名を入力"
	,idProxyBypassInput:"プロキシを使用しないアドレスを入力"
}
,SCRIPTACTION_COMMAND="command,"
,SCRIPTACTION_URLACTION="urlAction,"
;

/////////////////////////////////////////////////////////////////////////////////////
// common
function loadScriptDetails(){
	if(!g_scriptDetails){
		g_scriptDetails=[undefined,undefined];
		var	scriptDir=getScriptDirPath(),fso=getFSO();
		var	scriptsPath=fso.BuildPath(scriptDir,"scripts.json");
		if(fso.FileExists(scriptsPath)){
			g_scriptDetails[0]=parseJsonFile(scriptsPath);
		}
		scriptsPath=fso.BuildPath(scriptDir,"reserved\\scripts.json");
		if(fso.FileExists(scriptsPath)){
			g_scriptDetails[1]=parseJsonFile(scriptsPath);
		}
	}
	return g_scriptDetails;
}
function getScriptDetail(script){
	var	isReserved=script.indexOf("reserved\\")===0
		,details=loadScriptDetails()[isReserved?1:0]
		,detail;
	if(details){
		var	key=isReserved?script.substr(9):script;
		detail=details[key];
	}
	return detail;
}
function queryScriptAction(script,action){
	var	detail=getScriptDetail(script);
	if(!detail||!detail.action){
		// no scripts detail(etc. sample.js)
		return true;
	}
	return detail.action.indexOf(action)!==-1;
}
function _getScriptDisplayName(script){
	// remove cmd prefix(script:)
	if(script.indexOf(":")!==-1){
		script=script.substr(7);
	}
	var	detail=getScriptDetail(script);
	if(detail){
		if(detail&&detail.txt){
			script=detail.txt+" ("+script+")";
		}
	}
	return g_txtScript+":"+script;
}
function _getSearchDisplayName(search){
	// remove cmd prefix(search:)
	if(search.indexOf(":")!==-1){
		search=search.substr(7);
	}
	// remove extention
	var	iExt=search.lastIndexOf(".");
	if(-1===iExt){
		iExt=search.length;
	}
	return g_txtSearch+":"+search.substring(0,iExt);
}
function getCmdDisplayName(cmd){
	var	cmdText;
	if(-1===cmd.indexOf(":")){
		cmdText=g_app.getCmdText(cmd);
	}else{
		if(-1!==cmd.indexOf("script:")){
			cmdText=_getScriptDisplayName(cmd);
		}else if(-1!==cmd.indexOf("search:")){
			cmdText=_getSearchDisplayName(cmd);
		}
	}
	if(!cmdText)cmdText=cmd;
	return cmdText;
}
function getFSO(){
	if(!g_fso){
		g_fso=g_app.createObject("Scripting.FileSystemObject");
	}
	return g_fso;
}
function getScriptList(){
	if(!g_scriptList){
		g_scriptList=g_app.scriptList;
	}
	return g_scriptList;
}
function getSearchList(){
	if(!g_searchList){
		g_searchList=g_app.searchList;
	}
	return g_searchList;
}
function parseJsonFile(path){
	var	obj;
	try{
		var	txt=getFSO().OpenTextFile(path,1,false,-1).ReadAll();
		obj=eval("("+txt+")");
	}catch(e){}
	return obj;
}
function pathRemoveFileSpec(path){
	return path.substr(0,path.lastIndexOf('\\'));
}
function getSettingDirPath(){
	return getFSO().BuildPath(pathRemoveFileSpec(g_app.path),"setting");
}
function getScriptDirPath(){
	return getFSO().BuildPath(pathRemoveFileSpec(g_app.path),"script");
}
function addOption(options,val,txt){
	var	item=document.createElement("option");
	options.add(item);
	item.value=val;
	item.innerText=txt;
	return item;
}
function getSelectedValue(options){
	return options[options.selectedIndex].value;
}
function toggleEnable(chk,id){
	var elem=$$(id);
	if(elem){
		elem.disabled=!chk.checked;
	}
}
function valueIsCueBanner(elem){
	return -1!==elem.className.indexOf("cCueBanner");
}
function toggleCueBanner(ev,bannerTxt){
	if("focusin"===ev.type){
		if(valueIsCueBanner(ev.target)){
			ev.target.value="";
			$(ev.target).toggleClass("cCueBanner");
		}
	}else{
		if(0===ev.target.value.length){
			$(ev.target).toggleClass("cCueBanner");
			ev.target.value=bannerTxt;
		}
	}
}
function getCmdFlags(settingName){
	var	cnt=g_cmdFlags.length,flags=0x1;
	for(i=0;i<cnt;++i){
		if(settingName===g_cmdFlags[i][0]){
			flags=g_cmdFlags[i][1];
			break;
		}
	}
	return flags;
}
function getCheckedIdx(v,defVal){
	var	ret_idx=defVal,checkedCnt=v.length;
	for(checked_i=0;checked_i<checkedCnt;++checked_i){
		if(v[checked_i].checked){
			ret_idx=checked_i;
			break;
		}
	}
	return ret_idx;
}
function getAppStyleText(style){
	var	txt;
	switch(style){
	case 1:txt="シングルスレッド";break;
	case 2:txt="マルチスレッド";break;
	case 3:txt="マルチプロセス";break;
	}
	if(!txt)txt="unknown";
	return txt;
}
function getViewStyleText(style){
	var	txt;
	switch(style){
	case 0:txt="旧スタイル";break;
	case 1:txt="Internet Explorerスタイル";break;
	}
	if(!txt)txt="unknown";
	return txt;
}
/////////////////////////////////////////////////////////////////////////////////////
// input filter
function inputNum(k){
	// num
	if((48<=k&&k<=57)||(96<=k&&k<=105)) return true;
	// del, backspace, ins, <-, ->, home, end, tab
	if(8===k||46===k||45===k||37===k||39===k||35===k||36===k||9===k) {
		return true;
	}
	// return
	if(13===k) {
		apply();
		return false;
	}
	return false;
}
function inputAlpNum(k){
	// alp, num
	if(32<=k&&k<=125) return true;
	// del, backspace, ins, <-, ->, home, end, tab
	if(8===k||46===k||45===k||37===k||39===k||35===k||36===k||9===k) {
		return true;
	}
	// return
	if(13===k) {
		apply();
		return false;
	}
	return false;
}
// true:OK false:NG
function inputUrl(k){
	if(inputAlpNum(k)){
		return true;
	}

	// _ etc..
	if( 189===k||220===k||222===k||192===k||219===k||
		221===k||186===k||191===k||188===k||190===k||
		187===k||226===k){
		return true;
	}
	return false;
}
/////////////////////////////////////////////////////////////////////////////////////
// proxy
function getProxySettingNameFromPath(path){
	path=path.replace(/\\|\//g,"/");
	var	idx=path.lastIndexOf("/");
	var	name=path.substr(idx+7,path.length-idx-12);
	return name;
}
function getProxySettingPathFromName(name){
	var	fso=getFSO();
	return fso.BuildPath(getSettingDirPath(),"Proxy_"+name+".json");
}
function getProxyList(){
	if(!g_proxyList){
		// enum proxy setting file
		g_proxyList=[];
		var	fso=getFSO()
			,files=new Enumerator(fso.GetFolder(getSettingDirPath()).Files);
		for (;!files.atEnd();files.moveNext()){
			var f=files.item();
			if(f.Name.match(/^Proxy_.*.json$/i)){
				var	proxy=parseJsonFile(f.Path);
				if(proxy){
					g_proxyList.push({name:getProxySettingNameFromPath(f.Path),
						server:proxy.server,bypass:proxy.bypass});
				}
			}
		}
	}
	return g_proxyList;
}
function _refreshProxySelectList(list,isAdd,selVal){
	var	sel=document.proxyList.v;
	if(! list.length){
		return ;
	}
	var	options=sel.options;
	
	// check same item
	if(isAdd){
		for(i=0;i<options.length;++i){
			if(options[i].value==list[0].name){
				return ;
			}
		}
	}
	for(i=0;i<list.length;++i){
		var	proxy=list[i]
			,item=addOption(options,proxy.name,proxy.name);
		if(selVal==proxy.name){
			item.selected=true;
		}
	}
	
	// show UI select
	$($$("idNoProxyCaption")).hide();
	$(sel).show();
}
function _refreshProxy(contentId,list,isAdd){
	var	content=$$(contentId);
	var	cnt=list?list.length:0,parent=$(content);
	if(!isAdd){
		parent.empty();
	}else{
		// remove "empty" content
		if(3==content.firstChild.nodeType){
			parent.empty();
		}
	}
	if(cnt){
		var	c=document.createElement
			,nameInputBase=$(c("<input type=text name=v maxlength=100 class='cProxyNameInput cInline'>"))
			,serverInputBase=$(c("<input type=text name=v class='cProxyServerInput cInline'>"))
			,bypassInputBase=$(c("<input type=text name=v class='cProxyBypassInput cInline'>"))
			,bypassSpanBase=$(c("<span class='cProxyBypass'>"))
			,btnDelBase=$(c("<button>"));
		bypassSpanBase.text("例外: ");
		btnDelBase.append($("<span>削除</span>")).addClass("cProxyDel");
		for(i=0;i<cnt;++i){
			var	proxy=list[i]
				,div=$(c("<div>")).attr("id",contentId+i)
				,formInput=$(c("<form name="+contentId+"Input"+i+" class=cInline>"))
				,nameInput=nameInputBase.clone()
				,serverInput=serverInputBase.clone()
				,bypassInput=bypassInputBase.clone();
			div.data("proxy",proxy);
			
			var	btnDel=btnDelBase.clone();
			if(isAdd){
				div.addClass("cAdd cHide");
				nameInput.addClass("cMod");
				serverInput.addClass("cMod");
				bypassInput.addClass("cMod");
				proxy.isMod=true;
			}
			nameInput.val(proxy.name);
			serverInput.val(proxy.server);
			bypassInput.val(proxy.bypass);
			
			div .append(formInput.append(nameInput)
								 .append(serverInput)
								 .append(btnDel)
								 .append($("<br>"))
								 .append(bypassSpanBase.clone())
								 .append(bypassInput));
			if(isAdd&&parent.get(0).firstChild){
				$(parent.get(0).firstChild).before(div);
			}else{
				parent.append(div);
			}
			if(isAdd){
				div.slideDown("n");
				g_proxyList.push(proxy);
				break;
			}
		}
	}else{
		parent.text("なし");
	}
}
function initProxy(){
	if(!g_initProxy){
		g_initProxy=true;
		var	list=getProxyList();
		_refreshProxy("idProxy",list,false);
		var	settingProxy,indexProxy=0;
		if(g_setting.proxy){
			if(g_setting.proxy!=":direct:"){
				indexProxy=2;
				settingProxy=g_setting.proxy;
			}else{
				indexProxy=1;
			}
		}
		_refreshProxySelectList(list,false,settingProxy);
		document.proxy.v[indexProxy].checked=true;
	}
}
function addProxy(btn){
	var	parentNode=btn.parentNode
		,nameInput=document.forms.idProxyNameInput
		,serverInput=document.forms.idProxyServerInput
		,bypassInput=document.forms.idProxyBypassInput
		,proxy={name:nameInput.v.value
				,server:serverInput.v.value};
	var	bypassValue=!valueIsCueBanner(bypassInput.v);
	if(bypassValue){
		proxy.bypass=bypassInput.v.value;
	}
	if(proxy.name&&proxy.server){
		var	list=[proxy];
		_refreshProxy("idProxy",list,true);
		_refreshProxySelectList(list,true);
		nameInput.v.value="";
		serverInput.v.value="";
		var	ev={target:serverInput.v,type:"focusout"};
		toggleCueBanner(ev,g_cueBannerTxt[serverInput.name]);
		if(bypassValue){
			bypassInput.v.value="";
			ev.target=bypassInput.v;
			toggleCueBanner(ev,g_cueBannerTxt[bypassInput.name]);
		}
		nameInput.v.focus();
	}
	btn.disabled=true;
}
function saveProxy(){
	var	fso=getFSO();
	for(i=0;i<g_proxyList.length;++i){
		var	proxy=g_proxyList[i];
		if(proxy.isDel){
			fso.DeleteFile(getProxySettingPathFromName(proxy.name));
			continue;
		}
		if(proxy.isMod){
			// del old file
			if(proxy.oldName){
				fso.DeleteFile(getProxySettingPathFromName(proxy.oldName));
			}
			// save 
			var	saveProxy={server:proxy.server};
			if(proxy.bypass){
				saveProxy.bypass=proxy.bypass;
			}
			var	json=JSON.stringify(saveProxy,undefined," ")
				,path=getProxySettingPathFromName(proxy.name)
				,f=fso.OpenTextFile(path,2,true,-1);
			f.Write(json);
			f.Close();
		}
	}
}
function delProxy(btn,proxy,isDel){
	var	parentNode=btn.parentNode;
	$(":input:not(button.cProxyDel,button.cProxyDelCancel)",parentNode).attr("disabled",isDel);
	if(proxy.isDel){
		// to save
		proxy.isMod=true;
	}
	proxy.isDel=isDel;
	$(":first",btn).text(isDel?"取消":"削除");
	$(btn).toggleClass("cProxyDel cProxyDelCancel");
}
$("button.cProxyAdd:enabled").live("click", function(ev){
	addProxy(ev.target);
});
function checkProxyInputChanged(input,valName){
	var	proxy=$.data(input.parentNode.parentNode,"proxy");
	if(proxy){
		if(proxy[valName]!=input.value){
			if(valName==="name"){
				proxy.oldName=proxy.name;
			}
			proxy[valName]=input.value;
			proxy.isMod=true;
			$(input).addClass("cMod");
		}
	}
}
$("input.cProxyNameInput").live("focus blur",function(ev){
	var	focusin="focusin"===ev.type;
	g_ext.preventTransAccel(focusin);
	if(!focusin){
		checkProxyInputChanged(ev.target,"name");
	}
	return true;
});
$("input.cProxyServerInput").live("focus blur",function(ev){
	var	focusin="focusin"===ev.type;
	g_ext.preventTransAccel(focusin);
	if(!focusin){
		checkProxyInputChanged(ev.target,"server");
	}
	return true;
});
$("input.cProxyBypassInput").live("focus blur",function(ev){
	var	focusin="focusin"===ev.type;
	g_ext.preventTransAccel(focusin);
	if(!focusin){
		checkProxyInputChanged(ev.target,"bypass");
	}
	return true;
});
$("button.cProxyDel,button.cProxyDelCancel").live("click",function(ev){
	var	isDel="cProxyDel"===ev.target.className
		,proxy=$.data(ev.target.parentNode.parentNode,"proxy");
	delProxy(ev.target,proxy,isDel);
});
function UIUpdateProxyAdd(){
	$$("idProxyAdd").disabled=
		valueIsCueBanner(document.forms.idProxyNameInput.v)||
		valueIsCueBanner(document.forms.idProxyServerInput.v);
}
$("form[name=idProxyNameInput],form[name=idProxyServerInput]").live("keydown",function(ev){
	UIUpdateProxyAdd();
});
$("form[name=idProxyNameInput],form[name=idProxyServerInput]").live("focus blur",function(ev){
	toggleCueBanner(ev,g_cueBannerTxt[ev.target.form.name]);
	if("focusout"===ev.type){
		UIUpdateProxyAdd();
	}
});
$("form[name=idProxyBypassInput]").live("focus blur",function(ev){
	toggleCueBanner(ev,g_cueBannerTxt[ev.target.form.name]);
});
/////////////////////////////////////////////////////////////////////////////////////
// url action
function getUrlActionPath(){
	var	appDir=pathRemoveFileSpec(g_app.path),fso=getFSO();
	return fso.BuildPath(appDir,"setting\\customize\\url_action.json");
}
function getCurrentUrlAction(){
	return parseJsonFile(getUrlActionPath());
}
function getUrlActionCmd(action){
	if(action.script){
		return "script:"+action.script;
	}
	if(action.action){
		return action.action;
	}
	return "none";
}
function initUrlAction(){
	if(!g_initUrlAction){
		g_initUrlAction=true;
		g_urlAction=getCurrentUrlAction();
		if(g_urlAction){
			_refreshUrlAction("idUrlActionBefore", g_urlAction.before,false);
			_refreshUrlAction("idUrlActionComplete", g_urlAction.complete,false);
		}
	}
}
function _isEqualEventsLight(l,r){
	var	lOk=undefined!==l,rOk=undefined!==r;
	if(lOk!==rOk){
		return false;
	}
	if(lOk){
		if(l.length!==r.length){
			return false;
		}
	}
	return true;
}
function _isEqualEvents(l,r){
	if(l){
		var	len=l.length;
		for(i=0;i<len;++i){
			var	lEv=l[i],rEv=r[i];
			if( (lEv.url!==rEv.url)||
				(lEv.action&&rEv.script)||
				(lEv.script&&rEv.action)||
				(lEv.action!==rEv.action)||
				(lEv.script!==rEv.script)){
				return false;
			}
		}
	}
	return true;
}
function isEqualUrlAction(l,r){
	// check:    before complete
	// no check: emulation
	if( !_isEqualEventsLight(l.before,r.before)||
		!_isEqualEventsLight(l.complete,r.complete)||
		!_isEqualEvents(l.before,r.before)||
		!_isEqualEvents(l.complete,r.complete)){
		return false;
	}
	return true;
}
function _refreshUrlAction(contentId,actions,isAdd){
	var	content=$$(contentId);
	var	cnt=actions?actions.length:0,parent=$(content);
	if(!isAdd){
		parent.empty();
	}else{
		// remove "empty" content
		if(3==content.firstChild.nodeType){
			parent.empty();
		}
	}
	if(cnt){
		var	c=document.createElement
			,textInputBase=$(c("<input type=text name=v class='cUrlActionInput cInline'>"))
			,selectCmdBase=$(c("<select name=v class='cUrlActionCmd cInline'>"))
			,btnDelBase=$(c("<button>"))
			,btnUpBase=btnDelBase.clone()
			,btnDownBase=btnDelBase.clone();
		btnDelBase.append($("<span>削除</span>")).addClass("cUrlActionDel");
		btnUpBase.append($("<span></span>")).addClass("cUrlActionUp");
		btnDownBase.append($("<span></span>")).addClass("cUrlActionDown");
		for(i=0;i<cnt;++i){
			
			var	action=actions[i];
			var	data={contentId:contentId,action:action}
				,div=$(c("<div>")).text(": ").attr("id",contentId+i)
				,formInput=$(c("<form name="+contentId+"Input"+i+" class=cInline>"))
				,textInput=textInputBase.clone();
			div.data("action",data);
			
			var	formCmd=$(c("<form class='cDummy cInline'>"))
				,selectCmd=selectCmdBase.clone()
				,btnDel=btnDelBase.clone()
				,btnUp=btnUpBase.clone()
				,btnDown=btnDownBase.clone();
			selectCmd.change(function(ev){changeUrlActionCmd(ev.target)});
			if(isAdd){
				div.addClass("cAdd cHide");
				textInput.addClass("cMod");
				selectCmd.addClass("cMod");
			}
			textInput.val(action.url);
			
			var	optCmd=selectCmd.get(0).options
				,cmd=getUrlActionCmd(action);
			optCmd.length=1;
			optCmd[0].value=cmd;
			optCmd[0].text=getUrlActionDisplayName(cmd);
			div .append(formInput.append(textInput))
				.append(formCmd.append(selectCmd))
				.append(btnDel)
				.append(btnUp)
				.append(btnDown);
			
			if(isAdd&&parent.get(0).firstChild){
				$(parent.get(0).firstChild).before(div);
			}else{
				parent.append(div);
			}
			if(isAdd){
				div.slideDown("n");
				break;
			}
		}
	}else{
		parent.text("なし");
	}
}
function addUrlAction(btn){
	var	parentNode=btn.parentNode
		,contentId=btn.contentId
		,formInput=document.forms[contentId+"Input"]
		,url=formInput.v.value;
	if(url.length){
		var	formCmd=document.forms[contentId+"Cmd"]
			,selCmd=formCmd.v.value
			,action={"url":url}
			,iScript=selCmd.indexOf("script:")
		if(-1!==iScript){
			 action.script=selCmd.substr(7);
		}else{
			action.action=selCmd;
		}
		_refreshUrlAction(contentId,[action],true);
		formInput.v.value="";
		formInput.v.focus();
		selectOption(formCmd.v.options,"none");
	}
	btn.disabled=true;
}
function delUrlAction(btn,action,isDel){
	var	parentNode=btn.parentNode;
	$(":input:not(button.cUrlActionDel,button.cUrlActionDelCancel)",parentNode).attr("disabled",isDel);
	action.action.isDel=isDel;
	$(":first",btn).text(isDel?"取消":"削除");
	$(btn).toggleClass("cUrlActionDel cUrlActionDelCancel");
}
function _contentToUrlAction(content,actions){
	while(content){
		var	action=$(content).data("action").action;
		if(action&&!action.isDel&&action.url){
			var	add={"url":action.url};
			if(action.script){
				add.script=action.script;
			}else{
				add.action=action.action;
			}
			actions.push(add);
		}
		content=content.nextSibling;
	}
}
function _hasUrlAction(content){
	return content.firstChild&&1==content.firstChild.nodeType;
}
function saveUrlAction(){
	// before
	var	before=$$("idUrlActionBefore"),urlAction={};
	if(_hasUrlAction(before)){
		urlAction.before=[];
		_contentToUrlAction(before.firstChild,urlAction.before);
	}
	
	// complete
	var	complete=$$("idUrlActionComplete");
	if(_hasUrlAction(complete)){
		urlAction.complete=[];
		_contentToUrlAction(complete.firstChild,urlAction.complete);
	}

	// compare current setting
	var	current=getCurrentUrlAction();
	if(current&&isEqualUrlAction(current,urlAction)){
		return false;
	}

	// browser emulation
	if(g_urlAction&&g_urlAction.emulation){
		urlAction.emulation=g_urlAction.emulation;
	}

	var	json=JSON.stringify(urlAction,undefined," ")
		,f=getFSO().OpenTextFile(getUrlActionPath(),2,true,-1);
	f.Write(json);
	f.Close();
	return true;
}
function changeUrlActionCmd(elem){
	$(elem).addClass("cMod");
	var	action=$.data(elem.parentNode.parentNode,"action");
	if(action){
		var	value=elem.value;
		action=action.action;
		if(value.indexOf("script:")!==-1){
			action.action=undefined;
			action.script=value.substr(7);
		}else{
			action.script=undefined;
			action.action=value;
		}
	}
}
$("button.cUrlActionAdd:enabled").live("click", function(ev){
	addUrlAction(ev.target);
});
$("button.cUrlActionUp,button.cUrlActionDown").live("click",function(ev){
	var	parent=ev.target.parentNode
		,swp="cUrlActionDown"===ev.target.className?
		parent.nextSibling:parent.previousSibling;
	if(swp){
		swp.swapNode(parent);
	}
});
$("button.cUrlActionDel,button.cUrlActionDelCancel").live("click",function(ev){
	var	isDel="cUrlActionDel"===ev.target.className
		,action=$.data(ev.target.parentNode,"action");
	delUrlAction(ev.target,action,isDel);
});
$("input.cUrlActionInput").live("focus blur",function(ev){
	var	focusin="focusin"===ev.type;
	g_ext.preventTransAccel(focusin);
	if(!focusin){
		var action=$.data(ev.target.parentNode.parentNode,"action");
		if(action){
			action=action.action;
			if(action.url!=ev.target.value){
				action.url=ev.target.value;
				$(ev.target).addClass("cMod");
			}
		}
	}
	return true;
});
$("form.cDummy .cUrlActionCmd:enabled").live("mousedown focus",function(ev){
	var	select=ev.target,value=select.value
		,action=$.data(select.parentNode.parentNode,"action"),contentId;
	if(action){
		contentId=action.contentId;
	}else{
		contentId=select.parentNode.name;
	}
	var	event=(contentId.indexOf("Complete")===-1?"before":"complete");
	initUrlActionCmd(select.options,event);
	if(!selectOption(select.options,value)){
		addOption(select.options,value,getCmdDisplayName(value)).selected=true;
	}
	$(select.form).removeClass("cDummy");
	return false;
});
$("form[name=idUrlActionBeforeInput]").live("keydown",function(ev){
	$$("idAppUrlActionBeforeAdd").disabled=false;
});
$("form[name=idUrlActionCompleteInput]").live("keydown",function(ev){
	$$("idAppUrlActionCompleteAdd").disabled=false;
});
$("form[name=idUrlActionBeforeInput],form[name=idUrlActionCompleteInput]").live("focus blur",function(ev){
	toggleCueBanner(ev,g_cueBannerTxt[ev.target.form.name]);
});
/////////////////////////////////////////////////////////////////////////////////////
// toolbar
function doLockToolbar(){
	g_ext.lockToolbar();
}
function toolbarOption(id){
	if(g_ext.toolbarOption(id)){
		g_initToolbar=false;
		initToolbar();
	}
}
function addToolbar(clsid){
	if(g_ext.addToolbar(clsid)){
		g_initToolbar=false;
		initToolbar();
	}
}
function showToolbar(btn,id){
	var	isVisible=g_ext.showToolbar(id)
		,txtShow=" 隠す",imgShow="toolbarhide.png";
	if(! isVisible){
		txtShow=" 表示";
		imgShow="toolbar.png";
	}
	btn.firstChild.src=imgShow;
	btn.firstChild.nextSibling.nodeValue=txtShow;
}
function delToolbar(id,name){
	if(confirm("ツールバー「"+name+"」を削除しますか？    \n注：削除は取り消せません")){
		if(g_ext.delToolbar(id)){
			g_initToolbar=false;
			initToolbar();
		}
	}
}
function initToolbar(){
	if(! g_initToolbar){
		g_initToolbar=true;
		var	list=g_ext.toolbarList
			,cnt=list.count
			,html="";
		if(cnt>0){
			html="<table vspace=0px hspace=0px border=0 cellpadding=0 cellspacing=0>";
			for(i=0;i<cnt;++i){
				var	id=list.id(i),name=list.name(i)
					,style=list.style(i),disabled="",optionFunc=null;
				if(style&0x01000000){
					disabled=" disabled";
				}
				if(style&0x02000000){
					optionFunc='bookmarkToolbarOption('+id+');';
				}else{
					optionFunc='toolbarOption('+id+');';
				}
				var	txtShow=" 隠す", imgShow="toolbarhide.png";
				if(style&0x8){
					txtShow=" 表示";
					imgShow="toolbar.png";
				}
				tmp='<tr><td width=145px><span class=cToolbar>'+name+'</span></td>';
				tmp+='<td>';
				tmp+='<button style="width=5em;" onclick=showToolbar(this,'+id+');><img src='+imgShow+'>'+txtShow+'</button>';
				tmp+='<button style="width=8em;" onclick='+optionFunc+'><img src=property.png>&nbsp;詳細設定...</button>';
				tmp+='<button style="width=6em;"'+disabled+' onclick=delToolbar('+id+',\''+name+'\');><img src=-.png>&nbsp;削除...</button>';
				tmp+="</td></tr>";
				html+=tmp;
			}
			html+="</table>";
		}else{
			html='なし';
		}
		$$("toolbarView").innerHTML=html;
	}
}
/////////////////////////////////////////////////////////////////////////////////////
// bookmark
function invalidateBookmark(){
	var	initBm=g_initBookmark;
	g_initBookmark=false;
	if(initBm){
		initBookmark();
	}
	var	initTb=g_initToolbar;
	g_initToolbar=false;
	if(initTb){
		initToolbar();
	}
}
function bookmarkOption(guid){
	try{
		if(g_ext.bookmarkOption(guid)){
			invalidateBookmark();
		}
	}catch(e){
		errDlg(0);
	}
}
function bookmarkToolbarOption(idToolbar){
	try{
		guid=g_ext.bandIdToGuid(idToolbar);
		// todo no init bookmark
		initBookmark();
		if(g_ext.bookmarkOption(guid,'toolbar')){
			invalidateBookmark();
		}
	}catch(e){
		errDlg(0);
	}
}
function addBookmark(clsid){
	try{
		if(g_ext.addBookmark(clsid)){
			invalidateBookmark();
		}
	}catch(e){
		errDlg(0);
	}
}
function delBookmark(guid,name){
	if(confirm("ブックマーク「"+name+"」を削除しますか？\n削除するとツールバーも削除されます。\n\n注：削除は取り消せません")){
		try{
			if(g_ext.delBookmark(guid)){
				invalidateBookmark();
			}
		}catch(e){
			errDlg(0);
		}
	}
}
function _getBookmarkName(bm){
	return (bm.txt?bm.txt:"&lt;名前がありません&gt;");
}
function _getBookmarkNameFromOptions(guid){
	var	options=document.defaultBookmark.v.options
		,name="";
	for(i=0;i<options.length;++i){
		if(guid===options[i].value){
			name=options[i].text;
			break;
		}
	}
	return name;
}
function errDlg(err){
	var	msg="unknown error";
	if(0===err){
		msg="ブックマークの設定に失敗しました。";
	}
	alert(msg);
}
function changeDefaultBookmark(){
	var	options=document.defaultBookmark.v.options
		,selGuid=getSelectedValue(options)
		,change=confirm("ブックマーク「"+_getBookmarkNameFromOptions(selGuid)+"」を規定に設定しますか？");
	if(change){
		try{
			if(g_ext.setDefaultBookmark(selGuid)){
				// update bookmark content
				for(i=0;i<options.length;++i){
					var	guid=options[i].value
						,delBtn=$$(guid+"del"),def=(guid===selGuid);
					if(delBtn){
						delBtn.disabled=def;
					}
					var	defTxt=$$(guid+'def');
					if(defTxt){
						defTxt.style.display=(def?"inline":"none");
					}
				}
				g_defBookmarkGuid=selGuid;
			}
		}catch(e){
			errDlg(0);
		}
	}else{
		// prevent change
		selectOption(options,g_defBookmarkGuid);
	}
}
function _buildBookmarkContent(info){
	var	bookmark=info.bookmark
		,html=null;
	if(bookmark&&(bookmark.length>0)){

		// select default bookmark
		html="";
		html+="<form name=defaultBookmark><label style=\"padding-left:2px;\">\
			規定のブックマーク：&nbsp;<select name=v style=\"width:195px;\" onChange=\"changeDefaultBookmark()\">";
		for(i=0;i<bookmark.length;++i){
			var	bm=bookmark[i];
			html+="<option ";
			if(bm.isDefault){
				html+="defaultChecked ";
				g_defBookmarkGuid=bm.guid;
			}
			html+="value="+bm.guid+">"+_getBookmarkName(bm);
		}
		html+="</select></label></form>"
		
		// bookmark list
		html+="<table vspace=0px hspace=0px border=0 cellpadding=0 cellspacing=0>";
		for(i=0;i<bookmark.length;++i){
			var	bm=bookmark[i],txt=_getBookmarkName(bm)
				,disabled="",display="none";
			if(bm.isDefault){
				disabled="disabled";
				display="inline";
			}
			tmp='<tr><td style="width:195px;"><span class=cBookmark>'+txt+'\
				<span id="'+bm.guid+'def" style=\"display:'+display+';\"><b>&lt;規定&gt;</b></span></span></td>';
			tmp+='<td>';
			tmp+='<button style="width:8em;" onclick=bookmarkOption(\''+bm.guid+'\');><img src=property.png>&nbsp;詳細設定...</button>';
			tmp+='<button id="'+bm.guid+'del" style="width:5em;" '+disabled+' onclick=\"delBookmark(\''+bm.guid+'\',\''+txt+'\');\"><img src=-.png>&nbsp;削除</button>';
			tmp+="</td></tr>";
			html+=tmp;
		}
		html+="</table>";
	}
	return html;
}
function initBookmark(){
	if(! g_initBookmark){
		g_initBookmark=true;
		var	html=null;
		try{
			var	txt=g_ext.bookmarkInfo;
			html=_buildBookmarkContent(eval("("+txt+")"));
		}catch(e){}
		if(null===html){
			html='何らかのエラーが発生しました';
		}
		//$("#bookmarkView").empty().html(html);
		$$("bookmarkView").innerHTML=html;
		var	frm=document.defaultBookmark;
		if(frm){
			selectOption(frm.v.options,g_defBookmarkGuid);
		}
	}
}
function getUrlActionDisplayName(cmd){
	if(-1!==cmd.indexOf("script:")){
		return _getScriptDisplayName(cmd);
	}
	var	cmdCnt=g_urlActionCmds.length,i;
	for(i=0;i<cmdCnt;++i){
		var	acmd=g_urlActionCmds[i];
		if(acmd.cmd===cmd){
			return acmd.txt;
		}
	}
	return cmd;
}
function initUrlActionCmd(options,event){
	var	cmdCnt=g_urlActionCmds.length,i;
	options.length=0;
	for(i=0;i<cmdCnt;++i){
		var	cmd=g_urlActionCmds[i];
		if(cmd.event.indexOf(event)!==-1){
			addOption(options,cmd.cmd,cmd.txt);
		}
	}
	
	// script
	var	scriptList=getScriptList(),scriptCnt=scriptList.count;
	for(i=0;i<scriptCnt;++i){
		var	filename=scriptList.filename(i);
		if(queryScriptAction(filename,SCRIPTACTION_URLACTION)){
			addOption(options,"script:"+filename,_getScriptDisplayName(filename));
		}
	}
}
// fAddFlags
//    0x1:prevent add menu
function initSelectCmd(options, fAddFlags){
	var	cmdCnt=g_supportCmds.length;
	options.length=0;
	for(i=0;i<cmdCnt;++i){
		var	cmd=g_supportCmds[i];
		if(cmd==="menu"){
			if(fAddFlags&0x1){
				continue;
			}
		}
		addOption(options,cmd,g_app.getCmdText(cmd));
	}
	
	// script
	var	scriptList=getScriptList(),scriptCnt=scriptList.count;
	for(i=0;i<scriptCnt;++i){
		var	filename=scriptList.filename(i);
		if(queryScriptAction(filename,SCRIPTACTION_COMMAND)){
			addOption(options,"script:"+filename,_getScriptDisplayName(filename));
		}
	}
	
	// search
	var	searchList=getSearchList(),searchCnt=searchList.count;
	for(i=0;i<searchCnt;++i){
		addOption(options,"search:"+searchList.filename(i),
			_getSearchDisplayName(searchList.filename(i)));
	}
}
function initOptionCmd(options,cmd){
	options.length=1;
	options[0].value=cmd;
	options[0].text=getCmdDisplayName(cmd);
}
function selectOption(options,value){
	var	cnt=options.length;
	for(i=0;i<cnt;++i){
		if(options[i].value==value){
			options[i].selected=true;
			return true;
		}
	}
	// 初期アイテムを選択
	options.selectedIndex=0;
	return false;
}
function selectOptionCmd(options,cmd){
	var	cnt=options.length;
	for(i=0;i<cnt;++i){
		if(options[i].value===cmd){
			options[i].selected=true;
			return true;
		}
	}
	initOptionCmd(options,cmd);
	return false;
}
/////////////////////////////////////////////////////////////////////////////////////
// accel
function findAccel(list,spKey,accelKey){
	var	findIdx=-1
		,cnt=list.count-1;	// for add
	for(i=0;i<cnt;++i){
		if( (list.accel(i,0)===spKey) &&
			(list.accel(i,1)===accelKey)){
			findIdx=i;
			break;
		}
	}
	return findIdx;
}
function getSpKey(ev){
	var	spKey=0x0;
	if(ev.shiftKey)	spKey|=0x04;
	if(ev.ctrlKey)	spKey|=0x08;
	if(ev.altKey)	spKey|=0x10;
	return spKey;
}
function getSpKeyString(spKey){
	spKey&=~0x01;
	var	txt="";
	switch(spKey){
	case 0x04:	txt="Shift + ";					break;
	case 0x08:	txt="Ctrl + ";					break;
	case 0x0C:	txt="Ctrl + Shift + ";			break;
	case 0x10:	txt="Alt + ";					break;
	case 0x14:	txt="Shift + Alt + ";			break;
	case 0x18:	txt="Ctrl + Alt + ";			break;
	case 0x1C:	txt="Ctrl + Shift + Alt + ";	break;
	}
	return txt;
}
var	g_vkeys=[
	// event keycode, virtual:0x1, keycode, display string
	  [0x08, 0x1, 0x08, "BackSpace"]
	, [0x09, 0x1, 0x09, "Tab"]
	, [0x1B, 0x1, 0x1B, "Escape"]
	, [0x21, 0x1, 0x21, "Page Up"]
	, [0x22, 0x1, 0x22, "Page Down"]
	, [0x23, 0x1, 0x23, "End"]
	, [0x24, 0x1, 0x24, "Home"]
	, [0x25, 0x1, 0x25, "Left"]
	, [0x26, 0x1, 0x26, "Up"]
	, [0x27, 0x1, 0x27, "Right"]
	, [0x28, 0x1, 0x28, "Down"]
	, [0x29, 0x1, 0x29, "Select"]
	, [0x2A, 0x1, 0x2A, "Print"]
	, [0x2B, 0x1, 0x2B, "Execute"]
	, [0x2C, 0x1, 0x2C, "SnapShot"]
	, [0x2D, 0x1, 0x2D, "Insert"]
	, [0x2E, 0x1, 0x2E, "Delete"]
	, [0x2F, 0x1, 0x2F, "Help"]
	// Ctrl＋で動かないことがあるため取り消し
	//, [0xBA, 0x0, 0x3A, ":"]
	//, [0xBB, 0x0, 0x3B, ";"]
	//, [0xBC, 0x0, 0x2C, ","]
	//, [0xBD, 0x0, 0x2D, "-"]
	//, [0xBE, 0x0, 0x2E, "."]
	//, [0xBF, 0x0, 0x2F, "/"]
	//, [0xC0, 0x0, 0x40, "@"]
	//, [0xDB, 0x0, 0x5B, "["]
	//, [0xDC, 0x0, 0x5C, "\\"]
	//, [0xDD, 0x0, 0x7D, "]"]
	//, [0xDE, 0x0, 0x5E, "^"]
	//, [0xE2, 0x0, 0x5C, "\\"]
	//, [0x6F, 0x0, 0x2F, "/"]
	//, [0x6E, 0x0, 0x2E, "."]
	//, [0x6D, 0x0, 0x2D, "-"]
	//, [0x6B, 0x0, 0x2B, "+"]
	//, [0x6A, 0x0, 0x2A, "*"]
];
function findVKey(keyCode){
	var	vkeyLen=g_vkeys.length;
	for(vkey_i=0;vkey_i<vkeyLen;++vkey_i){
		if(g_vkeys[vkey_i][0]===keyCode){
			return vkey_i;
		}
	}
	return -1;
}
function compareAccelList(left,right){
	var	leftCnt=left.count,rightCnt=right.count
		,isEqual=(leftCnt===rightCnt);
	if(isEqual){
		for(i=0;i<leftCnt;++i){
			if((left.accel(i,0)!==right.accel(i,0))||
			   (left.accel(i,1)!==right.accel(i,1))||
			   (left.accel(i,2)!==right.accel(i,2))){
				isEqual=false;
				break;
			}
		}
	}
	return isEqual;
}
function accelKeyToEventKeyCode(accelKey,isVirt){
	var	vkeyLen=g_vkeys.length;
	for(vkey_i=0;vkey_i<vkeyLen;++vkey_i){
		if(g_vkeys[vkey_i][2]===accelKey&&g_vkeys[vkey_i][1]===isVirt){
			return g_vkeys[vkey_i][0];
		}
	}
	return accelKey;
}
function eventToAccelInfo(ev){
	var	keyCode=ev.keyCode,spKey=getSpKey(ev),spTxt="",keyTxt="";

	// ctrl,shift,alt
	if(0x10==keyCode||0x11==keyCode||0x12==keyCode){
		keyInfo=$(ev.target).data("keyInfo");
		if(undefined!==keyInfo){
			keyTxt=keyInfo.keyTxt;
			keyCode=keyInfo.keyCode;
		}
		spKey+=0x1;
	}else
	// alnum
	if((0x30<=keyCode)&&(keyCode<=0x39)||
	   (0x41<=keyCode)&&(keyCode<=0x5A)){
		// must Ctrl
		if(0===spKey){
			spKey=0x8;
		}
		spKey+=0x1;
		keyTxt=String.fromCharCode(keyCode);
	}else
	// F1 ... F24
	if((0x70<=keyCode)&&(keyCode<=0x87)){
		keyTxt="F"+(keyCode-0x6F).toString();
		spKey+=0x1;
	}else
	// numpad
	if((0x60<=keyCode)&&(keyCode<=0x69)){
		// must ctrl
		if(0===spKey){
			spKey=0x8;
		}
		spKey+=0x1;
		keyTxt=(keyCode-0x60).toString();
	}else{
		// virtual key
		var	vkey_i=findVKey(keyCode);
		if(-1!==vkey_i){
			spKey+=g_vkeys[vkey_i][1];
			keyCode=g_vkeys[vkey_i][2];
			keyTxt=g_vkeys[vkey_i][3];
		}else{
			// debug
			if(false){
				keyTxt+=keyCode.toString();
				keyTxt+="(0x";
				keyTxt+=keyCode.toString(16);
				keyTxt+=")";
				keyTxt+=" "+String.fromCharCode(keyCode);
			}
		}
	}

	var	accel=null;
	if(keyTxt&&keyTxt.length){
		// save accel key for press only ctrl,shift,alt
		$(ev.target).data("keyInfo",{keyTxt:keyTxt,keyCode:keyCode});
		accel={virt:spKey,key:keyCode,text:getSpKeyString(spKey)+keyTxt};
	}
	return accel;
}
function inputAccel(ev){
	var	keyCode=ev.keyCode,accelKey=keyCode,spKey=getSpKey(ev);

	// tab, numlock
	if((0x00===spKey&&0x9===keyCode)||(0x90===keyCode)){
		return true;
	}

	// return
	if(0x0D===keyCode){
		apply();
		return false;
	}

	var	info=eventToAccelInfo(ev);
	if(!info){
		return false;
	}
	
	var	input=$(ev.target)
		,accel=input.data("accel")
		,list=accel.list
		,isAdd=(accel.index==null)
		,index=(isAdd?list.count-1:accel.index)
		,sameIndex=findAccel(list,info.virt,info.key)
		,isFind=(-1!==sameIndex&&index!=sameIndex);

	input.val(info.text);
	list.accel(index,0)=info.virt;
	list.accel(index,1)=info.key;
	input.toggleClass("cAccelNg",isFind);
	input.addClass("cMod",!isFind);
	if(isAdd){
		var	contentId=input.attr("contentId")
			,addBtn=$("#"+contentId+"Add")
			,ng=$("#"+contentId+"Ng");
		addBtn.attr("disabled",isFind);
		if(isFind){
			ng.show();
		}else{
			ng.hide();
		}
	}
	return false;
}
function dispSelectCmd(select){
	var	value=select.value
		,addFlags=getCmdFlags(select.form.name);
	initSelectCmd(select.options,addFlags);
	selectOptionCmd(select.options,value);
}
function changeAccelCmd(elem){
	var	accel=$.data(elem,"accel")
		,list=accel.list
		,idx=(accel.index!=null?accel.index:list.count-1);
	list.accel(idx,2)=elem.value;
}
function addAccel(btn){
	var	contentId=$(btn).attr("contentId")
		,formCmd=document.forms[contentId+"Cmd"]
		,content=$("#"+contentId)
		,accel=content.data("accel");
	refreshAccel(contentId,accel.list,true);
	btn.disabled=true;
	var	formInput=document.forms[contentId+"Input"];
	formInput.v.value="";
	formInput.v.focus();
	selectOption(formCmd.v.options,"none");
}
function delAccel(btn,accel,isDel){
	var	div=$("#"+accel.contentId+accel.index);
	$(":input:not(button)",div).attr("disabled",isDel);
	accel.list.markDel(accel.index)=isDel;
	$(":first",btn).text(isDel?"取消":"削除");
	$(btn).toggleClass("cAccelDel cAccelDelCancel");
}
$("button.cAccelAdd:enabled").live("click", function(ev){
	addAccel(ev.target);
});
$("button.cAccelDel,button.cAccelDelCancel").live("click",function(ev){
	var	isDel=(-1===ev.target.className.indexOf("cAccelDelCancel"))
		,accel=$.data(ev.target,"accel");
	delAccel(ev.target,accel,isDel);
});
$("input.cAccelInput").live("keydown",function(ev){
	return inputAccel(ev);
});
$("input.cAccelInput").live("focus blur",function(ev){
	var	isPrevent=("focusin"===ev.type);
	g_ext.preventTransAccel(isPrevent);
	return true;
});
$("form.cDummy .cSelectCmd:enabled").live("mousedown focus",function(ev){
	dispSelectCmd(ev.target);
	$(ev.target.form).removeClass("cDummy");
	return false;
});
$("form[name=idAppAccelInput]").live("focus blur",function(ev){
	toggleCueBanner(ev,g_cueBannerTxt[ev.target.form.name]);
});
/*  change が動かない
$("select.cAccelCmdHidden").live("change",function(ev){
	changeAccelCmd(ev.target);
	return false;
});
*/
function refreshAccel(contentId,list,isAdd){
	var	content=$$(contentId);
	var	cnt=list.count,parent=$(content)
		,headData={contentId:contentId,list:list};
	parent.data("accel",headData);
	if(! isAdd){
		parent.empty();
		var	head=$("[name="+contentId+"Input] [name=v],[name="+contentId+"Cmd] [name=v]");
		head.data("accel",headData);
	}else{
		// remove "empty" content
		if(3==content.firstChild.nodeType){
			parent.empty();
		}
	}
	if(cnt){
		var	ev=document.createEventObject()
			,textInputBase=$("<input type=text name=v class=cAccelInput>")
			,selectCmdBase=$("<select name=v class=cSelectCmd>")
			,btnDelBase=$("<button>")
			,c=document.createElement;
		//btnDelBase.css("width","8em");
		btnDelBase.append($("<span>削除</span>")).addClass("cAccelDel");
		for(i=cnt-1;i>=0;--i){
			var	virt=list.accel(i,0)
				,key=list.accel(i,1)
				,cmd=list.accel(i,2)
				,accel={contentId:contentId,list:list,index:i}
				,div=$("<div>").text(": ").attr("id",contentId+i)
				,formInput=$(c("<form name="+contentId+"Input"+i+">"))
				,textInput=textInputBase.clone();
			textInput.data("accel",accel);
			if(isAdd){
				div.addClass("cAdd cHide");
				textInput.addClass("cMod");
			}
			var	formCmd=$(c("<form name="+contentId+"Cmd"+i+" class=cDummy>"));
			var selectCmd=selectCmdBase.clone();
			selectCmd.data("accel",accel);
			selectCmd.change(function(ev){changeAccelCmd(ev.target)});
			var	btnDel=btnDelBase.clone().data("accel",accel);
			
			ev.shiftKey=(virt&0x4?true:false);
			ev.ctrlKey=(virt&0x8?true:false);
			ev.altKey=(virt&0x10?true:false);
			ev.keyCode=accelKeyToEventKeyCode(key,(virt&0x1));
			ev.target=textInput.get(0);
			var	info=eventToAccelInfo(ev);
			if(info){
				textInput.val(info.text);
			}
			
			var	optCmd=selectCmd.get(0).options;
			optCmd.length=1;
			optCmd[0].value=cmd;
			optCmd[0].text=getCmdDisplayName(cmd);
			
			div .append(formInput.append(textInput))
				.append(formCmd.append(selectCmd))
				.append(btnDel);
			
			if(isAdd&&parent.get(0).firstChild){
				$(parent.get(0).firstChild).before(div);
			}else{
				parent.append(div);
			}
			if(isAdd){
				div.slideDown("n");
				break;
			}
		}
	}else{
		parent.text("なし");
	}
	// for accel add
	list.add(0,0,"none");
}
function setDefaultAccel(){
	if(g_initAccel){
		refreshAccel("idAppAccel",g_setting.defaultAccelList,false);
	}
}
function initAccel(){
	if(! g_initAccel){
		g_initAccel=true;
		refreshAccel("idAppAccel",g_setting.accelList,false);
	}
}
/////////////////////////////////////////////////////////////////////////////////////
// search
$("button.cSearchDel").live("click",function(ev){
	var	id=$.data(ev.target,"id");
	g_ext.delSearchEngine(id, true);
	$(":first",ev.target).text("取消");
	ev.target.nextSibling.style.textDecoration="line-through";
	$(ev.target).toggleClass("cSearchDel cSearchDelCancel");
});
$("button.cSearchDelCancel").live("click",function(ev){
	var	id=$.data(ev.target,"id");
	g_ext.delSearchEngine(id, false);
	$(":first",ev.target).text("削除");
	ev.target.nextSibling.style.textDecoration="none";
	$(ev.target).toggleClass("cSearchDel cSearchDelCancel");
});
$("a.cSearchAdd").live("click",function(){
	goAddSearchPage();
});
function initSearch(){
	if(!g_initSearch){
		g_initSearch=true;
		var	cnt = g_ext.searchEngineCount
			,content=null;
		if(cnt>0){
			var	div=$("<div>")
				,btn=$("<button>")
				,delTxt=$("<span>削除</span>")
				,name=$("<span>");
			btn.addClass("cSearchDel");
			name.addClass("cSearch");
			content=$("<div>");
			for(i=0;i<cnt;++i){
				var	searchId=g_ext.searchEngineId(i)
					,delBtn=btn.clone().append(delTxt.clone());
				delBtn.data("id",searchId);
				content.append(
					div.clone().append(delBtn)
							   .append(name.clone().text(g_ext.searchEngine(i)))
				);
			}
		}
		if(!content){
			content=$("<div>なし</div>");
		}
		$("#searchView").empty().append(content);
	}
}
/////////////////////////////////////////////////////////////////////////////////////
// script
function initScriptSetting(){
	if(!g_initScriptSetting){
		g_initScriptSetting=true;
		var	list=g_ext.scriptSettingList,content=null,cnt=list.length;
		if(cnt>0){
			content=document.createElement("div");
			var	c=document.createElement;
			for(i=0;i<cnt;++i){
				var	script=list[i],li=c("li"),span=c("span")
					,btn=c("button"),img=c("img");
			    span.innerText=g_ext.scriptDisplayName(script)+"("+script+")";
				span.title=script;
				img.src="property.png"
				btn.appendChild(img);
				btn.appendChild(document.createTextNode("設定..."));
				btn.script={script:script};
				btn.onclick=function(){g_ext.scriptSetting(this.script.script);}
				li.appendChild(span);
                li.appendChild(btn);
				content.appendChild(li);
			}
		}
		if(!content){
			content=$("<div>なし</div>");
		}
		$("#idScriptSetting").empty().append(content);
	}
}
/////////////////////////////////////////////////////////////////////////////////////
// user agent
function initUserAgent(){
	if(! g_initUserAgent) {
		g_initUserAgent=true;
		document.userAgentList.v.options.length=g_userAgents.length;
		var	userAgent=g_setting.userAgent;
		for(i = 0; i < g_userAgents.length; ++i) {
			document.userAgentList.v.options[i].value=i;
			document.userAgentList.v.options[i].text=g_userAgents[i];
			if(userAgent===g_userAgents[i]) {
				document.userAgentList.v.selectedIndex=i;
			}
		}
		if(userAgent) {
			document.userAgent.v.value=userAgent;
		} else {
			document.userAgent.v.value=g_userAgents[0];
			document.userAgentList.v.options[0].selected=true;
		}
	}
}
$("button.cSetDefault[category]").live("click",function(ev){
	selectCmds($(ev.target).attr("category"),true);
});
function userAgentChange(){
	var idx=document.userAgentList.v.selectedIndex;
	document.userAgent.v.value=document.userAgentList.v.options[idx].text;
}
/////////////////////////////////////////////////////////////////////////////////////
// home page
function setHomeUrl(target){
	var	urls=g_app.homeList;
	if(urls.count){
		target.value=urls.url(0);
	}
}
/////////////////////////////////////////////////////////////////////////////////////
// mouse
function initMouseAction(){
	if(! g_initMouseAction){
		g_initMouseAction=true;
		for(category in g_cmdInfo){
			selectCmds(category,false);
		}
	}
}
function sepCmd(cmd){
	var	ret=new Array(2),iFind=cmd.lastIndexOf(":");
	if(-1!==iFind){
		ret[0]=cmd.substring(0,iFind);
		ret[1]=cmd=value.substring(iFind+1);
	}else{
		ret[0]=cmd;
		ret[1]=null;
	}
	return ret;
}
function selectCmds(category,isSetDefault){
	var	cmdInfo=g_cmdInfo[category];
	for (name in cmdInfo){
		var	cmd=(isSetDefault?cmdInfo[name]:g_setting[name]);
		selectOptionCmd(document[name].v.options,cmd);
	}
}
/////////////////////////////////////////////////////////////////////////////////////
// tab font
function setTabFontDefault(){
	$$("currentTabFont").innerText="規定のフォント";
	g_defaultTabFont=true;
	g_ext.defaultTabFont();
}
function chooseTabFont(){
	var	currentTabFont=null;
	if(!g_defaultTabFont){
		currentTabFont=$$("currentTabFont").innerText;
	}
	var	tabFont=g_ext.chooseFont(currentTabFont);
	if(tabFont){
		g_defaultTabFont=false;
		$$("currentTabFont").innerText=tabFont;
	}
}
/////////////////////////////////////////////////////////////////////////////////////
// regist app
function isAssoced(ext){
	var	exe=g_ext.AssocQuery(ext,null),ret=false;
	if(exe&&typeof exe==="string"){
		var	appPath=g_app.path;
		appPath=appPath.toUpperCase();
		exe=exe.toUpperCase();
		ret=appPath===exe;
	}
	return ret;
}
function selectBrowserUI(){
	// Vista,7 only
	var	shl=g_app.createObject("WScript.Shell"),fso=getFSO()
		,ctl=fso.BuildPath(fso.GetSpecialFolder(1),"control.exe");
	shl.Run('"'+ctl+'" /name Microsoft.DefaultPrograms /page pageDefaultProgram',1, false);
}
function initAssocSetting(){
	if(!g_initAssoc){
		g_initAssoc=true;
		var	isAssoc=isAssoced("http");
		if(undefined===g_assoc||isAssoc!==g_assoc){
			g_assoc=isAssoc;
			var	assocs=$("#idIsNoAssoc,#idIsAssoc,#btnUnregApp,#btnRegApp,#idDisableUnregApp")
				,ctx=assocs.context;
			$("#idIsNoAssoc,#idIsAssoc",ctx).hide();
			$("#btnRegApp",ctx).attr("disabled",false);
			if(g_setting.sysVer>=6000){
				// Vista,7
				var	elem=$("#idDisableUnregApp",ctx);
				if(!isAssoc)elem.hide();
				else elem.slideDown("slow");
				$("#btnUnregApp",ctx).attr("disabled",isAssoc);
			}else{
				// Xp
				$("#btnUnregApp",ctx).attr("disabled",!isAssoc);
			}
			if(isAssoc){
				$("#idIsAssoc",ctx).slideDown("slow");
			}else{
				$("#idIsNoAssoc",ctx).slideDown("slow");
			}
		}
	}
	return g_assoc;
}
var	STR_BROWSERCHANGED="Software\\Clients\\StartMenuInternet";
// called from html dialog
function settingChange(strChanged){
	if(g_initAssoc&&(STR_BROWSERCHANGED.toUpperCase()===strChanged.toUpperCase())){
		var	assoc=$("#assocSetting:visible");
		if(assoc.length){
			g_initAssoc=false;
			var assoc=g_assoc;
			if(assoc==initAssocSetting()){
				// fix Xp
				if(g_setting.ieVer<9000){
					setTimeout(function(){
						g_initAssoc=false;
						initAssocSetting();
					},3000);
				}
			}
		}
	}
}
function regApp(regist){
	
	var	msg=regist?"レジストリに登録しますか?":"レジストリから削除しますか?";
	if(confirm(msg)){
		var	appPath=g_app.path
			,ar=[];
		ar.push("'regist':"+regist);
		ar.push("'sysVer':"+g_setting.sysVer);
		ar.push("'ieVer':"+g_setting.ieVer);
		ar.push("'appPath':'"+appPath.replace(/\\/g, "\\\\")+"'");
		if(regist){
			ar.push("'appName':'Ancia Chrome'");
			ar.push("'appDetail':'Ancia Chromeは、AnciaのWebKitエンジンバージョンです。'");
		}
		var	shl=g_app.createObject("WScript.Shell")
			,fso=getFSO()
			,appDir=pathRemoveFileSpec(appPath)
			,regApp=fso.BuildPath(appDir,"Regist.exe")
			,regScript=fso.BuildPath(appDir,"script\\reserved\\regApp.js")
			,cscriptPath=fso.BuildPath(fso.GetSpecialFolder(1),"cscript.exe");
		try{
			shl.Run('"'+regApp+'" "'+cscriptPath+'" "'+regScript+'" "{'+ar.join(",")+'}"', 0, true);
			if(g_setting.sysVer<6000){
				g_ext.assocChanged();
				g_ext.broadcastSettingChanged(STR_BROWSERCHANGED);
			}
		}catch(e){}
	}
}
/////////////////////////////////////////////////////////////////////////////////////
// init, apply, view
function goAddSearchPage(){
	g_app.ExecScript("reserved\\goAddSearchPage.js");
	g_ext.optionClose();
}
function doFind(ev){
	if(13===ev.keyCode){
		view("find");
	}
}
function view(category){
	var	isFind=("find"===category);
	if(!isFind&&g_view===category){
		return;
	}
	g_ext.hilite("");
	var	elemNotFound=$("#notFound")
		,elemNeedKw=$("#needKw");
	$$("view").scrollTop=0;
	elemNotFound.hide();
	elemNeedKw.hide();	
	var	g_elemCnt=g_cats.length;

	$.each(g_cats,function(){
		this.toggleClass(C_SELECTED,this.get(0).id===category);
		});

	var	g_settingsCnt=g_settings.length
		,kw=document.findKeyword.v.value;
	if(isFind&&kw.length){
		kw=kw.toUpperCase();
		var notFound=true;
		for(j=0;j<g_settingsCnt;++j){
			var	setting=$("#"+g_settings[j][1]);
			if(setting){
				var	show=false;
				// call init
				if(null!==g_settings[j][2]){
					g_settings[j][2]();
				}
				var	txt=setting.text().toUpperCase();
				if(txt.indexOf(kw)!=-1){
					show=true;
					notFound=false;
				}
				show ? setting.show() : setting.hide();
			}
		}
		if(notFound){
			elemNotFound.slideDown(300);
		} else {
			g_ext.hilite(kw);
		}
	}else{
		for(j=0;j<g_settingsCnt;++j){
			var	setting=$("#"+g_settings[j][1]);
			if(setting){
				if(isFind||(-1!=g_settings[j][0].indexOf(category))){
					// call init
					if(null!==g_settings[j][2]){
						g_settings[j][2]();
					}
					setting.show();
				}else{
					setting.hide();
				}
			}
		}
		if(isFind){
			elemNeedKw.slideDown(300);
		}
	}
	g_view=category;
}
function init(){
	// category
	g_cats=[
		  $($$("main"))
		, $($$("reg"))
		, $($$("style"))
		, $($$("bookmark"))
		, $($$("webkit"))
		, $($$("tab"))
		, $($$("urlaction"))
		, $($$("toolbar"))
		, $($$("mouse"))
		, $($$("accel"))
		, $($$("search"))
		, $($$("script"))
		, $($$("cache"))
		, $($$("sidebar"))
		, $($$("find"))
	];
	$.each(g_cats,function(){this.mouseout(
		function(ev){
			var	target=$(ev.target);
			if((ev.target.className.indexOf(C_SELECTED)===-1)&&ev.target.tagName==="A"){
				target.addClass(C_UNHOVER[0]);
				setTimeout(function(){
					if(!target.hasClass(C_SELECTED)){
						target.addClass(C_UNHOVER[1]);
					}
					target.removeClass(C_UNHOVER[0]);
					setTimeout(function(){
						target.removeClass(C_UNHOVER[1]);
					},50);
				},30);
			}
		})
	});

	//////////////////////////////////////////////////////
	// reg
	if(g_setting.sysVer<6000){
		$$("idSelectBrowserUI").style.display="none";
		$$("idAssocNew").style.display="none";
		$$("idAssocOld").style.display="block";
		$$("idNewSystem").style.display="none";
	}

	//////////////////////////////////////////////////////

	// start
	document.start.v[g_setting.start].checked=true;
	// app style
	document.appStyle[g_setting.style].checked=true;
	$$("idCurrentStyle").innerText=getAppStyleText(g_setting.currentStyle);
	// view style
	document.viewStyle[g_setting.viewStyle].checked=true;
	$$("currentViewStyle").innerText=getViewStyleText(g_setting.currentViewStyle);
	// single instance
	document.singleInstance.v.checked=g_setting.singleInstance;
	// single instance start enable
	document.singleInstanceStartEnable.v.checked=g_setting.singleInstanceStartEnable;
	// max closed
	document.maxClosed.v.value=g_setting.maxClosed;
	// max travellog
	document.maxTravelLog.v.value=g_setting.maxTravelLog;
	// max lasttab
	document.maxLastTab.v.value=g_setting.maxLastTab;
	// tab width
	document.tabWidth.v.value=g_setting.tabWidth;
	// tab font
	if(g_setting.tabFont){
		$$("currentTabFont").innerText=g_setting.tabFont;
		g_defaultTabFont=false;
	}
	// auto text link
	document.autoTextLink.v.checked=g_setting.autoTextLink;
	// auto text link dialog
	document.autoTextLinkDialog.v.checked=g_setting.autoTextLinkDialog;
	// auto image resize
	document.autoImageResize.v.checked=g_setting.autoImageResize;
	// security
	var	security = g_setting.security;
	document.securityImage.v.checked=(security&0x10);
	document.securityVideo.v.checked=(security&0x20);
	document.securitySound.v.checked=(security&0x40);
	document.securityScript.v.checked=(0===(security&0x80));
	document.securityJava.v.checked=(0===(security&0x100));
	document.securityRunActiveX.v.checked=(0===(security&0x200));
	document.securityDownloadActiveX.v.checked=(0===(security&0x400));
	document.metaRefresh.v.checked=g_setting.metaRefresh;
	// inherit security
	document.inheritSecurity.v.checked=g_setting.inheritSecurity;
	// feature
	selectOption(document.featureBrowserEmulation.v.options,g_setting.featureBrowserEmulation);
	document.featureGpuRendering.v.checked=g_setting.featureGpuRendering;
	document.featureObjectCaching.v.checked=g_setting.featureObjectCaching;
	document.featureZoneElevation.v.checked=g_setting.featureZoneElevation;
	document.featureMimeHandling.v.checked=g_setting.featureMimeHandling;
	document.featureMimeSniffing.v.checked=g_setting.featureMimeSniffing;
	document.featureWindowRestrictions.v.checked=g_setting.featureWindowRestrictions;
	document.featureWebocPopupmanagement.v.checked=g_setting.featureWebocPopupmanagement;
	document.featureBehaviors.v.checked=g_setting.featureBehaviors;
	document.featureDisableMkProtocol.v.checked=g_setting.featureDisableMkProtocol;
	document.featureLocalmachineLockdown.v.checked=g_setting.featureLocalmachineLockdown;
	document.featureSecurityband.v.checked=g_setting.featureSecurityband;
	document.featureRestrictActivexinstall.v.checked=g_setting.featureRestrictActivexinstall;
	document.featureValidateNavigateUrl.v.checked=g_setting.featureValidateNavigateUrl;
	document.featureRestrictFiledownload.v.checked=g_setting.featureRestrictFiledownload;
	document.featureProtocolLockdown.v.checked=g_setting.featureProtocolLockdown;
	document.featureHttpUsernamePasswordDisable.v.checked=g_setting.featureHttpUsernamePasswordDisable;
	document.featureSafeBindtoobject.v.checked=g_setting.featureSafeBindtoobject;
	document.featureUncSavedfilecheck.v.checked=g_setting.featureUncSavedfilecheck;
	document.featureGetUrlDomFilepathUnencoded.v.checked=g_setting.featureGetUrlDomFilepathUnencoded;
	document.featureTabbedBrowsing.v.checked=g_setting.featureTabbedBrowsing;
	document.featureSslux.v.checked=g_setting.featureSslux;
	document.featureDisableNavigationSounds.v.checked=g_setting.featureDisableNavigationSounds;
	document.featureDisableLegacyCompression.v.checked=g_setting.featureDisableLegacyCompression;
	document.featureXmlHttp.v.checked=g_setting.featureXmlHttp;
	document.featureDisableTelnetProtocol.v.checked=g_setting.featureDisableTelnetProtocol;
	document.featureFeeds.v.checked=g_setting.featureFeeds;
	document.featureBlockInputPrompts.v.checked=g_setting.featureBlockInputPrompts;
	// MClick new tab
	document.MClickNewTab.v.checked=g_setting.MClickNewTab;
	// target name resolve
	document.targetNameResolve.v.checked=g_setting.targetNameResolve;
	// trident theme
	document.tridentTheme.v.checked=g_setting.tridentTheme;
	// auto complete
	document.autoComplete.v.checked=g_setting.autoComplete;
	// dpi aware
	document.dpiAware.v.checked=g_setting.dpiAware;
	// drop action
	document.dropAction.v.checked=g_setting.dropAction;
	// mouse gesture
	document.mouseGesture.v[g_setting.mouseGesture].checked=true;
	// mouse gesture limit
	document.mouseGestureLimit.v.value=g_setting.mouseGestureLimit;
	// mouse redirect
	document.wheelRedirect.v.checked=g_setting.wheelRedirect;
	// new url
	document.newUrl.v.value=g_setting.newUrl;
	// search new tab
	document.searchNewTab.v.checked=g_setting.searchNewTab;
	// tab style
	document.tabStyle.v[g_setting.tabStyle].checked=true;
	// new tab position
	document.newTabPosition.v[g_setting.newTabPosition].checked=true;
	// new tab position tab list
	selectOption(document.newTabPositionTabList.v.options,g_setting.newTabPositionTabList);
	// new tab activate
	document.newTabActivate.v.checked=g_setting.newTabActivate;
	// new process activate
	selectOption(document.newProcessActivate.v.options,g_setting.newProcessActivate);
	// close active tab
	document.closeActiveTab.v[g_setting.closeActiveTab].checked=true;
	// last tab cmd
	document.lastTabCmd.v[g_setting.lastTabCmd].checked=true;
	// wheel tab
	document.wheelTab.v.checked=g_setting.wheelTab;
	// wheel tab loop
	document.wheelTabLoop.v.checked=g_setting.wheelTabLoop;
	// wheel tab scroll
	document.wheelTabScroll.v.checked=g_setting.wheelTabScroll;
	// select tab MDI
	document.selectTabMDI.v.checked=g_setting.selectTabMDI;
	// nav close lock
	document.navCloseLock.v.checked=g_setting.navCloseLock;
	// show tab state
	document.showTabState.v.checked=g_setting.showTabState;
	// active no auto refresh
	document.activeNoAutoRefresh.v.checked=g_setting.activeNoAutoRefresh;
	// taskbar thumbnail
	document.taskbarThumbnail.v.checked=g_setting.taskbarThumbnail;
	// taskbar progress
	document.taskbarProgress.v.checked=g_setting.taskbarProgress;
	// check downloading
	document.checkDownloading.v.checked=g_setting.checkDownloading;
	// delete history on close
	document.deleteHistoryOnClose.v.checked=g_setting.deleteHistoryOnClose;
	// delete cache on close
	document.deleteCacheOnClose.v.checked=g_setting.deleteCacheOnClose;
	// delete cookie on close
	document.deleteCookieOnClose.v.checked=g_setting.deleteCookieOnClose;
	// delete search history on close
	document.deleteSearchHistoryOnClose.v.checked=g_setting.deleteSearchHistoryOnClose;
	// delete address history on close
	document.deleteAddressHistoryOnClose.v.checked=g_setting.deleteAddressHistoryOnClose;
	// jump list
	document.jumpList.v.checked=g_setting.jumpList;
	toggleEnable(document.jumpList.v,'jumpListButton');
	// show active script error
	document.showActiveScriptError.v.checked=g_setting.showActiveScriptError;
	// show page script error
	document.showPageScriptError.v.checked=g_setting.showPageScriptError;
	// favicon
	document.favicon.v.checked=g_setting.favicon;
	// thumbnail
	document.thumbnail.v.checked=g_setting.thumbnail;
	// feed
	document.feed.v.checked=g_setting.feed;
	// feed new tab
	document.feedNewTab.v.checked=g_setting.feedNewTab;
	// auto hilite
	document.autoHilite.v.checked=g_setting.autoHilite;
	// inherit hilite
	document.inheritHilite.v.checked=g_setting.inheritHilite;
	// tab pos
	document.tabPos.v[g_setting.tabPos].checked=true;
	// hilite pos
	document.hilitePos.v[g_setting.hilitePos].checked=true;
	// isearch pos
	document.isearchPos.v[g_setting.isearchPos].checked=true;
	// max search histroy
	document.maxSearchHistory.v.value=g_setting.maxSearchHistory;
	// max inc history
	document.maxIncHistory.v.value=g_setting.maxIncHistory;
	// lock toolbar
	document.lockToolbar.v.checked=g_setting.lockToolbar;
	// favicon limit count
	document.faviconLimitCount.v.value=g_setting.faviconLimitCount;
	// favicon delete percent
	document.faviconDeletePercent.v.value=g_setting.faviconDeletePercent;
	// thumbnail limit count
	document.thumbnailLimitCount.v.value=g_setting.thumbnailLimitCount;
	// thumbnail delete percent
	document.thumbnailDeletePercent.v.value=g_setting.thumbnailDeletePercent;
	// DEP
	document.DEP.v.checked=g_setting.DEP;
	// LFH
	document.LFH.v.checked=g_setting.LFH;
	// crash file
	document.crashFile.v.checked=g_setting.crashFile;
	// delete old crash file
	document.deleteOldCrashFile.v.checked=g_setting.deleteOldCrashFile;
	// save closed
	document.saveClosed.v.checked=g_setting.saveClosed;
	// EBPlus tab mode
	document.EBPlusTabMode.v.checked=g_setting.EBPlusTabMode;
	// url action
	document.urlAction.v.checked=g_setting.urlAction;
	// sub frame url action
	document.subFrameUrlAction.v.checked=g_setting.subFrameUrlAction;

	// select main
	g_cats[0].click();
	
	// focus
	document.findKeyword.v.focus();
}
function apply(){
	if(!apply_check()){
		return;
	}
	if(g_initUrlAction){
		if(saveUrlAction()){
			g_ext.reloadUrlAction();
		}
	}
	if(g_initProxy){
		saveProxy();
		var	indexProxy=getCheckedIdx(document.proxy.v,0);
		var	proxy="";
		if(1===indexProxy){
			proxy=":direct:";
		}else if(2===indexProxy){
			proxy=getSelectedValue(document.proxyList.v.options);
			if(proxy===":ng:"){
				alert("プロキシ情報が選択してください");
				document.proxyList.v.focus();
				return;
			}
			if(!getFSO().FileExists(getProxySettingPathFromName(proxy))){
				alert("プロキシ情報のファイルが読み取れません。");
				document.proxyList.v.focus();
				return;
			}
		}
		g_setting.proxy=proxy;
	}

	// start
	g_setting.start=getCheckedIdx(document.start.v,g_setting.start);
	// app style
	g_setting.style=getCheckedIdx(document.appStyle.v,g_setting.style);
	// view style
	g_setting.viewStyle=getCheckedIdx(document.viewStyle.v,g_setting.viewStyle);
	// single instance
	g_setting.singleInstance=document.singleInstance.v.checked;
	// single instance start enable
	g_setting.singleInstanceStartEnable =document.singleInstanceStartEnable.v.checked;
	// max closed
	g_setting.maxClosed=parseInt(document.maxClosed.v.value);
	// max travellog
	g_setting.maxTravelLog=parseInt(document.maxTravelLog.v.value);
	// max lasttab
	g_setting.maxLastTab=parseInt(document.maxLastTab.v.value);
	// tab width
	var	tabWidth=parseInt(document.tabWidth.v.value);
	if(tabWidth < 20) {
		tabWidth=20;
	}
	g_setting.tabWidth=tabWidth;
	// tab font
	var	tabFont="";
	if(!g_defaultTabFont){
		tabFont=$$("currentTabFont").innerText;
	}
	g_setting.tabFont=tabFont;
	// auto text link
	g_setting.autoTextLink=document.autoTextLink.v.checked;
	// auto text link dialog
	g_setting.autoTextLinkDialog=document.autoTextLinkDialog.v.checked;
	// auto image resize
	g_setting.autoImageResize=document.autoImageResize.v.checked;
	// security
	var	security = 0;
	security|=(document.securityImage.v.checked?0x10:0);
	security|=(document.securityVideo.v.checked?0x20:0);
	security|=(document.securitySound.v.checked?0x40:0);
	security|=(document.securityScript.v.checked?0:0x80);
	security|=(document.securityJava.v.checked?0:0x100);
	security|=(document.securityRunActiveX.v.checked?0:0x200);
	security|=(document.securityDownloadActiveX.v.checked?0:0x400);
	g_setting.security=security;
	g_setting.metaRefresh=document.metaRefresh.v.checked;
	// inherit security
	g_setting.inheritSecurity=document.inheritSecurity.v.checked;
	// user agent
	if(g_initUserAgent) {
		var	idx=document.userAgentList.v.selectedIndex;
		if(0==idx) {
			g_setting.userAgent="";
		} else {
			g_setting.userAgent=document.userAgent.v.value;
		}
	}
	// feature
	g_setting.featureBrowserEmulation=getSelectedValue(document.featureBrowserEmulation.v.options);
	g_setting.featureGpuRendering=document.featureGpuRendering.v.checked;
	g_setting.featureObjectCaching=document.featureObjectCaching.v.checked;
	g_setting.featureZoneElevation=document.featureZoneElevation.v.checked;
	g_setting.featureMimeHandling=document.featureMimeHandling.v.checked;
	g_setting.featureMimeSniffing=document.featureMimeSniffing.v.checked;
	g_setting.featureWindowRestrictions=document.featureWindowRestrictions.v.checked;
	g_setting.featureWebocPopupmanagement=document.featureWebocPopupmanagement.v.checked;
	g_setting.featureBehaviors=document.featureBehaviors.v.checked;
	g_setting.featureDisableMkProtocol=document.featureDisableMkProtocol.v.checked;
	g_setting.featureLocalmachineLockdown=document.featureLocalmachineLockdown.v.checked;
	g_setting.featureSecurityband=document.featureSecurityband.v.checked;
	g_setting.featureRestrictActivexinstall=document.featureRestrictActivexinstall.v.checked;
	g_setting.featureValidateNavigateUrl=document.featureValidateNavigateUrl.v.checked;
	g_setting.featureRestrictFiledownload=document.featureRestrictFiledownload.v.checked;
	g_setting.featureProtocolLockdown=document.featureProtocolLockdown.v.checked;
	g_setting.featureHttpUsernamePasswordDisable=document.featureHttpUsernamePasswordDisable.v.checked;
	g_setting.featureSafeBindtoobject=document.featureSafeBindtoobject.v.checked;
	g_setting.featureUncSavedfilecheck=document.featureUncSavedfilecheck.v.checked;
	g_setting.featureGetUrlDomFilepathUnencoded=document.featureGetUrlDomFilepathUnencoded.v.checked;
	g_setting.featureTabbedBrowsing=document.featureTabbedBrowsing.v.checked;
	g_setting.featureSslux=document.featureSslux.v.checked;
	g_setting.featureDisableNavigationSounds=document.featureDisableNavigationSounds.v.checked;
	g_setting.featureDisableLegacyCompression=document.featureDisableLegacyCompression.v.checked;
	g_setting.featureXmlHttp=document.featureXmlHttp.v.checked;
	g_setting.featureDisableTelnetProtocol=document.featureDisableTelnetProtocol.v.checked;
	g_setting.featureFeeds=document.featureFeeds.v.checked;
	g_setting.featureBlockInputPrompts=document.featureBlockInputPrompts.v.checked;
	// MClick new tab
	g_setting.MClickNewTab=document.MClickNewTab.v.checked;
	// target name resolve
	g_setting.targetNameResolve=document.targetNameResolve.v.checked;
	// trident theme
	g_setting.tridentTheme=document.tridentTheme.v.checked;
	// auto complete
	g_setting.autoComplete=document.autoComplete.v.checked;
	// dpi aware
	g_setting.dpiAware=document.dpiAware.v.checked;
	// drop action
	g_setting.dropAction=document.dropAction.v.checked;
	// mouse gesture
	g_setting.mouseGesture=getCheckedIdx(document.mouseGesture.v,g_setting.mouseGesture);
	// mouse gesture limit
	var	mouseGestureLimit=parseInt(document.mouseGestureLimit.v.value);
	if(mouseGestureLimit < 1) {
		mouseGestureLimit=4;
	}
	g_setting.mouseGestureLimit=mouseGestureLimit;
	// mouse redirect
	g_setting.wheelRedirect=document.wheelRedirect.v.checked;
	// new url
	g_setting.newUrl=document.newUrl.v.value;
	// search new tab
	g_setting.searchNewTab=document.searchNewTab.v.checked;
	// tab style
	g_setting.tabStyle=getCheckedIdx(document.tabStyle.v,g_setting.tabStyle);
	// new tab position
	g_setting.newTabPosition=getCheckedIdx(document.newTabPosition.v,g_setting.newTabPosition);
	// new tab position tab list
	g_setting.newTabPositionTabList=parseInt(getSelectedValue(document.newTabPositionTabList.v.options));
	// new tab activate
	g_setting.newTabActivate=document.newTabActivate.v.checked;
	// new process activate
	g_setting.newProcessActivate=parseInt(getSelectedValue(document.newProcessActivate.v.options));
	// close active tab
	g_setting.closeActiveTab=getCheckedIdx(document.closeActiveTab.v,g_setting.closeActiveTab);
	// last tab cmd
	g_setting.lastTabCmd=getCheckedIdx(document.lastTabCmd.v,g_setting.lastTabCmd);
	// wheel tab
	g_setting.wheelTab=document.wheelTab.v.checked;
	// wheel tab loop
	g_setting.wheelTabLoop=document.wheelTabLoop.v.checked;
	// wheel tab scroll
	g_setting.wheelTabScroll=document.wheelTabScroll.v.checked;
	// select tab MDI
	g_setting.selectTabMDI=document.selectTabMDI.v.checked;
	// nav close lock
	g_setting.navCloseLock=document.navCloseLock.v.checked;
	// show tab state
	g_setting.showTabState=document.showTabState.v.checked;
	// active no auto refresh
	g_setting.activeNoAutoRefresh=document.activeNoAutoRefresh.v.checked;
	// show active script error
	g_setting.showActiveScriptError=document.showActiveScriptError.v.checked;
	// show page script error
	g_setting.showPageScriptError=document.showPageScriptError.v.checked;
	// taskbar thumbnail
	g_setting.taskbarThumbnail=document.taskbarThumbnail.v.checked;
	// taskbar progress
	g_setting.taskbarProgress=document.taskbarProgress.v.checked;
	// check downloading
	g_setting.checkDownloading=document.checkDownloading.v.checked;
	// delete history on close
	g_setting.deleteHistoryOnClose=document.deleteHistoryOnClose.v.checked;
	// delete cache on close
	g_setting.deleteCacheOnClose=document.deleteCacheOnClose.v.checked;
	// delete cookie on close
	g_setting.deleteCookieOnClose=document.deleteCookieOnClose.v.checked;
	// delete search history on close
	g_setting.deleteSearchHistoryOnClose=document.deleteSearchHistoryOnClose.v.checked;
	// delete address history on close
	g_setting.deleteAddressHistoryOnClose=document.deleteAddressHistoryOnClose.v.checked;
	// jump list
	g_setting.jumpList=document.jumpList.v.checked;
	// favicon
	g_setting.favicon=document.favicon.v.checked;
	// thumbnail
	g_setting.thumbnail=document.thumbnail.v.checked;
	// feed
	g_setting.feed=document.feed.v.checked;
	// feed new tab
	g_setting.feedNewTab=document.feedNewTab.v.checked;
	// auto hilite
	g_setting.autoHilite=document.autoHilite.v.checked;
	// inherit hilite
	g_setting.inheritHilite=document.inheritHilite.v.checked;
	// tab pos
	g_setting.tabPos=getCheckedIdx(document.tabPos.v,g_setting.tabPos);
	// hilite pos
	g_setting.hilitePos=getCheckedIdx(document.hilitePos.v,g_setting.hilitePos);
	// isearch pos
	g_setting.isearchPos=getCheckedIdx(document.isearchPos.v,g_setting.isearchPos);
	// max search history
	g_setting.maxSearchHistory=parseInt(document.maxSearchHistory.v.value);
	// max inc history
	g_setting.maxIncHistory=parseInt(document.maxIncHistory.v.value);
	// mouse
	if(g_initMouseAction){
		for(category in g_cmdInfo){
			var	infos=g_cmdInfo[category];
			for(name in infos){
				g_setting[name]=getSelectedValue(document[name].v.options);
			}
		}
	}
	// accel
	if(g_initAccel){
		// del add accel item
		var	accel=$($$("idAppAccel")).data("accel");
		var	list=accel.list;
		list.del(list.count-1);
		// apply del
		var	count=list.count;
	
		while(count){
			--count;
			if(list.markDel(count)){
				list.del(count);
			}
		}
		// check default accel list
		list.sort();
		g_setting.defaultAccelList=false;
		if(compareAccelList(list,g_setting.defaultAccelList)){
			g_setting.defaultAccelList=true;
		}
		// check custom accel list
		else if(! compareAccelList(list,g_setting.accelList)){
			g_setting.accelList=list;
		}
	}
	// favicon limit count
	g_setting.faviconLimitCount=parseInt(document.faviconLimitCount.v.value);
	// favicon delete percent
	g_setting.faviconDeletePercent=parseInt(document.faviconDeletePercent.v.value);
	// thumbnail limit count
	g_setting.thumbnailLimitCount=parseInt(document.thumbnailLimitCount.v.value);
	// thumbnail delete percent
	g_setting.thumbnailDeletePercent=parseInt(document.thumbnailDeletePercent.v.value);
	// DEP
	g_setting.DEP=document.DEP.v.checked;
	// LFH
	g_setting.LFH=document.LFH.v.checked;
	// check file
	g_setting.crashFile=document.crashFile.v.checked;
	// delete old crash file
	g_setting.deleteOldCrashFile=document.deleteOldCrashFile.v.checked;
	// save closed
	g_setting.saveClosed=document.saveClosed.v.checked;
	// EBPlus tab mode
	g_setting.EBPlusTabMode=document.EBPlusTabMode.v.checked;
	// url action
	g_setting.urlAction=document.urlAction.v.checked;
	// sub frame url action
	g_setting.subFrameUrlAction=document.subFrameUrlAction.v.checked;

	g_ext.optionApply();
	g_ext.optionClose();
}
function apply_check(){
	var	checks=
	[
			document.maxClosed
		,	document.maxLastTab
		,	document.maxTravelLog
		,	document.tabWidth
		,	document.mouseGestureLimit
		,	document.maxSearchHistory
		,	document.maxIncHistory
		,	document.faviconLimitCount
		,	document.faviconDeletePercent
		,	document.thumbnailLimitCount
		,	document.thumbnailDeletePercent
	];
	for(i=0;i<checks.length;++i){
		if(0===checks[i].v.value.length){
			alert("不正な入力です。["+checks[i].name+"]");
			checks[i].v.focus();
			return false;
		}
	}
	return true;
}
