/// <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 requirePasswordChange;
var userinfo_sid;
var userInfo_userName;
var optionList = [];

var force_pw_change_on_login;
var force_pw_change_periodically;
var user_data_backup;
var marking;
var force_login_periodically;

var login_errorMessage = ""; 
//Load login Info
function loadLoginInfo() {
	
    $('#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
function initialScreen() {

    //Check Last time display language
    //ClientData.userInfo_language(localStorage.getItem(avwsys_storagekey));

    if (ClientData.userInfo_rememberLogin()) {
        loadLoginInfo();                                     
    }
};

//check Save Login Info
function saveLoginInfo() {
    SessionStorageUtils.login();
    
	// 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(userInfo_userName);
	
    if(chkRemember == 'checked')
    {
   		ClientData.userInfo_rememberLogin(true);
    }
    else
    {
    	ClientData.userInfo_rememberLogin(false);
    }

    ClientData.userInfo_lastLoginTime(date.jpDateTimeString());
	//ClientData.requirePasswordChange(requirePasswordChange);
	//ClientData.userInfo_sid(userinfo_sid);
	ClientData.userInfo_sid_local(userinfo_sid);
	saveServiceUserOption();
	
};

//Check validation
function checkValidation() {

    var accountPath = $('#txtAccPath').val();
    var loginId = $('#txtAccId').val();
    var password = $('#txtPassword').val();
    var msgError = $('#main-error-message');

    if (!ValidationUtil.CheckRequiredForText(accountPath)) {
    	login_errorMessage = "";
        msgError.html(i18nText('msgLoginEmpty'));
        msgError.attr('lang', 'msgLoginEmpty');
        msgError.show();        
        return false;
    }
    else if (!ValidationUtil.CheckRequiredForText(loginId)) {
		login_errorMessage = "";
        msgError.html(i18nText('msgLoginEmpty'));
        msgError.attr('lang', 'msgLoginEmpty');
        msgError.show();
        return false;
    }
    else if (!ValidationUtil.CheckRequiredForText(password)) {
    	login_errorMessage = "";
        msgError.html(i18nText('msgLoginEmpty'));
        msgError.attr('lang', 'msgLoginEmpty');
        msgError.show();
        return false;
    }
    else {
        return true;
    }
};

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

	if (!ValidationUtil.CheckRequiredForText(currentPass)) {
		login_errorMessage = "";
	    msgError.html(i18nText('msgPwdEmpty'));
	    msgError.attr('lang', 'msgPwdEmpty');
	    msgError.show();

	    /* show error messages */
	    //$().toastmessage({ position: 'middle-center' });
	    //$().toastmessage('showToast', {
	    //    type: 'error',
	    //    sticky: true,
	    //    text: i18nText('msgPwdEmpty')
	    //});
    
        return false;
	}
    else if (!ValidationUtil.CheckRequiredForText(newPass)) {
    	login_errorMessage = "";
        msgError.html(i18nText('msgPwdEmpty'));
        msgError.attr('lang', 'msgPwdEmpty');
        msgError.show();
        /* show error messages */
        //$().toastmessage({ position: 'middle-center' });
        //$().toastmessage('showToast', {
         //   type: 'error',
        //    sticky: true,
         //   text: i18nText('msgPwdEmpty')
        //});
        
        return false;
	}
//    else if (!ValidationUtil.CheckRequiredForText(confirmPass)) {
//        //msgError.html(i18nText('msgPwdEmpty'));
//        //msgError.show();
//        /* show error messages */
//        $().toastmessage({ position: 'middle-center' });
//        $().toastmessage('showToast', {
//            type: 'error',
//            sticky: true,
//            text: i18nText('msgPwdEmpty')
//        });
//        return false;
//	}
	else
	{
		if(newPass != confirmPass){
			login_errorMessage = "";
		    msgError.html(i18nText('msgPwdNotMatch'));
		    msgError.attr('lang', 'msgPwdNotMatch');
		    msgError.show();
		    /* show error messages */
		   // $().toastmessage({ position: 'middle-center' });
		   // $().toastmessage('showToast', {
		   //     type: 'error',
		   //     sticky: true,
		    //    text: i18nText('msgPwdNotMatch')
		    //});
			return false;
		}
		else{
			return true;
		}					
	}	
};

//Login Process
function processLogin() {

	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 = sysSettings.apiLoginUrl;

    avwCmsApiWithUrl(apiLoginUrl, null, 'webClientLogin', 'GET', params, function (data) {
        requirePasswordChange = data.requirePasswordChange;
        userinfo_sid = data.sid;
        userInfo_userName = data.userName;
        optionList = data.serviceOptionList;
        getServiceOptionList();

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

            // Save retrieved info
            saveLoginInfo();

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

            if (data.requirePasswordChange == 0) {
                ClientData.userInfo_sid(ClientData.userInfo_sid_local());
                avwScreenMove("abvw/" + ScreenIds.Home);
            }
            else if (data.requirePasswordChange == 1) {

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

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

                    if (skipPwdDate == null || skipPwdDate == 'undefined') {

                        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());
                            avwScreenMove("abvw/" + ScreenIds.Home);
                        }
                        else if (numDay > 30) {
                            OpenChangePasswordDialog();
                            $('#btnSkip').show();
                            $(".ui-dialog-titlebar").hide();
                        }
                    }
                }
                else {  // no need to change password
                    ClientData.userInfo_sid(ClientData.userInfo_sid_local());
                    avwScreenMove("abvw/" + ScreenIds.Home);
                }
            }
            else if (data.requirePasswordChange == 2) {

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

                    if (skipPwdDate == null || skipPwdDate == 'undefined') {
                        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());
                            avwScreenMove("abvw/" + ScreenIds.Home);
                        }
                        else if (numDay > 30) {
                            OpenChangePasswordDialog();
                            $(".ui-dialog-titlebar").hide();
                        }
                    }
                } else if (force_pw_change_periodically == 2) {  // Force to change password
                    OpenChangePasswordDialog();
                    $('#btnSkip').hide();
                    $(".ui-dialog-titlebar").hide();
                    $("#txtPwdRemind").css('visibility', 'hidden');
                }
                else {  // No need to change password
                    ClientData.userInfo_sid(ClientData.userInfo_sid_local());
                    avwScreenMove("abvw/" + ScreenIds.Home);
                }
            }
        }
        else {
        	login_errorMessage = data.errorMessage; 
            $('#main-error-message').html(format(i18nText('msgLoginErrWrong'), data.errorMessage).toString());
            $('#main-error-message').show();

            //            $('#main-error-message').attr('lang', 'msgLoginErrWrong');
            //            //$('#main-error-message').html(i18nText('msgLoginErrWrong'));
            //            //alert($('#main-error-message').html());
            //            $('#main-error-message').css('display', 'block');

            //            if (ClientData.userInfo_language() != null) {
            //                changeLanguage(ClientData.userInfo_language());
            //            }
            //            else {
            //                changeLanguage(Consts.ConstLanguage_Ja);
            //            }

        }
    }, function (xhr, statusText, errorThrown) {
        if (xhr.responseText && xhr.status != 0) {
    	    login_errorMessage = JSON.parse(xhr.responseText).errorMessage;
        
	        $('#main-error-message').html(format(i18nText('msgLoginErrWrong'), JSON.parse(xhr.responseText).errorMessage).toString());
        } else {
        	$('#main-error-message').html(format(i18nText('msgLoginErrWrong'), 'E001'));
        }
        $('#main-error-message').show();
    });
};

