/// <reference path="../common/js/avweb.js" />
/// <reference path="../common/js/screenLock.js" />
/// <reference path="../common/js/common.js" />
/// <reference path="../common/js/i18n.js" />
/// <reference path="../common/js/jquery-1.8.1.min.js" />
/// <reference path="../common/js/jquery-ui-1.8.23.custom.min.js" />
/// <reference path="../common/js/jquery.toastmessage.js" />
/// <reference path="../common/js/pageViewer.js" />

//グローバルの名前空間用のオブジェクトを用意する
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.force_login_periodically;
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() {
    //Check Last time display language
    //ClientData.userInfo_language(localStorage.getItem(avwsys_storagekey));
    if (ClientData.userInfo_rememberLogin()) {
        LOGIN.loadLoginInfo();
    }
};

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

    var lang = getCurrentLanguage();

    //clear session of old user
    //SessionStorageUtils.clear();
    //avwUserSessionObj = null;
    // create new session for anonymous user
    //avwCreateUserSession();

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

    var chkRemember = $('#chkRemember').attr('checked');
	var accountPath = $('#txtAccPath').val();
	var loginId = $('#txtAccId').val();
	var 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);
	LOGIN.saveServiceUserOption();
	
};

//Check validation
LOGIN.checkValidation = function() {
    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(i18nText('msgLoginEmpty'));
        msgError.attr('lang', 'msgLoginEmpty');
        msgError.show();        
        return false;
    }
    else if (!ValidationUtil.CheckRequiredForText(loginId)) {
		LOGIN.login_errorMessage = "";
        msgError.html(i18nText('msgLoginEmpty'));
        msgError.attr('lang', 'msgLoginEmpty');
        msgError.show();
        return false;
    }
    else if (!ValidationUtil.CheckRequiredForText(password)) {
    	LOGIN.login_errorMessage = "";
        msgError.html(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(i18nText('msgPwdEmpty'));
	    msgError.attr('lang', 'msgPwdEmpty');
	    msgError.show();
        return false;
	}
    else if (!ValidationUtil.CheckRequiredForText(newPass)) {
    	LOGIN.login_errorMessage = "";
        msgError.html(i18nText('msgPwdEmpty'));
        msgError.attr('lang', 'msgPwdEmpty');
        msgError.show();
        return false;
	}
	else
	{
		if(newPass != confirmPass){
			LOGIN.login_errorMessage = "";
		    msgError.html(i18nText('msgPwdNotMatch'));
		    msgError.attr('lang', 'msgPwdNotMatch');
		    msgError.show();
			return false;
		}
		else{
			return true;
		}
	}	
};

