// クッキーの値を取得
function getCookie( key ){
	cookieValues = document.cookie.split("; ");
	for( i = 0; i < cookieValues.length; i++ ) {
		cookieElements = cookieValues[i].split("=");
		if( key == cookieElements[0] ) {
			return( decodeJavaURL( cookieElements[1] ) );
		}
	}
	return( "" );
}

// ログイン
function doLogin() {
	if( document.loginForm.isRequested ) {
		alert( "現在、処理を実行中です。\nサーバーが混雑している場合、数分かかる場合があります。\n申し訳ありませんが、今暫くお待ちください。" );
		return false;
	}
	// 入力チェック
	if (!isSingleByte(document.loginForm.user, true, 255, "日本外科学会会員番号", true)) {
		return false;
	}
	if (!isAlphanumeric(document.loginForm.user, true, 255, "日本外科学会会員番号", true)) {
		return false;
	}
	if (!isHtmlTagElementLess(document.loginForm.user, true, 255, "日本外科学会会員番号", true)) {
		return false;
	}

	if (!isSingleByte(document.loginForm.password, true, 255, "パスワード", true)) {
		return false;
	}
	if (!isHtmlTagElementLess(document.loginForm.password, true, 255, "パスワード", true)) {
		return false;
	}

	// 会員番号の値をクッキーに保存
	document.cookie = "id=" + escape(document.loginForm.user.value) + "; expires=Fri, 31-Dec-2030 23:59:59; path=/; ";
	
	document.loginForm.submit();
	document.loginForm.isRequested = true;
	window.focus();
	return false;
}

// 外科学会からのお知らせ
function doCheckOshirase() {
	if( document.loginForm.isRequested ) {
		alert( "現在、処理を実行中です。\nサーバーが混雑している場合、数分かかる場合があります。\n申し訳ありませんが、今暫くお待ちください。" );
		return false;
	}
	document.oshiraseForm.submit();
	document.loginForm.isRequested = true;
	return false;
}

// ログアウト
function doLogout() {
	if( document.loginForm.isRequested ) {
		alert( "現在、処理を実行中です。\nサーバーが混雑している場合、数分かかる場合があります。\n申し訳ありませんが、今暫くお待ちください。" );
		return false;
	}
	document.loginForm.submit();
	document.loginForm.isRequested = true;
	return false;
}

// クリア
function doClear() {
	document.loginForm.user.value = "";
	document.loginForm.password.value = "";
	return false;
}

// 現在表示中のページのパスを取得
function getCurrentPathName() {
	var pathNameValue = location.pathname;
	// パスが「/」で終わる時はindex.htmlを付加
	if(pathNameValue.match('/$')) {
		pathNameValue += 'index.html';
	}
	return pathNameValue;
}

