//グローバルの名前空間用のオブジェクトを用意する
var LOGIN = {};

// var requirePasswordChange;
LOGIN.userinfo_sid;
LOGIN.userInfo_userName;
LOGIN.optionList = [];

LOGIN.force_pw_change_on_login;
LOGIN.force_pw_change_periodically;
LOGIN.login_error_flag = false;
LOGIN.login_errorMessage = "";

LOGIN.timeWaitSplashScreen = 2000;// wait splash screen 2 second

// Load login Info
LOGIN.loadLoginInfo = function() {
	$('#chkRemember').attr('checked', 'checked');
	if (ClientData.userInfo_accountPath() != null) {
		$('#txtAccPath').val(ClientData.userInfo_accountPath());
	}

	if (ClientData.userInfo_loginId() != null) {
		$('#txtAccId').val(ClientData.userInfo_loginId());
	}
};

// Initial Screen
LOGIN.initialScreen = function() {
	if (ClientData.userInfo_rememberLogin()) {
		LOGIN.loadLoginInfo();
	}
};

// check Save Login Info
LOGIN.saveLoginInfo = function() {

	var lang = I18N.getCurrentLanguage();
	// load language
	I18N.changeLanguage(lang);

	// Set flag コンテンツデータチェックフラグ = true to sync local with server
	// ClientData.common_contentDataChkFlg(true);

	var accountPath, loginId, password;
	var chkRemember = $('#chkRemember').attr('checked');
	accountPath = $('#txtAccPath').val();
	loginId = $('#txtAccId').val();
	password = $('#txtPassword').val();

	var date = new Date();
	ClientData.userInfo_accountPath(accountPath);
	ClientData.userInfo_loginId(loginId);
	ClientData.userInfo_accountPath_session(accountPath);
	ClientData.userInfo_loginId_session(loginId);
	ClientData.userInfo_userName(LOGIN.userInfo_userName);
	if (chkRemember == 'checked') {
		ClientData.userInfo_rememberLogin(true);
	} else {
		ClientData.userInfo_rememberLogin(false);
	}

	ClientData.userInfo_lastLoginTime(date.jpDateTimeString());
	ClientData.userInfo_sid_local(LOGIN.userinfo_sid);
	// バックアップにも保持
	ClientData.userInfo_sid_local_bak(LOGIN.userinfo_sid);

	LOGIN.saveServiceUserOption();
	// ページジャンプ設定をクリア
	ClientData.JumpQueue([]);
	ClientData.IsJumpBack(false);

};

// Check validation
LOGIN.checkValidation = function() {

	// 暗号化モードならチェック無し
	// if (ClientData.serviceOpt_encryption() == 'Y') {
	// 	return true;
	// }

	var accountPath = $('#txtAccPath').val();
	var loginId = $('#txtAccId').val();
	var password = $('#txtPassword').val();
	var msgError = $('#main-error-message');
	if (!ValidationUtil.CheckRequiredForText(accountPath)) {
		LOGIN.login_errorMessage = "";
		msgError.html(I18N.i18nText('msgLoginEmpty'));
		msgError.attr('lang', 'msgLoginEmpty');
		msgError.show();
		return false;
	} else if (!ValidationUtil.CheckRequiredForText(loginId)) {
		LOGIN.login_errorMessage = "";
		msgError.html(I18N.i18nText('msgLoginEmpty'));
		msgError.attr('lang', 'msgLoginEmpty');
		msgError.show();
		return false;
	} else if (!ValidationUtil.CheckRequiredForText(password)) {
		LOGIN.login_errorMessage = "";
		msgError.html(I18N.i18nText('msgLoginEmpty'));
		msgError.attr('lang', 'msgLoginEmpty');
		msgError.show();
		return false;
	} else {
		return true;
	}
};

