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

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

LOGIN.force_pw_change_on_login;
LOGIN.force_pw_change_periodically;
LOGIN.user_data_backup;
LOGIN.marking;
LOGIN.login_error_flag = false;
LOGIN.force_login_periodically;
LOGIN.login_errorMessage = "";
LOGIN.avwUserEnvObj = new UserEnvironment();

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();
	} else {
		//OpenUrlでコンテンツ開く場合
		if( paramContentID != '' ){
			if (ClientData.userInfo_sid_local_bak()) {
				params.previousSid = ClientData.userInfo_sid_local_bak();
			}
		}
	}

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

    AVWEB.avwCmsApiWithUrl(apiLoginUrl, null, 'webClientLogin', 'GET', params, 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;
            }

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

                //OpenUrlでコンテンツ開く場合
                if( paramContentID != '' ){
                    LOGIN.showContentViewByOpenUrl(paramContentID);
                } else {
                    //ホームへ移動
                	AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);
                }

            }
            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());
                            //OpenUrlでコンテンツ開く場合
                            if( paramContentID != '' ){
                                LOGIN.showContentViewByOpenUrl(paramContentID);
                            } else {
                                //ホームへ移動
                            	AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);
                            }
                        }
                        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());

                    //OpenUrlでコンテンツ開く場合
                    if( paramContentID != '' ){
                        LOGIN.showContentViewByOpenUrl(paramContentID);
                    } else {
                        //ホームへ移動
                    	AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);
                    }

                }
            }
            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());

                            //OpenUrlでコンテンツ開く場合
                            if( paramContentID != '' ){
                                LOGIN.showContentViewByOpenUrl(paramContentID);
                            } else {
                                //ホームへ移動
                            	AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);
                            }

                        }
                        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());
                    //OpenUrlでコンテンツ開く場合
                    if( paramContentID != '' ){
                        LOGIN.showContentViewByOpenUrl(paramContentID);
                    } else {
                        //ホームへ移動
                    	AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);
                    }

                }
            }
        }
        else {
            LOGIN.login_errorMessage = data.errorMessage;
            $('#main-error-message').html(AVWEB.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(AVWEB.format(I18N.i18nText('msgLoginErrWrong'), JSON.parse(xhr.responseText).errorMessage).toString());
        } else {
            $('#main-error-message').html(AVWEB.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());
            AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);
        }
        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
        	AVWEB.showSystemError();
        }
    });
};

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

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

//Change Language English
LOGIN.changeLanguageEn = function(){
	I18N.changeLanguage(COMMON.Consts.ConstLanguage_En);
    document.title = I18N.i18nText('dspLogin') + ' | ' + I18N.i18nText('sysAppTitle');
    //ClientData.userInfo_language(COMMON.Consts.ConstLanguage_En);
    if (LOGIN.login_errorMessage != ""){
    	$('#main-error-message').html(AVWEB.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());
	AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);

};

//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").dialog('close');
};

//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 == 33) {
            ClientData.serviceOpt_marking(option.value);
        }
        else if (option.serviceOptionId == 28) {
            ClientData.serviceOpt_user_data_backup(option.value);
        }
        else if (option.serviceOptionId == 42) {
            ClientData.serviceOpt_copy_text(option.value);
        }
        else if (option.serviceOptionId == 60) {
            ClientData.serviceOpt_web_screen_lock(option.value);
        }
        else if (option.serviceOptionId == 61) {
            ClientData.serviceOpt_web_screen_lock_wait(option.value);
        }
        else if( option.serviceOptionId == 70) {
            ClientData.serviceOpt_catalog_edition(option.value);
        }
        else if( option.serviceOptionId == 77) {
            ClientData.serviceOpt_hibiyakadan_catalog(option.value);
        }
        else if( option.serviceOptionId == 71) {
            ClientData.serviceOpt_usable_readinglog_gps(option.value);
        }
        else if( option.serviceOptionId == 72) {
            ClientData.serviceOpt_usable_readinglog_object(option.value);
        }
        else if( option.serviceOptionId == 83) {
            ClientData.serviceOpt_reader_usable_readinglog_gps(option.value);
        }
        else if( option.serviceOptionId == 84) {
            ClientData.serviceOpt_reader_readinglog_object(option.value);
        }
        else if( option.serviceOptionId == 87) {
            ClientData.serviceOpt_daihatsu(option.value);
        }
        else if( option.serviceOptionId == 78) {
            ClientData.serviceOpt_content_share(option.value);
        }
        else if( option.serviceOptionId == 12) {
            ClientData.serviceOpt_apns(option.value);
        }
        else if( option.serviceOptionId == 49) {
            ClientData.serviceOpt_usable_push_message(option.value);
        }
        else if( option.serviceOptionId == 126) {
            ClientData.serviceOpt_encryption(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;
		}
		else if(option.serviceOptionId == 23){
			LOGIN.force_login_periodically = option.value;
		}
		else if(option.serviceOptionId == 33){
			LOGIN.marking = option.value;
		}
		else if(option.serviceOptionId == 28){
			LOGIN.user_data_backup = 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);
};