// ヘッダ用共通ボタン部分描画
function writeHeaderCommon() {
	// クッキーの値を取得
	var cookieUserId = getCookie("id");
	var cookieUserName = getCookie("username");

	// 遷移先（次の画面）と戻り先（現在の画面）
	var viewNext = "/jssoc/JSP/login/JssWebShouninKensuuHyouji2JSP.jsp";
	var viewNow  = getCurrentPathName();

	// クッキーに氏名があればログイン済みと判断する
	if(cookieUserName) {
		// お知らせ遷移用action（プロトコルはhttpsを使用）
		var formAction = "https:\/\/" + location.host + "\/servlet\/JssServlet";
		document.write('<form action="' + formAction + '" method="post" name="oshiraseForm">');
		document.write('<input type="hidden" name="bean" value="10050"    \/>');
		document.write('<input type="hidden" name="cmd"  value="continue" \/>');
		document.write('<input type="hidden" name="view" value="' + viewNext + '" \/>');
		document.write('<input type="hidden" name="viewNext"  value="' + viewNow  + '" \/>');
		document.write('<input type="hidden" name="viewError" value="' + viewNext + '" \/>');
		document.write('<input type="hidden" name="NoInsertionPage" value="true" \/>');
		document.write('<ul id="headNav">');
		document.write('<li><a href="/index.html"                          ><img src="/images/headnav001.gif" alt="トップページ" width="80" height="21" border="0" /></a></li>');
		document.write('<li><a href="#" onClick="return doCheckOshirase();"><img src="/images/headnav005.gif" alt="おしらせ"     width="64" height="21" border="0" /></a></li>');
		document.write('<li><a href="/rd/otInquiryMail.html"               ><img src="/images/headnav002.gif" alt="お問い合わせ" width="74" height="21" border="0" /></a></li>');
		document.write('<li><a href="/sitemap/index.html"                  ><img src="/images/headnav003.gif" alt="サイトマップ" width="82" height="21" border="0" /></a></li>');
		document.write('<li><a href="/english/index.html"                  ><img src="/images/headnav004.gif" alt="English"      width="55" height="21" border="0" /></a></li>');
		document.write('<\/form>');
		document.write('</ul>');
	} else {
		document.write('<ul id="headNav">');
		document.write('<li><a href="/index.html"           ><img src="/images/headnav001.gif" alt="トップページ" width="80" height="21" border="0" /></a></li>');
		document.write('<li><a href="/rd/otInquiryMail.html"><img src="/images/headnav002.gif" alt="お問い合わせ" width="74" height="21" border="0" /></a></li>');
		document.write('<li><a href="/sitemap/index.html"   ><img src="/images/headnav003.gif" alt="サイトマップ" width="82" height="21" border="0" /></a></li>');
		document.write('<li><a href="/english/index.html"   ><img src="/images/headnav004.gif" alt="English"      width="55" height="21" border="0" /></a></li>');
		document.write('</ul>');
	}
}

// ヘッダ用ログインフォーム描画
function writeHeaderLoginForm() {
	// クッキーの値を取得
	var cookieUserId = getCookie("id");
	var cookieUserName = getCookie("username");
	
	// フォームの遷移先：現在表示中のページ
	var viewValue = getCurrentPathName();

	// クッキーに氏名があればログイン済みと判断する
	if(cookieUserName) {
		// ログアウト用action（プロトコルはhttpを使用）
		var formAction = "http:\/\/" + location.host + "\/servlet\/JssServlet";
		document.write('<form action="' + formAction + '" method="post" name="loginForm">');
		document.write('<input type="hidden" name="bean" value="1" \/>');
		document.write('<input type="hidden" name="cmd" value="logout" \/>');
		document.write('<input type="hidden" name="view" value="' + viewValue + '" \/>');
		document.write('<input type="hidden" name="viewError" value="' + viewValue + '" \/>');
		document.write('<input type="hidden" name="user" value="' + cookieUserId + '" \/>');
		document.write('<p>');
		document.write('<a href="\/rd\/tjKaiinJyouhouSyoukai.html"><img src="\/images\/btn_change_s.gif" width="77" height="20" border="0" alt="会員登録情報" \/><\/a>');
		document.write('<a href="\/rd\/tjPasswordHenkou.html"><img src="\/images\/btn_pw_s.gif" width="84" height="20" border="0" alt="パスワード変更" \/><\/a>');
		document.write('<a href="\/index.html" onClick="return doLogout();"><img src="\/images\/btn_logout_s.gif" width="70" height="20" border="0" alt="ログアウト" \/><\/a>');
		document.write('<\/p>');
		document.write('<span class="mess">会員番号：<span class="r10">' + cookieUserId + '<\/span>　ようこそ！<span class="r10">' + cookieUserName + '<\/span>先生<\/span>');
		document.write('<\/form>');
	} else {
		// ログイン用action（プロトコルはhttpsを使用）
		var formAction = "https:\/\/" + location.host + "\/servlet\/JssServlet";
		document.write('<div class="headlogin">');
		document.write('<form action="' + formAction + '" method="post" name="loginForm">');
		document.write('<input type="hidden" name="bean" value="1" \/>');
		document.write('<input type="hidden" name="cmd" value="login" \/>');
		document.write('<input type="hidden" name="view" value="' + viewValue + '" \/>');
		document.write('<input type="hidden" name="viewError" value="' + viewValue + '" \/>');
		document.write('会員番号<input name="user" type="text" class="loginform" value="' + cookieUserId + '" \/>');
		document.write('パスワード<input name="password" type="password" class="loginform" \/>');
		document.write('<input type="image" src="\/images\/btn_login.gif" alt="ログイン" onclick="return doLogin();" \/>');
		document.write('<\/form>');
		document.write('<\/div>');
	}
}