// Check Dialog validation
LOGIN.checkDialogValidation = function() {
	var currentPass = $('#txtCurrentPass').val();
	var newPass = $('#txtNewPass').val();
	var confirmPass = $('#txtConfirmNew').val();
	var msgError = $('#dialog-error-message');

	if (!ValidationUtil.CheckRequiredForText(currentPass)) {
		LOGIN.login_errorMessage = "";
		msgError.html(I18N.i18nText('msgPwdEmpty'));
		msgError.attr('lang', 'msgPwdEmpty');
		msgError.show();
		return false;
	} else if (!ValidationUtil.CheckRequiredForText(newPass)) {
		LOGIN.login_errorMessage = "";
		msgError.html(I18N.i18nText('msgPwdEmpty'));
		msgError.attr('lang', 'msgPwdEmpty');
		msgError.show();
		return false;
	} else {
		if (newPass != confirmPass) {
			LOGIN.login_errorMessage = "";
			msgError.html(I18N.i18nText('msgPwdNotMatch'));
			msgError.attr('lang', 'msgPwdNotMatch');
			msgError.show();
			return false;
		} else {
			return true;
		}
	}
};

// Login Process
LOGIN.processLogin = function() {
	var accountPath = "";
	var loginId = "";
	var password = "";

	loginId = $('#txtAccId').val();

	password = $('#txtPassword').val();

	accountPath = $('#txtAccPath').val();
	var requireChangePassword = 0;
	var skipPwdDate;

	var params = {
		previousSid : '',
		loginId : loginId,
		password : password,
		urlpath : accountPath
	};

	// 引数パラメータがあれば取得
//	var paramContentID = COMMON.getUrlParam('cid', '');

	// Set sid for login, this will be checked authoring 2 sessions
	if (ClientData.userInfo_sid_local()) {
		params.previousSid = ClientData.userInfo_sid_local();
	}

	// Get url to login
	var apiLoginUrl = ClientData.conf_apiLoginUrl(); // sysSettings.apiLoginUrl;

	COMMON.callCmsApi(apiLoginUrl, null, 'webClientLogin', 'GET', params, true, function(data) {
		LOGIN.userinfo_sid = data.sid;
		LOGIN.userInfo_userName = data.userName;
		LOGIN.optionList = data.serviceOptionList;

		LOGIN.getServiceOptionList();

		if (data.result == 'success') {
			// Save retrieved info
			LOGIN.saveLoginInfo();
			// set number new push message to 0
			ClientData.pushInfo_newMsgNumber(0);

			$('#main-error-message').css('display', 'none');

			// if (ClientData.serviceOpt_encryption() == 'Y') {
			// 	data.requirePasswordChange = 0;
			// }

			console.log("data.requirePasswordChange:" + data.requirePasswordChange);
			console.log("ClientData.serviceOpt_abook_check:" + ClientData.serviceOpt_abook_check());


			if (data.requirePasswordChange == 0) {
				ClientData.userInfo_sid(ClientData.userInfo_sid_local());

				// ホームへ移動 
				COMMON.avwScreenMove("index.html");

			} else if (data.requirePasswordChange == 1) {

				if (LOGIN.force_pw_change_on_login == 2) { // force to change
															// password
					LOGIN.OpenChangePasswordDialog();
					$(".ui-dialog-titlebar").hide();
					$('#btnSkip').hide();
					$("#txtPwdRemind").css('visibility', 'hidden');
				} else if (LOGIN.force_pw_change_on_login == 1) { // recommend
																	// to change
																	// password

					// Check 30 days
					skipPwdDate = ClientData.userInfo_pwdSkipDt();

					if (skipPwdDate == null || skipPwdDate == 'undefined') {
						LOGIN.OpenChangePasswordDialog();
						$('#btnSkip').show();
						$(".ui-dialog-titlebar").hide();
					} else {
						var date = new Date();
						var skpPwdDt = new Date(skipPwdDate);
						var numDay = date.subtractByDays(skpPwdDt);
						if (numDay <= 30) {

							ClientData.userInfo_sid(ClientData.userInfo_sid_local());
							// ホームへ移動 
							COMMON.avwScreenMove("index.html");
						} else if (numDay > 30) {
							LOGIN.OpenChangePasswordDialog();
							$('#btnSkip').show();
							$(".ui-dialog-titlebar").hide();
						}
					}
				} else { // no need to change password
					ClientData.userInfo_sid(ClientData.userInfo_sid_local());

					// ホームへ移動 
					COMMON.avwScreenMove("index.html");
				}
			} else if (data.requirePasswordChange == 2) {

				if (LOGIN.force_pw_change_periodically == 1) { // recommend to
																// change
																// password
					$('#btnSkip').show();
					skipPwdDate = ClientData.userInfo_pwdSkipDt();

					if (skipPwdDate == null || skipPwdDate == 'undefined') {
						LOGIN.OpenChangePasswordDialog();
						$(".ui-dialog-titlebar").hide();
					} else {

						var date = new Date();
						var skpPwdDt = new Date(skipPwdDate);
						var numDay = date.subtractByDays(skpPwdDt);

						if (numDay <= 30) {
							ClientData.userInfo_sid(ClientData.userInfo_sid_local());

							// ホームへ移動 
							COMMON.avwScreenMove("index.html");

						} else if (numDay > 30) {
							LOGIN.OpenChangePasswordDialog();
							$(".ui-dialog-titlebar").hide();
						}
					}
				} else if (LOGIN.force_pw_change_periodically == 2) { // Force
																		// to
																		// change
																		// password
					LOGIN.OpenChangePasswordDialog();
					$('#btnSkip').hide();
					$(".ui-dialog-titlebar").hide();
					$("#txtPwdRemind").css('visibility', 'hidden');
				} else { // No need to change password
					ClientData.userInfo_sid(ClientData.userInfo_sid_local());
					// ホームへ移動 
					COMMON.avwScreenMove("index.html");
				}
			}
		} else {
			LOGIN.login_errorMessage = data.errorMessage;
			$('#main-error-message').html(COMMON.format(I18N.i18nText('msgLoginErrWrong'), data.errorMessage).toString());
			$('#main-error-message').show();

		}

	}, function(xhr, statusText, errorThrown) {
		LOGIN.login_error_flag = true;
		if (xhr.responseText && xhr.status != 0) {
			LOGIN.login_errorMessage = JSON.parse(xhr.responseText).errorMessage;

			$('#main-error-message').html(COMMON.format(I18N.i18nText('msgLoginErrWrong'), JSON.parse(xhr.responseText).errorMessage).toString());
		} else {
			$('#main-error-message').html(COMMON.format(I18N.i18nText('msgLoginErrWrong'), 'E001'));
		}
		$('#main-error-message').show();
	});
};

