/// 設定変更画面
/// <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();

        // check disabled button backup
        checkDisabledButton('#dlgConfirmBackup .option_backup input', '#dspOptBk_OK');
    }
    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');
        $('#regionOptionBackup').css('visibility', 'hidden');
    }
    else {
        //        if (IsExistBackupFile() == false) {
        //            $("#dspOptRes").css('visibility', 'hidden');
        //        }
        //        else {
        //            $("#dspOptRes").css('visibility', '');
        //  }

        // check show restore button No.17

        var isExistMarking = IsExistBackupFile('Marking.json', 2);
        var isExistContentMemo = IsExistBackupFile('ContentMemo.json', 1);
        var isExistBookmark = IsExistBackupFile('Bookmark.json', 4);

        if (isExistMarking || isExistContentMemo || isExistBookmark) {
            $("#dspOptRes").css('visibility', '');

            if (!isExistMarking) {
                $('#chkopResMarking').attr('disabled', 'disabled').removeAttr('checked');
            }
            else {
                $('#chkopResMarking').removeAttr('disabled');
            }

            if (!isExistContentMemo) {
                $('#chkopResMemo').attr('disabled', 'disabled').removeAttr('checked');
            }
            else {
                $('#chkopResMemo').removeAttr('disabled');
            }

            if (!isExistBookmark) {
                $('#chkopResShiori').attr('disabled', 'disabled').removeAttr('checked');
            }
            else {
                $('#chkopResShiori').removeAttr('disabled');
            }

            // check disabled button restore
            checkDisabledButton('#dlgConfirmRestore .option_backup input', '#dspOptRes_OK');

        }
        else {
            $("#dspOptRes").css('visibility', 'hidden');
        }
    }
});

/*
  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;
//};

/*
Check backup file exists or not for No.17
*/

function IsExistBackupFile(file,type) {
    var isExisted = false;
    var params = { "sid": ClientData.userInfo_sid(), "filename": file, fileType: type }; //, deviceType: '4' 
    // 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();

    // check button is disabled
    if ($(this).hasClass('disabled'))
        return;

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

    // backup data for No.17

    var isBackupMarking = $('#chkopBkMarking').attr('checked') == 'checked';
    var isBackupMemo = $('#chkopBkMemo').attr('checked') == 'checked';
    var isBackupBookmark = $('#chkopBkShiori').attr('checked') == 'checked';

    if (!isBackupMarking && !isBackupMemo && !isBackupBookmark)
    {
        closeBackup();
        return;
    }

    // call backup file at header
    DoBackup(isBackupMarking, isBackupMemo, isBackupBookmark, false,
    function () {

        // Check to hide/show backup button
        setStatusButtonBackup();

        // update check box restore
        if (isBackupMarking && !ClientData.isChangedMarkingData()) {
            $('#chkopResMarking').removeAttr('disabled');
        }
        if (isBackupMemo && !ClientData.isChangedMemo()) {
            $('#chkopResMemo').removeAttr('disabled');
        }
        if (isBackupBookmark && !ClientData.isChangedBookmark()) {
            $('#chkopResShiori').removeAttr('disabled');
        }

        closeBackup();

    });  
};

// set status button backup and checkbox option
function setStatusButtonBackup() {    
    if (ClientData.isChangedBookmark() == true || ClientData.isChangedMarkingData() == true || ClientData.isChangedMemo() == true) {

        if (ClientData.isChangedBookmark() != true) {
            $('#chkopBkShiori').attr('disabled', 'disabled').removeAttr('checked');
        }
        if (ClientData.isChangedMarkingData() != true) {
            $('#chkopBkMarking').attr('disabled', 'disabled').removeAttr('checked');
        }
        if (ClientData.isChangedMemo() != true) {
            $('#chkopBkMemo').attr('disabled', 'disabled').removeAttr('checked');
        }
        $("#dspOptBk").show();
    }
    else {
        
        $("#dspOptBk").hide();
    }
};