// TOPページ用ログインフォーム描画
function writeTopPageLoginForm() {
	// クッキーの値を取得
	var cookieUserId = getCookie("id");
	var cookieUserName = getCookie("username");
	
	// フォームの遷移先：現在表示中のページ
	var viewValue = getCurrentPathName();

	// クッキーに氏名があればログイン済みと判断する
	if(cookieUserName) {
		// ログアウト用action（プロトコルはhttpを使用）
		var formAction = "http:\/\/" + location.host + "\/servlet\/JssServlet";
		document.write('<p class="mess">会員番号：' + cookieUserId + '<br \/>');
		document.write('ようこそ！<span class="usrName">' + cookieUserName + '</span>先生<\/p>');
		document.write('<form action="' + formAction + '" method="post" name="loginForm">');
		document.write('<input type="hidden" name="bean" value="1" \/>');
		document.write('<input type="hidden" name="cmd" value="logout" \/>');
		document.write('<input type="hidden" name="view" value="' + viewValue + '" \/>');
		document.write('<input type="hidden" name="viewError" value="' + viewValue + '" \/>');
		document.write('<input type="hidden" name="user" value="' + cookieUserId + '" \/>');
		document.write('<p><a href="\/rd\/tjKaiinJyouhouSyoukai.html"><img src="\/images\/btn_change.gif" alt="会員登録情報" width="144" height="29" border="0" \/><\/a><\/p>');
		document.write('<p><a href="\/rd\/tjPasswordHenkou.html"><img src="\/images\/btn_pw.gif" alt="パスワード変更" width="144" height="29" border="0" \/><\/a><\/p>');
		document.write('<p><a href="#"><input type="image" src="\/images\/btn_logout.gif" alt="ログアウト" onclick="return doLogout();" \/><\/a><\/p>');
		document.write('<\/form>');
	} else {
		// ログイン用action（プロトコルはhttpsを使用）
		var formAction = "https:\/\/" + location.host + "\/servlet\/JssServlet";
		document.write('<form action="' + formAction + '" method="post" name="loginForm">');
		document.write('<input type="hidden" name="bean" value="1" \/>');
		document.write('<input type="hidden" name="cmd" value="login" \/>');
		document.write('<input type="hidden" name="view" value="' + viewValue + '" \/>');
		document.write('<input type="hidden" name="viewError" value="' + viewValue + '" \/>');
		document.write('日本外科学会会員番号<input name="user" type="text" class="loginform" value="' + cookieUserId + '" \/>');
		document.write('パスワード<input name="password" type="password" class="loginform" \/>');
		document.write('<p><input type="image" src="\/images\/btn_login.gif" alt="ログイン" onclick="return doLogin();" \/><input type="image" src="\/images\/btn_clear.gif" alt="クリア" onclick="return doClear();" \/><\/p>');
		document.write('<p><a href="\/rd\/tjFirstLogin.html"><img src="\/images\/btn_regist.gif" alt="初回ログイン画面" width="123" height="28" border="0" \/><\/a><\/p>');
		document.write('<hr class="dot">');
		document.write('<p class="r10"><a href="\/rd\/tjPasswordReminder.html">[パスワードを忘れた方はこちら]<\/a><\/p>');
		document.write('<\/form>');
	}
}