// Change Password Process
LOGIN.changePasswordProcess = function() {
	var accountPath = $('#txtAccPath').val();
	var sid = ClientData.userInfo_sid_local();
	var loginId = $('#txtAccId').val();
	var password = $('#txtCurrentPass').val();
	var confirmPass = $('#txtConfirmNew').val();

	var params = {
		sid : sid,
		loginId : loginId,
		password : password,
		newPassword : confirmPass,
		appId : 4
	};

	AVWEB.avwCmsApiSync(accountPath, 'passwordChange', 'GET', params, function(data) {
		var result = data.result;
		if (result == 'success') {
			$('#dialog-error-message').css('display', 'none');
			LOGIN.CloseChangePasswordDialog();
			ClientData.userInfo_sid(ClientData.userInfo_sid_local());

			if (ClientData.serviceOpt_abook_check() == 'Y') {
				// ホームへ移動 
				COMMON.avwScreenMove("index.html");
			} else {
				$('#main-error-message').html(COMMON.format(I18N.i18nText('msgLoginErrWrong'), 'E001'));
				$('#main-error-message').show();
			}

		} else {
			$('#dialog-error-message').html(I18N.i18nText('msgPwdOldWrong'));
			$('#dialog-error-message').show();
		}
	}, function(xhr, b, c) {
		if (xhr.responseText && xhr.status != 0) {
			$('#dialog-error-message').html(JSON.parse(xhr.responseText).errorMessage);
			$('#dialog-error-message').show();
		} else {
			// Show systemerror
			COMMON.showSystemError();
		}
	});
};

