/// 設定変更画面
/// <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" />

// Init function of page
$(document).ready(function () {

    if (!avwCheckLogin(ScreenIds.Login)) return;
    ToogleLogoutNortice();
    LockScreen();

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

    // Set bookmark screen
    ClientData.BookmarkScreen(ScreenIds.Setting);

    InitScreen();

    $("#dspSave").click(dspSave_Click);

    $("#dspPwdUpd").click(dspPwdUpd_Click);

    $("#dspOptReset").click(dspOptReset_Click);

    $("#dspOptBk").click(dspOptBk_Click);

    $("#dspOptRes").click(dspOptRes_Click);

    $("#dspPwdUpd1").click(dspPwdUpd1_Click);
    $("#dspSkip").click(dspSkip_Click);
    $("#dspCancel").click(dspCancel_Click);

    $("#dspOptRes_OK").click(dspOptRes_OK_Click);
    $("#dspOptRes_Cancel").click(dspOptRes_Cancel_Click);

    $("#dspOptBk_OK").click(dspOptBk_OK_Click);
    $("#dspOptBk_Cancel").click(dspOptBk_Cancel_Click);

    // Check to hide/show backup button
    if (ClientData.isChangedBookmark() == true
        || ClientData.isChangedMarkingData() == true
        || ClientData.isChangedMemo() == true) {
        $("#dspOptBk").show();
    }
    else {
        $("#dspOptBk").hide();
    }


    // Get flag to determine must change password
    avwCmsApi(ClientData.userInfo_accountPath(), "requirePasswordChange", 'GET', { sid: ClientData.userInfo_sid() },
                avwCmsApi_requirePasswordChange_success,
                null
    );

    // In case: user_data_backup = "Y" -> backup
    if (ClientData.serviceOpt_user_data_backup() != "Y") {

        $("#dspOptBk").css('visibility', 'hidden');
        $("#dspOptRes").css('visibility', 'hidden');

        $("#chkOptBkCfm").css('visibility', 'hidden');
        $("#txtOptBkCfm").css('visibility', 'hidden');
        $("#txtBkResCap").css('visibility', 'hidden');
    }
    else {
        if (IsExistBackupFile() == false) {
            $("#dspOptRes").css('visibility', 'hidden');
        }
        else {
            $("#dspOptRes").css('visibility', '');
        }
    }

});

/*
  event of changing language
*/
function changeLanguageCallBackFunction() {        
    document.title = i18nText('dspSetting') + ' | ' + i18nText('sysAppTitle');
};

/*
Check backup file exists or not
*/
function IsExistBackupFile() {
    var isExisted = false;
    var params = { sid: ClientData.userInfo_sid(), deviceType: '4', filename: "webBackupData.json" };
    // Get list of files
    avwCmsApiSync(ClientData.userInfo_accountPath(), "getBackupFile", "post", params,
                    function (data) {
                        if (data) {
                            isExisted = true;
                        }
                    },
                    function (xhr, b, c) {
                        if (xhr.status != 0) {
                            isExisted = false;
                        }
                        else {
                            showSystemError();
                        }
                    });
    return isExisted;
};