// ログイン結果アラート表示
function showLoginResult() {
	var arrayQueryString = new Array();
	if (location.search.length > 1) {
		var m_Array = location.search.substr(1).split("&");
		for (var idx in m_Array) {
			arrayQueryString.push(m_Array[idx].split("="));
		}
	}

	var userName = "";
	for (idx in arrayQueryString) {
		if (arrayQueryString[idx][0] == "user") {
			userName = arrayQueryString[idx][1];
			break;
		}
	}

	//  この後の arrayQueryString[idx][1] == "xxx" の部分の "xxx" の値に関しては
	//  IJssAuthenticator.java を参照のこと。
	for (idx in arrayQueryString) {
		if (arrayQueryString[idx][0] == "result" && arrayQueryString[idx][1] == "-1") {
			alert("ログインに失敗しました。会員番号かパスワードが間違っています。");
			break;
		}
		else if (arrayQueryString[idx][0] == "result" && arrayQueryString[idx][1] == "-2") {
			//alert("ログインに失敗しました。入力した会員番号が存在しません。");
			alert("ログインに失敗しました。会員番号かパスワードが間違っています。");
			break;
		}
		else if (arrayQueryString[idx][0] == "result" && arrayQueryString[idx][1] == "-3") {
			alert("ログインに失敗しました。パスワードが間違っています。");
			break;
		}
		else if (arrayQueryString[idx][0] == "result" && arrayQueryString[idx][1] == "-4") {
			alert("ログインに失敗しました。会員番号かパスワードが間違っています。");
			break;
		}
		else if (arrayQueryString[idx][0] == "result" && arrayQueryString[idx][1] == "10") {
			alert("会員番号 " + userName + " の会員がログアウトしました。");
			break;
		}
	}
}

// 文字列のバイト数を返します。
function isProperByteSize( field, length, label, focus ) {
	var s = field.value;
	var strLen = 0;
	var i;
	for (i = 0; i < s.length && s != ""; i++) {
		var c = s.charCodeAt(i);
		if ( ( c >= 0x0 && c < 0x81 ) ||
			 ( c == 0xf8f0 ) ||
			 ( c >= 0xff61 && c < 0xffa0 ) ||
			 ( c >= 0xf8f1 && c < 0xf8f4 ) ) {
			strLen += 1;
		} else {
			strLen += 2;
		}
	}
	if (strLen > length) {
		var gap = strLen - length;
		var doubleByteLength = Math.floor(length / 2);	// 小数点以下切り捨て
		alert( label + "は、全角" + doubleByteLength + "文字、半角" + length + "文字以内で入力してください。\n現在、半角で" + gap + "文字分超えています。" );
		if( focus != false ){
			field.focus();
		}
		return false;
	}
	return true;
}

// 空文字列を受け付けるかどうか判定します。
function acceptEmptyString( field, required, label, focus ) {
	var s = field.value;
	if ( s.length == 0 ) {
		if ( required ) {
			alert( "" + label + "が入力されていません。入力してください。");
			if( focus != false ){
				field.focus();
			}
			return false;
		} else {
			return true;
		}
	} else {
		return true;
	}
}

// 半角文字だけかどうかをチェックします。
function isSingleByte( field, required, length, label, focus ) {

	var s = field.value;

	// 空文字列チェック
	if ( !acceptEmptyString( field, required, label, focus ) ) {
		return false;
	} else if ( s == "" ) {
		return true;
	}

	// バイト数チェック
	if ( !isProperByteSize( field, length, label, focus ) ) {
		return false;
	}

	// 文字種チェック
	var i;
	for ( i = 0; i < s.length && s != ""; i++ ) {
		var c = s.charCodeAt( i );
		if ( !( ( c >= 0x0 && c < 0x81 ) ||
				( c == 0xf8f0 ) ||
				( c >= 0xff61 && c < 0xffa0 ) ||
				( c >= 0xf8f1 && c < 0xf8f4 ) ) ) {
			alert( "文字 '" + s.charAt( i ) + "' は" + label + "に入力できません。半角文字を入力してください。" );
			if( focus != false ){
				field.focus();
			}
			return false;
		}
	}
	return true;
}