// Change Language Japanese
LOGIN.changeLanguageJa = function() {
	I18N.changeLanguage(CONSTANT.LANG.JAPAN);
	document.title = I18N.i18nText('dspLogin') + ' | ' + I18N.i18nText('sysAppTitle');
	// ClientData.userInfo_language(COMMON.Consts.ConstLanguage_Ja);
	if (LOGIN.login_errorMessage != "") {
		$('#main-error-message').html(COMMON.format(I18N.i18nText('msgLoginErrWrong'), LOGIN.login_errorMessage).toString());
	}
};

// Change Language Korean
LOGIN.changeLanguageKo = function() {
	I18N.changeLanguage(CONSTANT.LANG.KOREA);
	document.title = I18N.i18nText('dspLogin') + ' | ' + I18N.i18nText('sysAppTitle');
	// ClientData.userInfo_language(COMMON.Consts.ConstLanguage_Ko);
	if (LOGIN.login_errorMessage != "") {
		$('#main-error-message').html(COMMON.format(I18N.i18nText('msgLoginErrWrong'), LOGIN.login_errorMessage).toString());
	}
};

// Change Language English
LOGIN.changeLanguageEn = function() {
	I18N.changeLanguage(CONSTANT.LANG.ENGLISH);
	document.title = I18N.i18nText('dspLogin') + ' | ' + I18N.i18nText('sysAppTitle');
	// ClientData.userInfo_language(COMMON.Consts.ConstLanguage_En);
	if (LOGIN.login_errorMessage != "") {
		$('#main-error-message').html(COMMON.format(I18N.i18nText('msgLoginErrWrong'), LOGIN.login_errorMessage).toString());
	}
};

// Login click function
LOGIN.loginFunction = function() {
	if (LOGIN.checkValidation()) {
		LOGIN.processLogin();
	}
};

// Change Password function
LOGIN.changePassFunction = function() {
	if (LOGIN.checkDialogValidation()) {
		LOGIN.changePasswordProcess();
	}
};

// Skip Password function
LOGIN.skipPassFunction = function() {
	var date = new Date();

	ClientData.userInfo_pwdSkipDt(date);
	ClientData.userInfo_sid(ClientData.userInfo_sid_local());

	if (ClientData.serviceOpt_abook_check() == 'Y') {
		// ホームへ移動 
		COMMON.avwScreenMove("index.html");
	} else {
		$('#main-error-message').html(COMMON.format(I18N.i18nText('msgLoginErrWrong'), 'E001'));
		$('#main-error-message').show();
	}

};

// Open Change Password Dialog
LOGIN.OpenChangePasswordDialog = function() {
	// Clear all input values
	$("#main-password-change").show();
	$("#main-password-change").center();
	COMMON.lockLayout();
};

// Close Chnage Password Dialog
LOGIN.CloseChangePasswordDialog = function() {
	$("#main-password-change").hide();
};

// Save Service Option
LOGIN.saveServiceUserOption = function() {

	$.each(LOGIN.optionList, function(i, option) {

		if (option.serviceOptionId == 22) {
			ClientData.serviceOpt_force_pw_change_periodically(option.value);
		} else if (option.serviceOptionId == 21) {
			ClientData.serviceOpt_force_pw_change_on_login(option.value);
		} else if (option.serviceOptionId == 49) {
			ClientData.serviceOpt_usable_push_message(option.value);
		} else if (option.serviceOptionId == 161) {
			ClientData.serviceOpt_abook_check(option.value);
		}
	});
};

// Get Service Option
LOGIN.getServiceOptionList = function() {

	$.each(LOGIN.optionList, function(i, option) {

		if (option.serviceOptionId == 22) {
			LOGIN.force_pw_change_periodically = option.value;
		} else if (option.serviceOptionId == 21) {
			LOGIN.force_pw_change_on_login = option.value;
		}

	});
};

