// ------------
// prototype
// ------------
/**
 * 文字列をトリムします（半角スペースのみ）
 */
String.prototype.trim = function() {
	return this.replace(/^\s+|[\s]+$/g, "");
};
/**
 * 文字列をトリムします（全半角スペース）
 */
String.prototype.trimW = function() {
	return this.replace(/^\s+|[\s　]+$/g, "");
};
/**
 * 文字列を指定回数繰り返します。
 * @param count 回数
 * @return
 */
String.prototype.repeat = function(count) {
	if ( count <= 0 ) {
		return "";
	} else {
		return this + this.repeat(--count);
	}
};
/**
 * 指定文字長になるまで、右側をpad文字で埋めます。
 * @param len 文字長
 * @param pad 文字列の場合は1文字目のみ
 * @return
 */
String.prototype.rpad = function(len, pad) {
	return this + pad.charAt(0).repeat(len - this.length);
};
/**
 * 指定文字長になるまで、左側をpad文字で埋めます。
 * @param len 文字長
 * @param pad 文字列の場合は1文字目のみ
 * @return
 */
String.prototype.lpad = function(len, pad) {
	return pad.charAt(0).repeat(len - this.length) + this;
};


// ------------
// top-level
// ------------

//２度押し禁止
var processing = false;

function isProcessing() {
	if(window.document.readyState != null && window.document.readyState != 'complete' && document.readyState != "interactive") {
		alert('ただいま処理中です\nしばらくお待ちください');
		return true;
	} else {
		return false;
	}
}

//２度押し禁止
var processingAjax = false;

function isProcessingAjax() {
	if (processingAjax) {
		alert('ただいま処理中です\nしばらくお待ちください');
		return true;
	} else {
		return false;
	}
}

function setProcessingAjax(processing) {
	processingAjax = processing;
}

var session_button_info = null;
/**
 * ボタンポップアップを表示するかどうかを返します。<br>
 * @return
 */
function isDisplayPopup() {
	// ユーザー情報による
	if ( session_button_info != "0" ) {
		// window.onload() 完了後から制御可能
		if ( document.readyState == 'complete' ) {
			return true;
		}
	}
	return false;
}

/**
 * sgn 関数
 * @param x integer
 * @return 正値のとき 1 、負値のとき -1 、ゼロのとき 0 を返す
 */
function sgn(x) {
	return (x>0) | - (x<0);
}

/**
 * ヘッダーのボタン画像に説明画像をポップアップさせます。
 * @param ImgIdName イメージid
 * @param TableIdName テーブルid
 * @param ColIdName tdのid
 * @param Filename ファイルパス
 * @param NewDivIdName
 * @param intX
 * @param intY
 * @param intHoseiY
 * @param intHoseiX
 */
function createPopupForHeader(ImgIdName,TableIdName,ColIdName,Filename,NewDivIdName,intX,intY,intHoseiY,intHoseiX)
{
	if ( !isDisplayPopup() ) return;

	var div = document.createElement("div");
	var intTop = document.getElementById(TableIdName).offsetTop + document.getElementById(ColIdName).offsetTop + document.getElementById(ImgIdName).offsetTop + intHoseiY + intY;
	var intLeft = document.getElementById(ColIdName).offsetLeft + intX + intHoseiX;

	div.id = NewDivIdName;
	div.style.position = "absolute";
	div.style.top = intTop + "px";
	div.style.left =  intLeft + "px";
	div.style.zIndex = 100;
	document.body.appendChild(div);

	var img2 = document.createElement("img");
	img2.src = Filename;

	document.getElementById(div.id).appendChild(img2);
}

/**
 * createPopupForHeader() で作成したポップアップを削除します
 */
function removePopupForHeader(NewDivIdName)
{
	if ( !isDisplayPopup() ) return;

	if (document.getElementById(NewDivIdName) != null)
	{
		var div = document.getElementById(NewDivIdName);
		document.body.removeChild(div);
	}
}

/**
 * 指定したオブジェクトが、BODYタグであるかを返します。
 * @param obj タグオブジェクト
 * @return
 */
function isBodyElement(obj) {
	return ( obj != null && obj.tagName=="BODY" );
}