// init login for anonymous user
LOGIN.initLoginAnonymousUser = function() {

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

	var sysSettings = AVWEB.avwSysSetting(); // get info in conf.json
	var loginId = sysSettings.anonymousLoginId;
	var urlPath = sysSettings.anonymousLoginPath;

	if( loginId == "" ){
		loginId = "nologin";
	}

	if( urlPath == "" ){
		//URLからパース
		urlPath = LOGIN.getUrlPath();
		if( urlPath == null ){
			urlPath = "dmy";
		}
	}

    var params = {
        previousSid: null,
        loginId: loginId,
        urlpath: urlPath
    };

    AVWEB.avwCmsApiWithUrl(ClientData.conf_apiLoginUrl(), null, 'webClientAnonymousLogin', 'post', params, function (data) {

        if (data.result == 'success') {

            //clear session of old anonymous user
            //SessionStorageUtils.clear();
            //警告表示を組み込んだら I18N.i18nText()の値が未定義になるので言語リソース再読み込み
            I18N.initi18n();

            // set info user anonymous login
            ClientData.userInfo_accountPath(urlPath);
            ClientData.userInfo_accountPath_session(urlPath);

            ClientData.userInfo_loginId(loginId);
            ClientData.userInfo_loginId_session(loginId);

            ClientData.userInfo_userName(data.userName);

            ClientData.userInfo_sid(data.sid);
            ClientData.userInfo_sid_local(data.sid);

            // clear all local storage data of old anonymous
            LocalStorageUtils.clear();

            // set number new push message to 0
            ClientData.pushInfo_newMsgNumber(0);

            // get service option list
            LOGIN.optionList = data.serviceOptionList;

            // save service user option
            LOGIN.saveServiceUserOption();

            // hide splash screen then move to home page
            $('#anonymous').fadeOut('slow', 'swing', function () {
				//カタログエディション対応判定
				if( ClientData.serviceOpt_catalog_edition() == 'Y'){

					//引数パラメータがあれば取得
					var paramContentID = COMMON.getUrlParam('cid', '');
					//カタログ対応
					if( paramContentID != '' ){
						//OpenUrlでコンテンツ開く
						LOGIN.showContentViewByOpenUrl(paramContentID);
					} else {
						//ホームへ移動
						AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);
					}
				} else {
					//ホームへ移動
					AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);
				}

            });
        }
        else {
            if (data.errorMessage != null && data.errorMessage != undefined) {
                LOGIN.showMessageErrorLoginAnonymous(AVWEB.format(I18N.i18nText('msgAnonymousLoginErr'), data.errorMessage).toString());
            }
            else {
                LOGIN.showMessageErrorLoginAnonymous(I18N.i18nText('msgAnonymousLoginErr2'));
            }
        }
    }, function (xhr, statusText, errorThrown) {
        if (xhr.responseText && xhr.status != 0) {
            var errorMessage = JSON.parse(xhr.responseText).errorMessage;
            if (errorMessage) {
                LOGIN.showMessageErrorLoginAnonymous(AVWEB.format(I18N.i18nText('msgAnonymousLoginErr'), errorMessage).toString());
            }
            else {
                LOGIN.showMessageErrorLoginAnonymous(I18N.i18nText('msgAnonymousLoginErr2'));
            }
        } else {
            LOGIN.showMessageErrorLoginAnonymous(I18N.i18nText('msgAnonymousLoginErr2'));
        }
    });
};

// init login for getits user
LOGIN.initLoginGetitsUser = function() {

	//console.log("LOGIN.initLoginGetitsUser");

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

    var params = {
        urlpath: ClientData.userInfo_accountPath()
    };

    I18N.initi18n();

    AVWEB.avwCmsApiWithUrl(ClientData.conf_apiLoginUrl(), ClientData.userInfo_accountPath(), 'webClientGetitsLogin', 'post', params, function (data) {

        if (data.result == 'success') {

            //clear session of old anonymous user
            //SessionStorageUtils.clear();
            //警告表示を組み込んだら I18N.i18nText()の値が未定義になるので言語リソース再読み込み
            //I18N.initi18n();

            ClientData.userInfo_userName(data.userName);

            ClientData.userInfo_sid(data.sid);
            ClientData.userInfo_sid_local(data.sid);

            // clear all local storage data of old anonymous
            LocalStorageUtils.clear();

            // set number new push message to 0
            ClientData.pushInfo_newMsgNumber(0);

            // get service option list
            LOGIN.optionList = data.serviceOptionList;

            // save service user option
            LOGIN.saveServiceUserOption();
            // hide splash screen then move to home page
            $('#anonymous').fadeOut('slow', 'swing', function () {

				//引数パラメータがあれば取得
				var paramContentID = COMMON.getUrlParam('cid', '');
				//カタログ対応
				if( paramContentID != '' ){
					//OpenUrlでコンテンツ開く
					LOGIN.showContentViewByOpenUrl(paramContentID);
				} else {
					//ホームへ移動
					//AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);
					AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Login);
				}

            });
        }
        else {
            if (data.errorMessage != null && data.errorMessage != undefined) {
                LOGIN.showMessageErrorLoginAnonymous(AVWEB.format(I18N.i18nText('msgAnonymousLoginErr'), data.errorMessage).toString());
            }
            else {
                LOGIN.showMessageErrorLoginAnonymous(I18N.i18nText('msgAnonymousLoginErr2'));
            }
        }
    }, function (xhr, statusText, errorThrown) {
        if (xhr.responseText && xhr.status != 0) {
            var errorMessage = JSON.parse(xhr.responseText).errorMessage;
            if (errorMessage) {
                LOGIN.showMessageErrorLoginAnonymous(AVWEB.format(I18N.i18nText('msgAnonymousLoginErr'), errorMessage).toString());
            }
            else {
                LOGIN.showMessageErrorLoginAnonymous(I18N.i18nText('msgAnonymousLoginErr2'));
            }
        } else {
            LOGIN.showMessageErrorLoginAnonymous(I18N.i18nText('msgAnonymousLoginErr2'));
        }
    });
};