//Login Process
LOGIN.processLogin = function() {
	var accountPath = $('#txtAccPath').val();
	var loginId = $('#txtAccId').val();
	var password = $('#txtPassword').val();
	var requireChangePassword = 0;
	var skipPwdDate;

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

    // 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 sysSettings = avwSysSetting();
    var apiLoginUrl = ClientData.conf_apiLoginUrl(); //sysSettings.apiLoginUrl;

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

    avwCmsApiWithUrl(apiLoginUrl, null, 'webClientLogin', 'GET', params, function (data) {
        //requirePasswordChange = data.requirePasswordChange;
        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 (data.requirePasswordChange == 0) {
                ClientData.userInfo_sid(ClientData.userInfo_sid_local());
                
                //OpenUrlでコンテンツ開く場合
                if( paramContentID != '' ){
                    LOGIN.showContentViewByOpenUrl(paramContentID);
                } else {
                    //ホームへ移動
                    avwScreenMove("abvw/" + 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 {
                                //ホームへ移動
                                avwScreenMove("abvw/" + 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 {
                        //ホームへ移動
                        avwScreenMove("abvw/" + 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 {
                                //ホームへ移動
                                avwScreenMove("abvw/" + 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 {
                        //ホームへ移動
                        avwScreenMove("abvw/" + ScreenIds.Home);
                    }
                    
                }
            }
        }
        else {
            LOGIN.login_errorMessage = data.errorMessage;
            $('#main-error-message').html(AVWEB.format(i18nText('msgLoginErrWrong'), data.errorMessage).toString());
            $('#main-error-message').show();

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

            $('#main-error-message').html(AVWEB.format(i18nText('msgLoginErrWrong'), JSON.parse(xhr.responseText).errorMessage).toString());
        } else {
            $('#main-error-message').html(AVWEB.format(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
    };

    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());
            avwScreenMove("abvw/" + ScreenIds.Home);
        }
        else {
            $('#dialog-error-message').html(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
            showSystemError();
        }
    });	
};

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

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

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

//Open Change Password Dialog
LOGIN.OpenChangePasswordDialog = function(){
    // Clear all input values
    $("#main-password-change").show();
    $("#main-password-change").center();
    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.serviceName == 'force_pw_change_periodically') {
            ClientData.serviceOpt_force_pw_change_periodically(option.value);
        }
        else if (option.serviceName == 'force_pw_change_on_login') {
            ClientData.serviceOpt_force_pw_change_on_login(option.value);
        }

        // No.8: do not use serviceOpt_force_login_periodically
        //        else if (option.serviceName == 'force_login_periodically') {
        //            ClientData.serviceOpt_force_login_periodically(option.value);
        //        }
        else if (option.serviceName == 'marking') {
            ClientData.serviceOpt_marking(option.value);
        }
        else if (option.serviceName == 'user_data_backup') {
            ClientData.serviceOpt_user_data_backup(option.value);
        }
        else if (option.serviceName == 'web_screen_lock') {
            ClientData.serviceOpt_web_screen_lock(option.value);
        }
        else if (option.serviceName == 'web_screen_lock_wait') {
            ClientData.serviceOpt_web_screen_lock_wait(option.value);
        }
        
        else if( option.serviceName == 'catalog_edition' ) {
            ClientData.serviceOpt_catalog_edition(option.value);
        }
        else if( option.serviceName == 'hibiyakadan_catalog' ) {
            ClientData.serviceOpt_hibiyakadan_catalog(option.value);
        }
        else if( option.serviceName == 'usable_readinglog_gps' ) {
            ClientData.serviceOpt_usable_readinglog_gps(option.value);
        }
        else if( option.serviceName == 'usable_readinglog_object' ) {
            ClientData.serviceOpt_usable_readinglog_object(option.value);
        }
        else if( option.serviceName == 'daihatsu' ) {
            ClientData.serviceOpt_daihatsu(option.value);
        }
    });
};

//Get Service Option
LOGIN.getServiceOptionList = function(){
		
	$.each(LOGIN.optionList, function(i, option){
	
		if(option.serviceName == 'force_pw_change_periodically'){
			LOGIN.force_pw_change_periodically = option.value;
		}
		else if(option.serviceName == 'force_pw_change_on_login'){
			LOGIN.force_pw_change_on_login = option.value;
		}
		else if(option.serviceName == 'force_login_periodically'){
			LOGIN.force_login_periodically = option.value;
		}
		else if(option.serviceName == 'marking'){
			LOGIN.marking = option.value;
		}
		else if(option.serviceName == 'user_data_backup'){
			LOGIN.user_data_backup = option.value;
		}
		
	});
};

//function OpenChangePassword() {
//    //$("#dlgChangePassword").dialog("open");
//    //$(".ui-dialog-titlebar").hide();
//};

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

$(document).ready(function (e) {

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

	var sysSettings = avwSysSetting(); // get info in conf.json
	
	//getitsサーバー設定確認
	//getitsモード初期化
	ClientData.isGetitsMode(false);
	if( sysSettings.apiUrl == "" ){
	
		//引数パラメータを取得
		var siteUrl = LOGIN.getUrlParams('siteUrl');
		var urlPath = LOGIN.getUrlParams('urlPath');
		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("");
		
		}
	
	} else {
		//confのパラメータセット
		ClientData.conf_apiUrl( sysSettings.apiUrl );
		ClientData.conf_apiLoginUrl( sysSettings.apiLoginUrl );
		ClientData.conf_apiResourceDlUrl( sysSettings. apiResourceDlUrl );
	}

	if( ClientData.isGetitsMode() == true ){
	
		$('#anonymous').show();
		setTimeout(
			function () {
				LOGIN.initLoginGetitsUser();
			}, 
			LOGIN.timeWaitSplashScreen
		);
	
	} else if (COMMON.isAnonymousLogin()) {
	
console.log("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();
    }

});

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

    document.title = i18nText('dspLogin') + ' | ' + 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 = i18nText('dspLogin') + ' | ' + i18nText('sysAppTitle');

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

    var params = {
        previousSid: null,
        loginId: sysSettings.anonymousLoginId,
        urlpath: sysSettings.anonymousLoginPath
    };

    avwCmsApiWithUrl(ClientData.conf_apiLoginUrl(), null, 'webClientAnonymousLogin', 'post', params, function (data) {
    
        if (data.result == 'success') {

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

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

            ClientData.userInfo_loginId(sysSettings.anonymousLoginId);
            ClientData.userInfo_loginId_session(sysSettings.anonymousLoginId);

            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 = LOGIN.getUrlParams('cid');
					//カタログ対応
					if( paramContentID != '' ){
						//OpenUrlでコンテンツ開く
						LOGIN.showContentViewByOpenUrl(paramContentID);
					} else {
						//ホームへ移動
						avwScreenMove("abvw/" + ScreenIds.Home);
					}
				} else {
					//ホームへ移動
					avwScreenMove("abvw/" + ScreenIds.Home);
				}
				
            });
        }
        else {
            if (data.errorMessage != null && data.errorMessage != undefined) {
                LOGIN.showMessageErrorLoginAnonymous(AVWEB.format(i18nText('msgAnonymousLoginErr'), data.errorMessage).toString());
            }
            else {
                LOGIN.showMessageErrorLoginAnonymous(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(i18nText('msgAnonymousLoginErr'), errorMessage).toString());
            }
            else {
                LOGIN.showMessageErrorLoginAnonymous(i18nText('msgAnonymousLoginErr2'));
            }
        } else {
            LOGIN.showMessageErrorLoginAnonymous(i18nText('msgAnonymousLoginErr2'));
        }
    });
};

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

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

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

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

    initi18n();

    avwCmsApiWithUrl(ClientData.conf_apiLoginUrl(), ClientData.userInfo_accountPath(), 'webClientGetitsLogin', 'post', params, function (data) {
    
        if (data.result == 'success') {

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

            // set info user anonymous login
            //ClientData.userInfo_accountPath(sysSettings.anonymousLoginPath);
            //ClientData.userInfo_accountPath_session(sysSettings.anonymousLoginPath);
            //ClientData.userInfo_loginId(sysSettings.anonymousLoginId);
            //ClientData.userInfo_loginId_session(sysSettings.anonymousLoginId);

            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 = LOGIN.getUrlParams('cid');
				//カタログ対応
				if( paramContentID != '' ){
					//OpenUrlでコンテンツ開く
					LOGIN.showContentViewByOpenUrl(paramContentID);
				} else {
					//ホームへ移動
					avwScreenMove("abvw/" + ScreenIds.Home);
				}
				
            });
        }
        else {
            if (data.errorMessage != null && data.errorMessage != undefined) {
                LOGIN.showMessageErrorLoginAnonymous(AVWEB.format(i18nText('msgAnonymousLoginErr'), data.errorMessage).toString());
            }
            else {
                LOGIN.showMessageErrorLoginAnonymous(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(i18nText('msgAnonymousLoginErr'), errorMessage).toString());
            }
            else {
                LOGIN.showMessageErrorLoginAnonymous(i18nText('msgAnonymousLoginErr2'));
            }
        } else {
            LOGIN.showMessageErrorLoginAnonymous(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
	};
	avwCmsApiSync(ClientData.userInfo_accountPath(), "webGetContent", 'GET', params,
		function (data) {
		
			//コンテンツIDセット
			ClientData.contentInfo_contentId(strContentId);
			//コンテツタイプ判定
			contentType = data.contentData.contentType;
			if(contentType == ContentTypeKeys.Type_Others){
				//Download content
				HEADER.downloadResourceById(strContentId);
				// redraw content remove new icon
				//drawEditImage(contentId); 不要
			} else {
				//Go to Conten view page
				
				//アラート表示組み込めるか
				messageLevel[data.contentData.contentId] = { alertMessageLevel:data.contentData.alertMessageLevel, alertMessage:data.contentData.alertMessage};
				
				// check limit of content
				checkLimitContent(
					data.contentData.contentId,
					function()
					{ 
						LOGIN.alertMessageOkFunction_callback();
					},
					function()
					{ 
						LOGIN.alertMessageCancelFunction_callback();
					}
				);
				//avwScreenMove("abvw/" + ScreenIds.ContentView);
			}
		
		},
		function (xmlHttpRequest, txtStatus, errorThrown) {
			//見つからないかエラーなのでホームに移動
			avwScreenMove("abvw/" + ScreenIds.Home);
		}
	);

};

//警告表示時のOK処理
LOGIN.alertMessageOkFunction_callback = function(){
	avwScreenMove("abvw/" + ScreenIds.ContentView);
};
//警告表示時のキャンセル処理
LOGIN.alertMessageCancelFunction_callback = function(){
	avwScreenMove("abvw/" + ScreenIds.Home);
};

//Get param url
LOGIN.getUrlParams = function(name){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var regexS = "[\\?&]"+name+"=([^&#]*)";  
	var regex = new RegExp( regexS );  
	var results = regex.exec( window.location.href ); 
	if( results == null ){
		return "";
	}
	else{
		return results[1];
	}
};