// 半角英数字のみの入力チェックに使用します。
function isAlphanumeric( field, required, length, label, focus ) {
	
	var s = field.value;

	// 空文字列チェック
	if ( !acceptEmptyString( field, required, label, focus ) ) {
		return false;
	} else if ( s == "" ) {
		return true;
	}

	// バイト数チェック
	if ( !isProperByteSize( field, length, label, focus ) ) {
		return false;
	}

	// 文字種チェック
	var alphaNumericChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	var i;
	for ( i = 0; i < s.length; i++ ) {
		if ( alphaNumericChars.indexOf( s.charAt( i ), 0 ) == -1 ) {
			alert( "文字 '" + s.charAt( i ) + "' は" + label + "に入力できません。半角英数字を入力してください。" );
			if( focus != false ){
				field.focus();
			}
			return false;
		}
	}
	
	return true;
}

// htmlのtagが含まれているかどうかチェックします。
// <>が使用されていなければtrueを返します。
// 使用されていればfalseを返します。
function isHtmlTagElementLess( field, required, length, label, focus ) {

	var s = field.value;

	// 空文字列チェック
	if ( !acceptEmptyString( field, required, label, focus ) ) {
		return false;
	} else if ( s == "" ) {
		return true;
	}

	// バイト数チェック
	if ( !isProperByteSize( field, length, label, focus ) ) {
		return false;
	}

	// 文字種チェック
	var htmlTagElement = "<>";
	var i;
	for ( i = 0; i < s.length; i++ ) {
		if ( htmlTagElement.indexOf( s.charAt( i ), 0 ) != -1 ) {
			if( label == "" ){
				alert( "文字 ｢<｣、｢>｣ は入力できません。" );
			}else{
				alert( "文字 ｢<｣、｢>｣ は" + label + "に入力できません。" );
			}
			if( focus != false ){
				field.focus();
			}
			return false;
		}
	}
	return true;
}

function decodeJavaURL(orgString){
	var retString = "";

	for (var i = 0; i < orgString.length; i++) {
		var orgChar = orgString.charAt(i);

		if (orgChar == "+"){
			retString += " ";
		} else {
			if (orgChar != "%"){
				retString += orgChar;
			} else{
				var unicode = 0;
				var escapeFlag = 1;
				while (true) {
					var hexString = "";
					for (var j = 0; j < 2; j++ ) {
						var hexChar = orgString.charAt(++i);
						if (((hexChar >= "0") && (hexChar <= "9")) || ((hexChar >= "a") && (hexChar <= "f"))  || ((hexChar >= "A") && (hexChar <= "F"))) {
							hexString += hexChar;
						} else {
							--i;
							break;
						}
					}

					var num = parseInt(hexString, 16);
					if (num <= 0x7f){
						unicode = num; escapeFlag = 1;
					}
					if ((num >= 0xc0) && (num <= 0xdf)){
						unicode = num & 0x1f; escapeFlag = 2;
					}
					if ((num >= 0xe0) && (num <= 0xef)){
						unicode = num & 0x0f; escapeFlag = 3;
					}
					if ((num >= 0xf0) && (num <= 0xf7)){
						unicode = num & 0x07; escapeFlag = 4;
					}
					if ((num >= 0x80) && (num <= 0xbf)){
						unicode = (unicode << 6) + (num & 0x3f); --escapeFlag;
					}
					if (escapeFlag <= 1){
						break;
					}
					if (orgString.charAt(i + 1) == "%"){
						i++;
					} else {
						break;
					}
				}
				retString += String.fromCharCode(unicode);
			}
		}
	}
	return retString;
}