// Event success
function avwCmsApi_requirePasswordChange_success(data) {

    ClientData.requirePasswordChange(0);
    if (data.requirePasswordChange == 1) {
        if (ClientData.serviceOpt_force_pw_change_on_login() == 0) { // No need to change password
            // Skip this case
        }
        else if (ClientData.serviceOpt_force_pw_change_on_login() == 1) {  // Recommend to change password
            var pwdSkipDt = ClientData.userInfo_pwdSkipDt();
            
            if (pwdSkipDt) {
                // Check 30 days
                var currDate = new Date();
                var skipDate = new Date(pwdSkipDt);
                var numDay = currDate.subtractByDays(skipDate);
                
                if (numDay <= 30) {
                    // Do not show dialog to change password
                }
                else if (numDay > 30) {
                    // Show dialog to change password
                    OpenChangePassword();

                    $("#dspSkip").show();
                    $("#dspCancel").hide();
                }
            }
            else {
            	
                //alert('pwdSkipDt=null');
                OpenChangePassword();

                $("#dspSkip").show();
                $("#dspCancel").hide();
            }

            
        }
        else if (ClientData.serviceOpt_force_pw_change_on_login() == 2) {  // Force to change password
        	ClientData.requirePasswordChange(1);
            OpenChangePassword();
			
            $("#dspSkip").hide();
            $("#dspCancel").hide();
            //$("#dspPwdUpd1").css('margin', $("#dspCancel").css('margin'));
            $("#dspPwdUpd1").css('margin', '-27px 97px 0 0');
            $("#txtChangePassComment").css('visibility', 'hidden');

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

        if (ClientData.serviceOpt_force_pw_change_periodically() == 0) { // No need to change password
            // Skip this case
        }
        else if (ClientData.serviceOpt_force_pw_change_periodically() == 1) {  // Recommend to change password
            var pwdSkipDt = ClientData.userInfo_pwdSkipDt();

            if (pwdSkipDt) {
                // Check 30 days
                var currDate = new Date();
                var skipDate = new Date(pwdSkipDt);
                var numDay = currDate.subtractByDays(skipDate);
                
                if (numDay <= 30) {
                    // Do not show dialog to change password
                }
                else if (numDay > 30) {
                    // Show dialog to change password
                    OpenChangePassword();

                    $("#dspSkip").show();
                    $("#dspCancel").hide();
                }
            }
            else {
                //alert('pwdSkipDt=null');
                
                OpenChangePassword();

                $("#dspSkip").show();
                $("#dspCancel").hide();
            }


        }
        else if (ClientData.serviceOpt_force_pw_change_periodically() == 2) {  // Force to change password
        	ClientData.requirePasswordChange(1);
            OpenChangePassword();

            $("#dspSkip").hide();
            $("#dspCancel").hide();
            $("#dspPwdUpd1").css('margin', '-27px 97px 0 0');
            $("#txtChangePassComment").css('visibility', 'hidden');
        }
    }
    else if (data.requirePasswordChange == 0) {
        // Skip this case
    }
};

/*
----------------------------------------------------------------------------
Event groups [start]
----------------------------------------------------------------------------
*/

// OK for backup
function dspOptBk_OK_Click(e) {
    e.preventDefault();
    // ----------------------------
    // Process backup here
    // ----------------------------

    // Bakup memo/marking/bookmark
    var params = [
        { name: 'sid', content: ClientData.userInfo_sid() },
        { name: 'deviceType', content: '4' },
        { name: 'formFile', content: JSON.stringify(buildBackupData()), fileName: 'webBackupData.json', contentType: 'text-plain' }
    ];
        avwUploadBackupFile(ClientData.userInfo_accountPath(), params, false, avwCmsApi_uploadBackupFile_success,
                        function (a, b, c) {
                            // Show error message: msgBackupFailed
                            $().toastmessage({ position: 'middle-center' });
                            $().toastmessage('showToast', {
                                type: 'error',
                                sticky: true,
                                text: i18nText('msgBackupFailed')
                            });
                        });
    closeBackup();
};

function avwCmsApi_uploadBackupFile_success(data) {
    if (JSON.parse(data).result == "success") {
        ClientData.isChangedBookmark(false);
        ClientData.isChangedMarkingData(false);
        ClientData.isChangedMemo(false);
        $("#dspOptBk").hide();
        $("#dspOptRes").css('visibility', '');

        // Show message: msgBackupSuccess
        $().toastmessage({ position: 'middle-center' });
        $().toastmessage('showToast', {
            type: 'success',
            sticky: true,
            text: i18nText('msgBackupSuccess')
        });
    }
    else {
        // Show error message: msgBackupFailed
        $().toastmessage({ position: 'middle-center' });
        $().toastmessage('showToast', {
            type: 'error',
            sticky: true,
            text: i18nText('msgBackupFailed')
        });
    }
};

// Cancel for backup
function dspOptBk_Cancel_Click(e) {
    e.preventDefault();
    closeBackup(true);
};

// OK for restore
function dspOptRes_OK_Click(e) {
    e.preventDefault();
    // ----------------------------
    // Process restore
    // ----------------------------

    // Get list of files
    avwCmsApi(ClientData.userInfo_accountPath(), "getBackupFile", "post",
                { sid: ClientData.userInfo_sid(), deviceType: '4', filename: "webBackupData.json" },
                avwCmsApi_getBackupFile_success,
                function (xhr, b, c) {
                    if (xhr.status != 0) {
                        // Show error message
                        $().toastmessage({ position: 'middle-center' });
                        $().toastmessage('showToast', {
                            type: 'error',
                            sticky: true,
                            text: i18nText('msgRestoreFailed')
                        });
                    }
                    else {
                        showSystemError();
                    }
                }
    );

    closeRestore();
};
function avwCmsApi_getBackupFile_success(data) {
    if (data) {
        restoreData(data);
        ClientData.isChangedBookmark(false);
        ClientData.isChangedMarkingData(false);
        ClientData.isChangedMemo(false);
        $("#dspOptBk").hide();
        // Show message: msgRestoreSuccess
        $().toastmessage({ position: 'middle-center' });
        $().toastmessage('showToast', {
            type: 'success',
            sticky: true,
            text: i18nText('msgRestoreSuccess')
        });	
    }
};

// Cancel for restore
function dspOptRes_Cancel_Click(e) {
    e.preventDefault();
    closeRestore(true);
};

// Cancel to change password
function dspCancel_Click(e) {
    e.preventDefault();
    var msgError = $('#dialog-error-message');
    msgError.html('');
    closeChangePassword(true);
};

// Save setting
function dspSave_Click(e) {
    e.preventDefault();

    // 最初の画面を選択
    if ($("#rdoOpt001").attr('checked') == 'checked') {
        ClientData.sortOpt_viewMode(Consts.ConstDisplayMode_BookShelf); // Bookshelf
    }
    else {
        ClientData.sortOpt_viewMode(Consts.ConstDisplayMode_List); // List
    }
    // 動画、音楽繰り返し
    if ($("#chkOpt002").attr('checked') == 'checked') {
        ClientData.userOpt_musicMode(1);
        ClientData.userOpt_videoMode(1);
    }
    else {
        ClientData.userOpt_musicMode(0);
        ClientData.userOpt_videoMode(0);
    }
    // マーキング（コンテンツを開いた時に表示する）
    if ($("#chkOpt003").attr('checked') == 'checked') {
        ClientData.userOpt_makingDsp(1);        
    }
    else {
        ClientData.userOpt_makingDsp(0);        
    }
    // Show/not show alert when press F5.close tab.broswer.
    if ($("#chkOpt005").attr('checked') == 'checked') {
        ClientData.userOpt_closeOrRefreshAlert(1);
        ToogleLogoutNortice();
    }
    else {
        ClientData.userOpt_closeOrRefreshAlert(0);
        ToogleLogoutNortice();
    }
    // 毎回ログアウトの時、バックアップするかどうかは必ず確認する
    if ($("#chkOptBkCfm").attr('checked') == 'checked') {
        ClientData.userOpt_bkConfirmFlg(1);
    }
    else {
        ClientData.userOpt_bkConfirmFlg(0);
    }

    /* show messages */
    $().toastmessage({ position: 'middle-center' });
    $().toastmessage('showToast', {
        type: 'success',
        sticky: true,
        text: i18nText('msgSaveOk')
    });	

};

// Skip to change password
function dspSkip_Click(e) {
    e.preventDefault();
    var msgError = $('#dialog-error-message');
    msgError.html('');
    // Update パスワードスキップ日時
    ClientData.userInfo_pwdSkipDt(new Date());
    closeChangePassword();
};

function OpenChangePassword() {
    //$("#dlgChangePassword").dialog("open");
    //$(".ui-dialog-titlebar").hide();
    
    // Clear all input values
    $("#txtPwdCur").val('');
    $("#txtPwdNew").val('');
    $("#txtPwdNewRe").val('');

    lockLayout();
    $("#dlgChangePassword").show();
    $("#dlgChangePassword").center();

};

function closeChangePassword(skip) {
    //$("#dlgChangePassword").dialog("close");
    $("#dlgChangePassword").hide();
    unlockLayout();
};

// Want to change password
function dspPwdUpd_Click(e) {
    e.preventDefault();
    $("#dspCancel").show();
    $("#dspSkip").hide();
    $("#txtChangePassComment").css('visibility', 'hidden');
    $("#dspPwdUpd1").css('margin', '-27px 97px 0 0');
         
    // Show dialog
    OpenChangePassword();
};

// Reset setting
function dspOptReset_Click(e) {
    e.preventDefault();

    // 最初の画面を選択
    $("#rdoOpt001").attr('checked', 'checked');
    // 動画、音楽繰り返し
    $("#chkOpt002").attr('checked', 'checked');
    // マーキング（コンテンツを開いた時に表示する）
    $("#chkOpt003").attr('checked', 'checked');
    // Show alert when press F5.close tab.broswer
    $("#chkOpt005").attr('checked', 'checked');
    // 毎回ログアウトの時、バックアップするかどうかは必ず確認する
    $("#chkOptBkCfm").attr('checked', 'checked');
};

// Backup
function dspOptBk_Click(e) {
    e.preventDefault();
    openBackup();
};

// Restore
function dspOptRes_Click(e) {
    e.preventDefault();
    openRestore();
};

// Process changing password
function dspPwdUpd1_Click(e) {
    e.preventDefault();
    var isOK = true;
	var msgError = $('#dialog-error-message');
    // Check validation
    if (!ValidationUtil.CheckRequiredForText(getCurrentPassword())) {
        isOK = false;
        //alert(i18nText('msgPwdEmpty'));
        /* show error messages */
       // $().toastmessage({ position: 'middle-center' });
       // $().toastmessage('showToast', {
        //    type: 'error',
        //    sticky: true,
        //    text: i18nText('msgPwdEmpty')
        //});
	    msgError.html(i18nText('msgPwdEmpty'));
    	msgError.show();
        
    }
    else {
        if (!ValidationUtil.CheckRequiredForText(getNewPassword())) {
            isOK = false;
            //alert(i18nText('msgPwdEmpty'));
            /* show error messages */
            //$().toastmessage({ position: 'middle-center' });
           // $().toastmessage('showToast', {
            //    type: 'error',
            //    sticky: true,
            //    text: i18nText('msgPwdEmpty')
            //});
            
    	    msgError.html(i18nText('msgPwdEmpty'));
	    	msgError.show();
        }
        else {
            if (getNewPassword() != getNewPasswordRe()) {
                isOK = false;
                //alert(i18nText('msgPwdNotMatch'));
                /* show error messages */
                //$().toastmessage({ position: 'middle-center' });
               // $().toastmessage('showToast', {
                //    type: 'error',
                 //   sticky: true,
                 //   text: i18nText('msgPwdNotMatch')
               // });
                msgError.html(i18nText('msgPwdNotMatch'));
    			msgError.show();
            }

        }
    }

    if (isOK) {

        // Check max length
        if (!ValidationUtil.CheckMaxLengthForByte(getCurrentPassword(), 10)) {

            isOK = false;
        }
        if (!ValidationUtil.CheckMaxLengthForByte(getNewPassword(), 10)) {

            isOK = false;
        }
        if (!ValidationUtil.CheckMaxLengthForByte(getNewPasswordRe(), 10)) {

            isOK = false;
        }
        // Data type
        if (!ValidationUtil.IsAlphabetOrNumberOrSymbol(getCurrentPassword())) {

            isOK = false;
        }
        if (!ValidationUtil.IsAlphabetOrNumberOrSymbol(getNewPassword())) {
            isOK = false;
        }
        if (!ValidationUtil.IsAlphabetOrNumberOrSymbol(getNewPasswordRe())) {
            isOK = false;
        }
        var str = getCurrentPassword() + "";
        
//        if (str.contains("_") || str.contains("‐")) {
//            isOK = false;
//        }

    }

    // Do changing password
    var params = {
        sid: ClientData.userInfo_sid(),
        loginId: ClientData.userInfo_loginId_session(),
        password: getCurrentPassword(),
        newPassword: getNewPassword(),
        appId: 4
    };
    
    if (isOK) {

        avwCmsApi(ClientData.userInfo_accountPath(), "passwordChange", "GET", params,
                        avwCmsApi_passwordChange_success,
                        avwCmsApi_passwordChange_fail);
    }
    else {
        //alert('error');
    }
};

function avwCmsApi_passwordChange_success(data) {
    // OK
	var msgError = $('#dialog-error-message');
    if (data.result != undefined && data.result != null) {

        if (data.result != Consts.ConstAPI_SUCCESS) {
            /* show error messages */
            //$().toastmessage({ position: 'middle-center' });
            //$().toastmessage('showToast', {
            //    type: 'error',
            //    sticky: true,
            //    text: i18nText('msgPwdChangeNG')
            //});
            //alert(i18nText('msgPwdOldWrong'));
            
       	    msgError.html(i18nText('msgPwdChangeNG'));
			msgError.show();
        }
        else {
        	ClientData.requirePasswordChange(0);
        	msgError.html('');
            closeChangePassword();
            /* show messages */
            $().toastmessage({ position: 'middle-center' });
            $().toastmessage('showToast', {
                type: 'success',
                sticky: true,
                text: i18nText('msgPwdChangeOK')
            });
        }
    }
};
function avwCmsApi_passwordChange_fail(xhr, b, c) {
    if (xhr.responseText && xhr.status != 0) {
        /* show error messages */
        var msgError = $('#dialog-error-message');

        //msgError.html(i18nText('msgPwdChangeNG'));
        msgError.html(JSON.parse(xhr.responseText).errorMessage);
        msgError.show();
    }
    else {
        showSystemError();
    }
};


/*
----------------------------------------------------------------------------
Event groups [ end ]
----------------------------------------------------------------------------
*/




// Setting dialog
$(function () {
    $('#dlgChangePassword').center();
    $('#dlgConfirmBackup').center();
    $('#dlgConfirmRestore').center();

    $('#dlgChangePassword').hide();
    $('#dlgConfirmBackup').hide();
    $('#dlgConfirmRestore').hide();
//        $('#dlgChangePassword').dialog({
//            autoOpen: false,
//            title: 'Change password',
//            modal: true,
//            resizable: false,
//            width: 550,
//            height: 400

//        });
//        $('#dlgConfirmBackup').dialog({
//            autoOpen: false,
//            title: 'Backup',
//            modal: true,
//            resizable: false,
//            width: 550,
//            height: 400

//        });
//        $('#dlgConfirmRestore').dialog({
//            autoOpen: false,
//            title: 'Restore',
//            modal: true,
//            resizable: false,
//            width: 550,
//            height: 450

    //        });
    // LockScreen();
});

function openBackup() {

    //$("#dlgConfirmBackup").dialog("open");
    //$(".ui-dialog-titlebar").hide();

    lockLayout();
    $("#dlgConfirmBackup").show();
    $("#dlgConfirmBackup").center();

};

function closeBackup(cancel) {
    if (cancel != undefined || cancel == true) {
        //alert('you cancelled');
    }
    //$("#dlgConfirmBackup").dialog("close");
    $("#dlgConfirmBackup").hide();
    unlockLayout();
};

function openRestore() {

    //$("#dlgConfirmRestore").dialog("open");
    //$(".ui-dialog-titlebar").hide();

    lockLayout();
    $("#dlgConfirmRestore").show();
    $("#dlgConfirmRestore").center();
};

function closeRestore(cancel) {
    if (cancel != undefined || cancel == true) {
        //alert('you cancelled');
    }
    //$("#dlgConfirmRestore").dialog("close");
    $("#dlgConfirmRestore").hide();
    unlockLayout();
};

// Get input current password
function getCurrentPassword() {
    return $("#txtPwdCur").val();
};
// Get input new password
function getNewPassword() {
    return $("#txtPwdNew").val();
};
// Get input new password 
function getNewPasswordRe() {
    return $("#txtPwdNewRe").val();
};

// Initalize screen
function InitScreen() {

    // ログインID
    $("#txtLoginId").text(ClientData.userInfo_loginId_session());
    // アカウントパス
    $("#txtLoginPath").text(ClientData.userInfo_accountPath_session());

    // 最終ログイン時間
    $("#txtLastLoginTime").text(ClientData.userInfo_lastLoginTime());
    //alert(getLastLoginDate());


    // 最初の画面を選択
    if (ClientData.sortOpt_viewMode() == Consts.ConstDisplayMode_List) {
        $("#rdoOpt0011").attr('checked', 'checked');
    }
    else {
        $("#rdoOpt001").attr('checked', 'checked');
    }

    // 動画、音楽繰り返し
    if (ClientData.userOpt_musicMode() == 0) {
        $("#chkOpt002").removeAttr('checked');
    }
    else {
        $("#chkOpt002").attr('checked', 'checked');
    }

    // マーキング（コンテンツを開いた時に表示する）
    if (ClientData.userOpt_makingDsp() == 0) {
        $("#chkOpt003").removeAttr('checked');
    }
    else {
        
        $("#chkOpt003").attr('checked', 'checked');
    }
	// Show alert when press F5.close tab.broswer	
	if (ClientData.userOpt_closeOrRefreshAlert() == 0) {		
        $("#chkOpt005").removeAttr('checked');
    }
    else {        
        $("#chkOpt005").attr('checked', 'checked');
    }
    // 毎回ログアウトの時、バックアップするかどうかは必ず確認する
    if (ClientData.userOpt_bkConfirmFlg() == 0) {
        $("#chkOptBkCfm").removeAttr('checked');
    }
    else {
        $("#chkOptBkCfm").attr('checked', 'checked');
    }
};