LOGIN.loginWhenClickEnter = function(e) {
	var code = (e.keyCode ? e.keyCode : e.which);
	if (code == 13) { // Enter keycode
		$('#btnLogin').click();
	}
};

// init login for normal user
LOGIN.initLoginNormalUser = function() {

	document.title = I18N.i18nText('dspLogin') + ' | ' + I18N.i18nText('sysAppTitle');

	// Initial Screen
	LOGIN.initialScreen();
	// Change language japanese
	$('#language-ja').click(LOGIN.changeLanguageJa);
	// Change language korean
	$('#language-ko').click(LOGIN.changeLanguageKo);
	// Change laguage english
	$('#language-en').click(LOGIN.changeLanguageEn);
	// Button login click event
	$('#btnLogin').click(LOGIN.loginFunction);
	// Button Change click event
	$('#btnChange').click(LOGIN.changePassFunction);
	// Button Skip click event
	$('#btnSkip').click(LOGIN.skipPassFunction);

	$('#txtPassword').keydown(LOGIN.loginWhenClickEnter);
};


/* display alert screen */
LOGIN.showAlertScreen = function(errMes, scrMove) {

	// アラートメッセージの表示
	if (errMes == undefined || errMes == "") {
		errMes = "message."; // I18N.i18nText('msgPageImgErr');
	}

	COMMON.lockLayout();
	/* show error messages */
	$().toastmessage({
		position : 'middle-center'
	});
	$().toastmessage('showToast', {
		type : 'error',
		sticky : true,
		text : errMes,
		close : function() {
		}
	});
	$('.toast-type-error').css('height', '100px');
	$('.toast-type-error > p').css('padding-top', '35px');
	$('.toast-item-close').live('click', function() {
		COMMON.unlockLayout();
		if (scrMove) {
			COMMON.avwScreenMove(scrMove);
		}
	});
};

// $(document).ready(function (e) {
LOGIN.ready = function() {

	// セッションストレージクリア
	SessionStorageUtils.clear();
	COMMON.userSessionObj = null;
	// create new session
	COMMON.createUserSession();
	I18N.initi18n();

	var sysSettings = COMMON.sysSetting(); // get info in conf.json

	// getitsサーバー設定確認
	if (sysSettings.apiUrl == "") {

		// 引数パラメータを取得
		var siteUrl = COMMON.getUrlParam('siteUrl', '');
		var urlPath = COMMON.getUrlParam('urlPath', '');
		var storeUrl = COMMON.getUrlParam('storeUrl', '');
		if (siteUrl != "" && urlPath != "") {

			// ClientData.siteUrl(siteUrl);
			// api接続先設定
			ClientData.conf_apiUrl(siteUrl + "{0}/abvapi");
			ClientData.conf_apiLoginUrl(siteUrl + "nuabvapi");
			ClientData.conf_apiResourceDlUrl(siteUrl + "{0}/dl");
			// アカウント関連
			ClientData.userInfo_accountPath(urlPath);
			ClientData.userInfo_accountPath_session(urlPath);
			ClientData.userInfo_loginId("");
			ClientData.userInfo_loginId_session("");

		}

	} else {
		// confのパラメータセット
		ClientData.conf_apiUrl(sysSettings.apiUrl);
		ClientData.conf_apiLoginUrl(sysSettings.apiLoginUrl);
		ClientData.conf_apiResourceDlUrl(sysSettings.apiResourceDlUrl);
	}

	// 引数でアカウントパスを受け取ったらセットする

	$('#normalUser').show();
	$('#formlogin').hide();
	$('#logologin').animate({
		"margin-top" : 0
	}, LOGIN.timeWaitSplashScreen, function() {
		$('#formlogin').show();
		$('#menu-language').animate({
			opacity : 1
		}, LOGIN.timeWaitSplashScreen);
		$('#formlogin').animate({
			opacity : 1
		}, LOGIN.timeWaitSplashScreen);
		$('.cnt_footer').animate({
			opacity : 1
		}, LOGIN.timeWaitSplashScreen);
	});
	LOGIN.initLoginNormalUser();
};
// });