//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
    // ----------------------------

    // check button is disabled
    if ($(this).hasClass('disabled'))
        return;

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

    // Restore data for No.17

    var isRestoreMarking = $('#chkopResMarking').attr('checked') == 'checked';
    var isRestoreMemo = $('#chkopResMemo').attr('checked') == 'checked';
    var isRestoreBookmark = $('#chkopResShiori').attr('checked') == 'checked';
    if (!isRestoreMarking && !isRestoreMemo && !isRestoreBookmark) {
        closeRestore();
        return;
    }

        $().toastmessage({ position: 'middle-center' });
        $().toastmessage('showToast', {
            type: '',
            sticky: true,
            text: '',
            customMessages: 'divResultMessage'
        });
        $('#divResultMessage').append("<div class='toast-item-loading'></div>"); // show item loading

        setTimeout(function () {

            if (isRestoreMarking) {

                // restore Marking Data
                var res = restoreMarkingData();
                if (!res) {
                    $('#divResultMessage').append("<div class='toast-item-image-error toast-item-message'>" + i18nText('txtBkMarking') + " " + i18nText('msgRestoreFailed') + "</div>");
                }
                else {
                    $('#divResultMessage').append("<div class='toast-item-image-success toast-item-message'>" + i18nText('txtBkMarking') + " " + i18nText('msgRestoreSuccess') + "</div>");
                }
            }
            if (isRestoreMemo) {

                // restore Memo data
                var res = restoreMemoData();
                if (!res) {
                    $('#divResultMessage').append("<div class='toast-item-image-error toast-item-message'>" + i18nText('txtBkMemo') + " " + i18nText('msgRestoreFailed') + "</div>");
                }
                else {
                    $('#divResultMessage').append("<div class='toast-item-image-success toast-item-message'>" + i18nText('txtBkMemo') + " " + i18nText('msgRestoreSuccess') + "</div>");
                }
            }
            if (isRestoreBookmark) {

                // restore Bookmark data
                var res = restoreBookmarkData();
                if (!res) {
                    $('#divResultMessage').append("<div class='toast-item-image-error toast-item-message'>" + i18nText('txtBkShiori') + " " + i18nText('msgRestoreFailed') + "</div>");
                }
                else {
                    $('#divResultMessage').append("<div class='toast-item-image-success toast-item-message'>" + i18nText('txtBkShiori') + " " + i18nText('msgRestoreSuccess') + "</div>");
                }
            }

            // set status button backup
            //setStatusButtonBackup();

            // show message result restore

            // hide item loading
            $('#divResultMessage .toast-item-loading').hide();

            // active close toast button
            $('.toast-item-close').click(function () { $().toastmessage('removeToast', $('#divResultMessage'), null) });
        }, 1000);

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

// Restore data for No.17

/*
 * Call api to restore bookmark data
 */
function restoreBookmarkData()
{
    var result = false;
    avwCmsApiSync(ClientData.userInfo_accountPath(), "getBackupFile", "post",
                { sid: ClientData.userInfo_sid(), filename: "Bookmark.json" }, // deviceType: '4',
                    function (data) {
                        if (data) {                            
                            getDataBookmark(data);
                            ClientData.isChangedBookmark(false);
                            result = true;
                        }
                    }
                ,
                function (xhr, b, c) {
                }
    );
    return result;
};

/*
 * Call api to restore memo data
 */
function restoreMemoData() {
    var result = false;
    avwCmsApiSync(ClientData.userInfo_accountPath(), "getBackupFile", "post",
                { sid: ClientData.userInfo_sid(), filename: "ContentMemo.json" }, //deviceType: '4', 
                    function (data) {
                        if (data) {
                            getDataMemo(data);
                            //ClientData.isChangedMemo(true);
                            result = true;
                        }
                    }
                ,
                function (xhr, b, c) {
                }
    );
    return result;
};

/*
 * Call api to restore marking data
 */