/**
 * 指定したオブジェクトが、strClass の div タグであるかを返します。
 * @param obj タグオブジェクト
 * @param strClass スタイルクラス名
 * @return
 */
function isDivElement(obj, strClass) {
	return ( obj != null && obj.tagName=="DIV" && obj.className.indexOf(strClass) >= 0 );
}

/**
 * ポップアップ画像を、ベースのオブジェクトの真下に作成します。<br>
 * position:relative または absolute のエレメントの内側で使用してください。
 * @param baseImgObj 基点となるイメージタグエレメント
 * @param popupImgFile ポップアップする画像ファイルパス
 * @param popupDivId 作成するポップアップDIVタグのID
 * @param offsetY 規定の位置からの補正量（下方向をプラスとする。px単位）
 * @param offsetX 規定の位置からの補正量（右方向をプラスとする。px単位）
 * @return
 */
function createPopup(baseImgObj, popupImgFile, popupDivId, offsetY, offsetX) {

	if ( !isDisplayPopup() ) return;

	// BODY 直下のエレメントからのオフセット位置を計算
	var popupTop = 0;
	var popupLeft = 0;
	var obj = baseImgObj;
	while ( obj != null && !isBodyElement(obj.offsetParent) ) {
		popupTop += obj.offsetTop;
		popupLeft += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	var bodysChild = obj;

	var popupDiv = document.createElement("div");
	popupDiv.id = popupDivId;
	popupDiv.style.position = "absolute";
	popupDiv.style.top = popupTop + baseImgObj.offsetHeight + offsetY + "px";
	popupDiv.style.left = popupLeft + offsetX + "px";
	popupDiv.style.zIndex = 100;

	var popupImg = document.createElement("img");
	popupImg.src = popupImgFile;

	document.body.appendChild(popupDiv);
	popupDiv.appendChild(popupImg);

	bodysChild.appendChild(popupDiv);
}

/**
 * createPopup()で作成したポップアップを削除します。<br>
 * @param elementId 削除するポップアップDIVタグのID
 * @return なし
 */
function removePopup(elementId) {

	if ( !isDisplayPopup() ) return;

	var divObj = document.getElementById(elementId);
	if ( divObj && divObj.tagName == "DIV" )
		divObj.parentNode.removeChild(divObj);
}

/**
 * フォームのデータをコピーします。
 * @param form formオブジェクト(cf. document.forms[0])
 * @param storeMapping インプットフォーム名の対応付け定義情報オブジェクト。{コピー先name:コピー元name, ...}
 */
function saveFormContents(form, storeMapping) {
	for ( dest in storeMapping ) {
		var src = storeMapping[dest];
		// 子オブジェクトをもつかどうか
		if ( form[src][0] ) {

			switch ( form[src][0].tagName ) {
			case "OPTION": // select tag
				form[dest].value = form[src].value;
				break;
			case "INPUT":
				// type="radio" のみを想定
				for ( i = 0; i < form[src].length; i++ ) {
					if ( form[src][i].type == "radio" && form[src][i].checked ) {
						form[dest].value = form[src][i].value;
						break;
					}
				}
				break;
			default:
			}
		}
		else {
			switch ( form[src].tagName ) {
			case "SELECT":
				// fall thru
			case "TEXTAREA":
				form[dest].value = form[src].value;
				break;
			case "INPUT":
				switch ( form[src].type ) {
				case "checkbox":
					form[dest].value = form[src].checked;
					break;
				case "file":
					// fall thru
				case "hidden":
					// fall thru
				case "password":
					// fall thru
				case "text":
					form[dest].value = form[src].value;
					break;
				default:
				}
				break;
			default:
			}
		}
	}
}

/**
 * クエリ文字列を付加してsubmitします。
 * @param form formオブジェクト
 * @param queryString リクエストに付加するクエリ文字列(ex. "p1=v1&p2=v2")
 */
function doSubmitWithParameter(formObj, queryString) {
	// anchor がある場合はパラメータを間に挿入する
	var url = formObj.action;
	var path = url;
	var anchor = "";
	if ( path.indexOf("#") >= 0 ) {
		path = url.split("#")[0];
		anchor = "#" + url.split("#")[1];
	}
	if ( queryString ) {
		if ( path.indexOf("?") < 0 ) {
			path = path + "?";
		} else {
			path = path + "&";
		}
		formObj.action = path + queryString;
	}
	if ( anchor ) {
		path = path + anchor;
	}
	formObj.submit();
}

/**
 * クエリ文字列を付加してlocationを変更します。
 * @param url 遷移先URL（<html:rewrite />などを利用してください。）
 * @param queryString リクエストに付加するクエリ文字列(ex. "p1=v1&p2=v2")
 */
function doLoadWithParameter(url, queryString) {
	// anchor がある場合はパラメータを間に挿入する
	var path = url;
	var anchor = "";
	if ( url.indexOf("#") >= 0 ) {
		path = url.split("#")[0];
		anchor = "#" + url.split("#")[1];
	}
	if ( queryString ) {
		if ( path.indexOf("?") < 0 ) {
			path = path + "?";
		} else {
			path = path + "&";
		}
		path = path + queryString;
	}
	if ( anchor ) {
		path = path + anchor;
	}
	document.location = path;
}

//指定されたウィンドウでアドレス先のページを表示し、前画面は閉じる
function OpenAddWindow(addname , winname)
{

	nWin = window.open(addname,"MainWindow");
	nWin.focus();
	window.close();

}

//指定された画面パラメータで詳細画面をオープンする。
function OpenDetailWindow(strContextPath,strId,strIdEda,strIdFlg,strPara)
{
	var strHref = strContextPath + "/JWEB_CommonDetailInit.do?id=" + strId + "&idEda=" + strIdEda + "&idFlg=" + strIdFlg + "&param=" + strPara;
	nWin = window.open(strHref,"detail","width=510,height=505,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
	nWin.focus();
}

//指定された画面パラメータで詳細画面をオープンする。
function OpenMypageDetailWindow(strContextPath,strId,strIdEda,strIdFlg,strPara)
{
	var strHref = strContextPath + "/JWEB_CommonDetailInit.do?id=" + strId + "&idEda=" + strIdEda + "&idFlg=" + strIdFlg + "&param=" + strPara;
	nWin = window.open(strHref,"mypge_detail","width=510,height=505,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
	nWin.focus();
}

//指定された画面パラメータで画像表示画面をオープンする。
function OpenGazouWindow(strContextPath,strId,strIdEda,strGazouFlg)
{
	var strHref = strContextPath + "/JWEB_GazouFileShowInit.do?id=" + strId + "&idEda=" + strIdEda + "&gazouFlg=" + strGazouFlg;
	nWin = window.open(strHref,"gazou","menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no");
	nWin.focus();
}

//指定された画面パラメータでPDF表示画面をオープンする。
function OpenPdfWindow(strContextPath,strPdfName,strPdfParam)
{
	var strHref = strContextPath + "/JWEB_PdfShowInit.do?PDF_PARAM=" + strPdfParam + "&" + makeParameterString({"PDF_NAME" : strPdfName} , true);
	nWin = window.open(strHref,"jweb_pdf","width=850,height=650,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
	nWin.focus();
}

//指定された画面パラメータで動画表示画面をオープンする。
function OpenMovieWindow(strContextPath,strId,strIdEda)
{
	var strHref = strContextPath + "/JWEB_MovieShowInit.do?id=" + strId + "&idEda=" + strIdEda;
	nWin = window.open(strHref,"jweb_movie","width=640,height=480,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
	nWin.focus();
}

//指定されたヘルプファイル名でヘルプウィンドウへ出力する
function OpenHelpWindow(strContextPath,strHelpName)
{
	var strHref = strContextPath + "/JWEB_Forward.do?/link/" + strHelpName + ".htm";
	nWin = window.open(strHref,"jweb_help","width=682,height=512,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
	nWin.focus();
}

//指定された操作説明ファイル名で操作説明ウィンドウへ出力する
function OpenOperWindow(strContextPath,strOper)
{
	var strHref = strContextPath + "/JWEB_Forward.do?/link/" + strOper + ".htm";
	nWin = window.open(strHref,"jweb_oper","width=682,height=512,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
	nWin.focus();
}

//利用規約ウィンドウを表示する
function OpenRulesWindow(strContextPath)
{
	var strHref = strContextPath + "/JWEB_Rules.do";
	nWin = window.open(strHref,"jweb_rules","width=682,height=512,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
	nWin.focus();
}

//指定された画面パラメータでDBUP画面のPDF表示画面をオープンする。
function DbupOpenPdfWindow(strContextPath,strPdfName,strPdfParam)
{
	var strHref = strContextPath + "/DBUP_PdfShowInit.do?PDF_PARAM=" + strPdfParam + "&" + makeParameterString({"PDF_NAME" : strPdfName} , true);
	nWin = window.open(strHref,"dbup_pdf","width=850,height=650,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
	nWin.focus();
}

/**
 * パラメータ文字列を構成します。
 * @param key_values キー/値を持つObject。例: {"param1":"value1","param2":"value2", ...}
 * @param with_encode {@code TRUE }のときURLエンコードします。
 * @return 上記の例の場合、"param1=value1&param2=value2&..."
 */
function makeParameterString(key_values, with_encode) {
	var param = "";
	for (key in key_values) {
		var value = key_values[key];
		if ( with_encode ) {
			value = encodeURIComponent(value);
		}
		param += ("&" + key + "=" + value);
	}
	return param.slice(sgn(param.length));
}

/**
 * クエリ文字列から連想配列を生成します。<br>
 * 用例： params = getParameter(location.search, false);
 * @param query_string
 * @param with_decode
 * @return
 */
function getParameter(query_string, with_decode){
	var par = new Array;
	if ( typeof(query_string) == 'undefined' )
		return par;
	if ( query_string.indexOf('?', 0) >= 0 )
		query_string = query_string.split('?')[1];
	query_string = query_string.split('&');
	for ( i = 0; query_string.length > i; i++ ) {
		var itm = query_string[i].split("=");
		if ( itm[0] != '' ) {
			if ( typeof(itm[1]) == 'undefined' ) {
				par[itm[0]] = true;
			} else if ( with_decode ) {
				par[itm[0]] = decodeURIComponent(itm[1]);
			} else {
				par[itm[0]] = itm[1];
			}
		}
	}
	return par;
}

/**
 * クエリ文字列から指定のパラメータのみを抜き出した連想配列を生成します。<br>
 * 用例: params = retainParameter(location.search, new Array('paramid1','paramid2'...), false)
 * @param query_string クエリ文字列（location.search 推奨）
 * @param param_id_array 抽出するパラメータID配列
 * @param with_decode 抽出する際にURLエンコードをデコードするかどうか
 * @return
 */
function retainParameter(query_string, param_id_array, with_decode) {
	var preparams = getParameter(query_string, with_decode);
	var newparams = new Array;
	for (prop in param_id_array) {
		var id = param_id_array[prop];
		var val = preparams[id];
		if ( typeof(val) != 'undefined' )
			newparams[id] = val;
	}
	return newparams;
}

/**
 * JWEBOptionsFactory#CreateKikanOptionsで作成したセレクトボックスから期間を設定します。<br>
 * 設定先はセレクトボックスと同じフォーム内になければいけません
 * @param selectObj セレクトボックスオブジェクト
 * @param from_year 年のオブジェクト名（設定しない場合はnull）
 * @param from_month 月のオブジェクト名（設定しない場合はnull）
 * @param from_day 日のオブジェクト名（設定しない場合はnull）
 * @param to_year 年のオブジェクト名（設定しない場合はnull）
 * @param to_month 月のオブジェクト名（設定しない場合はnull）
 * @param to_day 日のオブジェクト名（設定しない場合はnull）
 * @return
 */
function fillKikan(selectObj, from_year, from_month, from_day, to_year, to_month, to_day) {
	var formObj = selectObj.form;
	var operator = selectObj.options[selectObj.selectedIndex].value;
	var now = new Date();
	var from = null;
	var to = null;
	var filling = false;
	if ( operator == "fullterm" ) {
		filling = true;
		// 期間開始を求める（valueが一番小さいもの）
		minYear = now.getFullYear();
		if ( formObj[from_year] != undefined ) {
			for (i=0; i<formObj[from_year].length; i++) {
				if ( formObj[from_year].options[i].value != "" && formObj[from_year].options[i].value < minYear )
					minYear = formObj[from_year].options[i].value;
			}
		}
		from = new Date(minYear, 0, 1);
		to = now;
	} else if ( operator == "last1year" ) {
		filling = true;
		from = new Date(now.getFullYear() -1, now.getMonth(), now.getDate());
		to = now;
	} else if ( operator == "last1month" ) {
		filling = true;
		from = new Date(now.getFullYear(), now.getMonth() -1, now.getDate());
		to = now;
	} else if ( operator == "last1week" ) {
		filling = true;
		from = new Date(now.getFullYear(), now.getMonth(), now.getDate() -7);
		to = now;
	}
	if ( filling ) {
		if ( from == null ) {
			if ( formObj[from_year] != undefined ) formObj[from_year].value = "";
			if ( formObj[from_month] != undefined ) formObj[from_month].value = "";
			if ( formObj[from_day] != undefined ) formObj[from_day].value = "";
		} else {
			if ( formObj[from_year] != undefined ) formObj[from_year].value = from.getFullYear();
			if ( formObj[from_month] != undefined ) formObj[from_month].value = ("0" + (from.getMonth() + 1)).slice(-2);
			if ( formObj[from_day] != undefined ) formObj[from_day].value = ("0" + from.getDate()).slice(-2);
		}
		if ( to == null ) {
			if ( formObj[to_year] != undefined ) formObj[to_year].value = "";
			if ( formObj[to_month] != undefined ) formObj[to_month].value = "";
			if ( formObj[to_day] != undefined ) formObj[to_day].value = "";
		} else {
			if ( formObj[to_year] != undefined ) formObj[to_year].value = to.getFullYear();
			if ( formObj[to_month] != undefined ) formObj[to_month].value = ("0" + (to.getMonth() + 1)).slice(-2);
			if ( formObj[to_day] != undefined ) formObj[to_day].value = ("0" + to.getDate()).slice(-2);
		}
	}
}

/**
 * 指定年月の最終日を取得します。
 * @param y 年
 * @param m 月
 * @return 最終日（ex. 2100/2 は 28）
 */
function getLastDayOfMonth(y, m) {
	return (new Date(y, m, 0)).getDate();
}

/**
 * menu_top画面の画像リサイズ処理
 * @param menu_top_right     右側に表示される画像
 * @param menu_top_interview インタビュー欄（左側に表示）の画像
 *
 */
function resize_img() {
	var max_width_right  = 128;
	var max_height_right = 96;

	var max_width_interview = 48;
	var max_height_interview = 64;

	for (i in document.images) {
		if (document.images[i].className == 'menu_img_right') {
			document.images[i].style.display = "inline"; // 画像表示
			stretchImage(document.images[i], max_width_right, max_height_right);
		} else if (document.images[i].className == 'menu_img_interview') {
			document.images[i].style.display = "inline"; // 画像表示
			stretchImage(document.images[i], max_width_interview, max_height_interview);
		}
	}
}

/**
 * 詳細画面の画像リサイズ処理
 * @param detail_large 上の大きい画像（１つ）
 * @param detail_small 下の小さい画像（２つ）
 *
 */
function resize_detail_img() {
	var max_width_large  = 128;
	var max_height_large = 96;

	var max_width_small = 64;
	var max_height_small = 48;

	for (i in document.images) {
		if (document.images[i].className == 'detail_large') {
			document.images[i].style.display = "inline"; // 画像表示
			stretchImage(document.images[i], max_width_large, max_height_large);
		} else if (document.images[i].className == 'detail_small') {
			document.images[i].style.display = "inline"; // 画像表示
			stretchImage(document.images[i], max_width_small, max_height_small);
		}
	}
}

/**
 * 画像をリサイズします。
 * @param image Imageオブジェクト
 * @param max_height 縦の上限
 * @param max_width  横の上限
 * @return
 */
function stretchImage(image, max_width, max_height) {
	if (max_width / image.width < max_height / image.height) {
		image.height = parseInt(max_width / image.width * image.height);
		image.width = parseInt(max_width / image.width * image.width);
	}
	else {
		image.width = parseInt(max_height / image.height * image.width);
		image.height = parseInt(max_height / image.height * image.height);
	}
}