LOGIN.showMessageErrorLoginAnonymous = function(errorMessage) {
    $().toastmessage({ position: 'middle-center' });
    $().toastmessage('showToast', {
        type: 'error',
        sticky: true,
        text: errorMessage
    });
    $('.toast-position-middle-center').css('width', '400px');
};

// OpenUriで開いた場合の直接コンテンツ表示
LOGIN.showContentViewByOpenUrl = function(strContentId) {

	var contentType = '';
	var result = [];
	var params = {
		sid: ClientData.userInfo_sid(),
		getType: '1',
		contentId: strContentId
	};
	AVWEB.avwCmsApiSync(ClientData.userInfo_accountPath(), "webGetContent", 'GET', params,
		function (data) {

			//コンテンツIDセット
			ClientData.contentInfo_contentId(strContentId);
			//コンテツタイプ判定
			contentType = data.contentData.contentType;
			if(contentType == COMMON.ContentTypeKeys.Type_Others){
				//Download content
				HEADER.downloadResourceById(strContentId);
			} else {
				//Go to Conten view page

				//アラート表示組み込めるか
				LIMIT_ACCESS_CONTENT.messageLevel[data.contentData.contentId] = { alertMessageLevel:data.contentData.alertMessageLevel, alertMessage:data.contentData.alertMessage};

				// check limit of content
				LIMIT_ACCESS_CONTENT.checkLimitContent(
					data.contentData.contentId,
					function()
					{
						LOGIN.alertMessageOkFunction_callback();
					},
					function()
					{
						LOGIN.alertMessageCancelFunction_callback();
					}
				);
			}

		},
		function (xmlHttpRequest, txtStatus, errorThrown) {
			//見つからないかエラーなのでホームに移動
			if( ClientData.isGetitsMode() == true ){
				AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Login);
			} else {
				//アラートメッセージ表示
				LOGIN.showAlertScreen(I18N.i18nText('msgContentNotExist'),"abvw/" + COMMON.ScreenIds.Home);
			}
		}
	);

};

//警告表示時のOK処理
LOGIN.alertMessageOkFunction_callback = function(){
	if (LOGIN.avwUserEnvObj.isMobile() && ClientData.isGetitsMode() ) {
		AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.ContentViewGetits);
	} else {
		AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.ContentView);
	}
};
//警告表示時のキャンセル処理
LOGIN.alertMessageCancelFunction_callback = function(){
	if( ClientData.isGetitsMode() == true ){
		AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Login);
	} else {
		AVWEB.avwScreenMove("abvw/" + COMMON.ScreenIds.Home);
	}
};

//Get urlPath String
LOGIN.getUrlPath = function(){
	//URL文字列から事業者ID部分を抽出
	var regex = new RegExp( "/webad/([^&#]*)/" );
	var results = regex.exec( window.location.href );
	if( results == null ){
		return "";
	}
	else{
		return results[1];
	}
};


/* 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 ){
            	AVWEB.avwScreenMove(scrMove);
            }
        }
    );
};



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

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

	var sysSettings = AVWEB.avwSysSetting(); // get info in conf.json

	//モード初期化
	ClientData.isGetitsMode(false);
	ClientData.isStreamingMode(false);

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

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

			//getitsモード有効
			ClientData.isGetitsMode(true);
			//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("");
			//ストア遷移用のURL
			ClientData.storeUrl(storeUrl);

		}

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

	if( ClientData.isGetitsMode() == true ){

		//念のため前回までの閲覧ログは削除
        ClientData.ContentLogData([]);

		$('#anonymous').show();
		setTimeout(
			function () {
				LOGIN.initLoginGetitsUser();
			},
			LOGIN.timeWaitSplashScreen
		);

	} else if (COMMON.isAnonymousLogin()) {

        $('#anonymous').show();
        setTimeout(
            function () {
                LOGIN.initLoginAnonymousUser();
            }, LOGIN.timeWaitSplashScreen);
    }
    else {

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

        $('#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();
    }
};
//});