function restoreMarkingData() 
{
    var result = false;
    avwCmsApiSync(ClientData.userInfo_accountPath(), "getBackupFile", "post",
                { sid: ClientData.userInfo_sid(), filename: "Marking.json" }, // deviceType: '4', 
                    function (data) {
                        if (data) {
                            getDataMarking(data);
                            ClientData.isChangedMarkingData(false);
                            result = true;
                        }
                    }
                ,
                function (xhr, b, c) {
                }
    );
    return result;
}


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


    // save options backup No.17
    if ($("#chkBkMarking").attr('checked') == 'checked') {
        ClientData.userOpt_bkMakingFlag(1);
    }
    else {
        ClientData.userOpt_bkMakingFlag(0);
    }

    if ($("#chkBkMemo").attr('checked') == 'checked') {
        ClientData.userOpt_bkMemoFlag(1);
    }
    else {
        ClientData.userOpt_bkMemoFlag(0);
    }

    if ($("#chkBkShiori").attr('checked') == 'checked') {
        ClientData.userOpt_bkShioriFlag(1);
    }
    else {
        ClientData.userOpt_bkShioriFlag(0);
    }

    // save config page transition No.4

    ClientData.userOpt_pageTransition($('#cboAnimation').val());

    var timeAnimation = $('#txtValueAnimation').val();

    if (isNaN(timeAnimation) || timeAnimation < 0.1 || timeAnimation.length == 2 || timeAnimation.length > 3 || timeAnimation.indexOf('.')==0) {
        timeAnimation = 0.1;
    }
    else if (timeAnimation > 9.9) {
        timeAnimation = 9.9;
    }

    ClientData.userOpt_pageTransitionPeriod(timeAnimation);
    $('#txtValueAnimation').val(timeAnimation);


    /* 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');

    // set default backup marking
    $('#chkBkMarking').attr('checked', 'checked');
    // set default backup memo
    $('#chkBkMemo').attr('checked', 'checked');
    // set default backup bookmark
    $('#chkBkShiori').attr('checked', 'checked');

    // reset page transition no.4
    $('#txtValueAnimation').val(1);
    $('#cboAnimation').val(0);
    $('#slidebar-animation').slider('value', 1);

};

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

    // set options backup No.17

    if (ClientData.userOpt_bkMakingFlag() == 0) 
    {
        $("#chkopBkMarking").removeAttr('checked');
    }
    else 
    {
        $("#chkopBkMarking").attr('checked', 'checked');
    }
    if (ClientData.userOpt_bkMemoFlag() == 0) {
        $("#chkopBkMemo").removeAttr('checked');
    }
    else {
        $("#chkopBkMemo").attr('checked', 'checked');
    }

    if (ClientData.userOpt_bkShioriFlag() == 0) {
        $("#chkopBkShiori").removeAttr('checked');
    }
    else {
        $("#chkopBkShiori").attr('checked', 'checked');
    }

    // check content is changed

    if (!ClientData.isChangedBookmark()) 
    {
        $('#chkopBkShiori').attr('disabled', 'disabled').removeAttr('checked');        
    }
    else {
        $('#chkopBkShiori').removeAttr('disabled');
    }

    if (!ClientData.isChangedMemo()) {
        $('#chkopBkMemo').attr('disabled', 'disabled').removeAttr('checked');
    }
    else {
        $('#chkopBkMemo').removeAttr('disabled');
    }    
    if (!ClientData.isChangedMarkingData()) {
        $('#chkopBkMarking').attr('disabled', 'disabled').removeAttr('checked');
    }
    else {
        $('#chkopBkMarking').removeAttr('disabled');
    }

    setDisabledButton('#dlgConfirmBackup .option_backup input', '#dspOptBk_OK');

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

    // check avaliable restore no.17

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

    // options backup No.17

    if (ClientData.userOpt_bkMakingFlag() == 0) {
        $("#chkBkMarking").removeAttr('checked');
    }
    else {
        $("#chkBkMarking").attr('checked', 'checked');
    }

    if (ClientData.userOpt_bkMemoFlag() == 0) {
        $("#chkBkMemo").removeAttr('checked');
    }
    else {
        $("#chkBkMemo").attr('checked', 'checked');
    }

    if (ClientData.userOpt_bkShioriFlag() == 0) {
        $("#chkBkShiori").removeAttr('checked');
    }
    else {
        $("#chkBkShiori").attr('checked', 'checked');
    }

    // load config page transition & page transition period  No.4

    $('#cboAnimation').val(ClientData.userOpt_pageTransition());

    $('#txtValueAnimation').val(ClientData.userOpt_pageTransitionPeriod());

    $('#txtValueAnimation').blur(function () {

        var value = $(this).val();
        if (isNaN(value) || value < 0.1 || value.length == 2 || value.length > 3 || value.indexOf('.') == 0) {
            value = 0.1;
        }
        else if (value > 9.9) {
            value = 9.9;
        }

        $(this).val(value);
        $('#slidebar-animation').slider('value', value);
    });

    $('#slidebar-animation').slider(
        {
            min: 0.1,
            max: 9.9,
            step: 0.1,
            value: $('#txtValueAnimation').val(),
            slide: doChangeAnimationSlidebar
        }
    );

};

function doChangeAnimationSlidebar(e,obj) {
    $('#txtValueAnimation').val(obj.value);
};