//Change Password Process
function changePasswordProcess(){
	var accountPath = $('#txtAccPath').val();
	//var sid = ClientData.userInfo_sid();
	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');
            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
function changeLanguageJa(){
	changeLanguage(Consts.ConstLanguage_Ja);
	document.title = i18nText('dspLogin') + ' | ' + i18nText('sysAppTitle');
    //ClientData.userInfo_language(Consts.ConstLanguage_Ja);    
    if (login_errorMessage != ""){    	
    	$('#main-error-message').html(format(i18nText('msgLoginErrWrong'), login_errorMessage).toString());
    }
};

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

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

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

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

//Skip Password function
function skipPassFunction(){
	var date = new Date();
	
	ClientData.userInfo_pwdSkipDt(date);
	//window.location = "abvw/" + ScreenIds.Home;
	ClientData.userInfo_sid(ClientData.userInfo_sid_local());
    avwScreenMove("abvw/" + ScreenIds.Home);
	
};

//Open Change Password Dialog
function OpenChangePasswordDialog(){
    // Clear all input values

    
    $("#main-password-change").show();
    $("#main-password-change").center();
    lockLayout();
};

//Close Chnage Password Dialog
function CloseChangePasswordDialog(){
	$("#main-password-change").dialog('close');
};

//Save Service Option
function saveServiceUserOption(){
	
	$.each(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);
		}
		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);
		}					
	});
};

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

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

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

$(document).ready(function (e) {
    
    document.title = i18nText('dspLogin') + ' | ' + i18nText('sysAppTitle');
    
    //Initial Screen
    initialScreen();
	
	//Change language
	$('#changeLanguage').change(function() {		
		switch($(this).val()) {
			case "language-ja":
				changeLanguageJa();
			break;
			
			case "language-ko":
				changeLanguageKo();
			break;
			
            case "language-en":
                changeLanguageEn();
            break;
            case "language-th":
                changeLanguageTh();
            break;
            case "language-in":
                changeLanguageIn();
            break;
			
			default:
				changeLanguageJa();
			break;
		}
	});
	
	/*
    //Change language japanese
    $('#language-ja').click(changeLanguageJa);
    //Change language korean
    $('#language-ko').click(changeLanguageKo);
    //Change laguage english
    $('#language-en').click(changeLanguageEn);
	*/
	
    //Button login click event
    $('#btnLogin').click(loginFunction);
    //Button Change click event
    $('#btnChange').click(changePassFunction);
    //Button Skip click event
    $('#btnSkip').click(skipPassFunction);
    
    $('#txtPassword').keydown(loginWhenClickEnter);

});
