// 名前空間
var CHAT_UI = {};

// Rotate
$(window).on('resize', function() {
    if (CHAT_UTIL.isMobile()) {
        return;
    }

    console.log(`width : ${$(this).width()}`);
    console.log(`height : ${$(this).height()}`);

    /*if(CHAT_UI.isLandscapeMode()) {
        $(".group_list").addClass("col-6").removeClass("col-12");
        $(".user_list").addClass("col-6").removeClass("col-12");
        $(".chat_list").addClass("col-6").removeClass("col-12");
        $(".squareBoxContent span").addClass("landscape_span");

        $(".mesgs").addClass("landscape_mesgs");
    } else {

        $(".group_list").removeClass("col-6").addClass("col-12");
        $(".user_list").removeClass("col-6").addClass("col-12");
        $(".chat_list").removeClass("col-6").addClass("col-12");
        $(".squareBoxContent span").removeClass("landscape_span");

        $(".mesgs").removeClass("landscape_mesgs");
    }*/

    if (CHAT_UTIL.isIOS()) {
        if (isLandscape == true) {
            $(".mesgs").addClass("landscape_mesgs");
        } else if (isLandscape == false) {
            $(".mesgs").removeClass("landscape_mesgs");
        }
    }
})

// New Room
// チャットルーム生成ボタン処理
$('#createChatRoom').on('click', function() {
    //loadingIndicatorを表示
    CHAT_UI.showLoadingIndicator();

    let isInvite = false;
    CHAT.globalIsInvite = isInvite;
    socket.emit('getGroupList', isInvite);
});

// Room Delete
// チャットルーム削除ボタン処理
$('#roomDeleteButton').on('click', function(e) {
    if ($('.deleteBox').is(':visible')) {
        // チャットルーム削除アイコンが表示されている時、ブラインド処理を行う
        $('.deleteBox').finish().show().fadeTo('slow', 0, function() {
            $(this).hide();
        });
        // チャットリストについてクリックイベントを与える
        $('.chat_list').off('click');
        $('.chat_list:not(.active_chat)').on('click', function(e) {
            //loadingIndicatorを表示
            CHAT_UI.showLoadingIndicator();
            let roomId = $(this).data('roomId');
            let roomName = $(this).data('roomname');
            socket.emit('joinRoom', roomId, roomName, function() {
                $('#messages').html('');
                $('.titleRoomName').text(roomName).data('roomName', roomName);
                $('#pills-chat-tab').tab('show');
                $("#message-search").attr("placeholder", getLocalizedString("chat_search_placeholder"));
            });
        });

        let roomListTitle = getLocalizedString("roomListTitle")
        $('.titleRoomName').text(roomListTitle)

        $('.chat_list.active_chat').on('click', function(e) {
            $('#pills-chat-tab').tab('show');
        });
    } else {
        // チャットルーム削除アイコンが表示されていない場合、表示する
        $('.deleteBox').finish().hide().fadeTo('slow',1).show();
        // #36129に対応
        let deleteRoomTitle = getLocalizedString("deleteRoomTitle")
        $('.titleRoomName').text(deleteRoomTitle)
        // 重複処理を防ぐためにチャットリストのクリックイベントを消す
        $('.chat_list').off('click');

        // チャットルームの削除アイコンにクリックイベントを与える
        $('.deleteBox').off('click');
        $('.deleteBox').on('click', function(e) {
            // #36174
            let roomId = $(this).data('roomId');
            let activeRoom = $(this).data('activeRoom');
            $("#roomDeleteTitle").text(getLocalizedString("roomDeleteTitle"));
            $("#roomDelete").text(getLocalizedString("roomDelete"));
            $("#cancelTitle").text(getLocalizedString("cancelTitle"));

            // #36128
            $('#roomDeleteConfirm').appendTo("body").modal({
                backdrop: 'static',
                keyboard: false
            })
            .on('click', '#roomDelete', function(e) {
                //loadingIndicatorを表示
                CHAT_UI.showLoadingIndicator();
                // 現在接続されているチャットルームを離れるとメッセージテップを初期化する
                if (activeRoom) {
                    $('#messages').html('');
                    CHAT.saveRoomInfo('', '');
                }
                // チャットルームから退場する
                socket.emit('exitRoom', roomId);

                // #36129に対応
                let roomListTitle = getLocalizedString("roomListTitle")
                $('.titleRoomName').text(roomListTitle)
            });
        });
    }
});

$('#room-search').on('input', function(event) {
    if ($('#room-search').val().length > 0) {
        // 検索結果が有る場合、結果を表示する
        socket.emit('roomSearch', encodeURIComponent($('#room-search').val()));
    } else {
        if (IS_ONLINE == 'true') {
            if (typeof(android) != "undefined") {
                android.updateRoomList();
            } else {
                webkit.messageHandlers.updateRoomList.postMessage({});
            }
            CHAT_UI.refreshRoomList(chatRoomType.DM);
            CHAT_UI.dismissLoadingIndicator();
        }
    }
});

//上にスクロールすると新しいメッセージを呼ぶ処理。
$('#messages').scroll(function() {
    if ($(this).scrollTop() === 0) {
        if (!$('#chatLoader').is(':visible')) {
            // 現在、メッセージの個数以前をメッセージを読み込む
            // ローディングアイコンを追加する
            let loader = $('<div id="chatLoader" class="text-center"><div class="spinner-grow spinner-grow-sm" role="status" /></div>')
            $('#messages').prepend(loader)
            loader.remove();
//            socket.emit('getMessages', $(this).children().length, function() {
//                // ローディングアイコンを削除する
//                loader.remove();
//            });
        }
    }
});

// UIの位置調整(キーボード出現時)
$('#message-form').on('focus', function() {
    if (CHAT_UTIL.isIOS()) {
        // メッセージ入力欄の位置指定
        document.querySelector('.fixed-bottom').style.bottom = 10000 + 'px';
        setTimeout(function() {
            document.querySelector('.fixed-bottom').style.bottom = 0 + 'px';
        },200);
    }
});

CHAT_UI.setNavigationPosition = function(y) {
    if (document.activeElement.id == 'message-form') {
        $('.navbar').css('position','absolute');
        $('.navbar').css('top', (y) + 'px');
        $('.tab-pane').css('margin-top', y + 'px');
        var height = document.getElementById("messages").getBoundingClientRect().height;
        $('.msg_history').css('height', height - y + 'px');
    } else if (document.activeElement.id == 'message-search') {
        $('.msg_history').css('height', '');
    }
}

CHAT_UI.resetNavigationPosition = function() {
    $('.navbar').css('position','');
    $('.navbar').css('top', '');
    $('.tab-pane').css('margin-top','');
    $('.msg_history').css('height', '');
}

// 端末の向きを記録(キーボード出現時にLandscapeModeと判定する対策)
var isLandscape;
CHAT_UI.setOrientation = function(isLandscapeMode) {
    if (isLandscapeMode == 'false') {
        $(".mesgs").removeClass("landscape_mesgs");
        isLandscape = false;
    } else {
        $(".mesgs").addClass("landscape_mesgs");
        isLandscape = true;
    }
}

CHAT_UI.sendMessage = function(e) {
    const messageTextBox = $('#messageInput');
    const message = messageTextBox.val().length > 0 ? encodeURIComponent(messageTextBox.val()) : "";
    messageTextBox.val('');

    if (message.length > 0) {
        socket.emit(
            'createMessage', { text: message + messageSeperator + messageType.TEXT }
            , 0
        );
    }
    $('.message_input_form').focus();
}
//メッセージ送信
$('#messageInput').on('keypress', function(event) {
    if (event.which == 13) {
        // Enterキーの処理
        $('#messageSend').click();
    }
});

// 写真アップロード
$('#imageInputButton').on('click', function() {
    $('#imageInputTag').click();
});

// 動画アップロード
$('#videoUploadButton').on('click', function() {
    $('#videoInputTag').click();
});

$('#imageInputTag').on('change', function() {
    $('#image-form').submit();
});

$('#videoInputTag').on('change', function() {
    $('#video-form').submit();
});

$('#image-form').on('submit', function(e) {
    e.preventDefault();
    const imageInputTag = $('#imageInputTag');
    const file = imageInputTag.prop('files')[0];
    if (file) {
        $('.overlay').addClass('active undismissable');
        $('.loader').addClass('active');
        CHAT_UI.showLoadingIndicator();
        var fd = new FormData($(this)[0]);

        //画像の大きさが500pixelより大きかったら、thumbnailを生成
        CHAT.createThumbnailAndUpload(file, function(resizeFile, thumbnailCreated) {
            if (resizeFile && thumbnailCreated) {
                //ただ、画像の大きさが500pixel以下の場合はthumbnailは生成されない
                fd.append('thumb', resizeFile)
            }

            // イメージをアップロード
            CHAT.uploadImage(fd)

        })
    }
});

$('#video-form').on('submit', function(e) {
    e.preventDefault();
    const videoInputTag = $('#videoInputTag');
    const file = videoInputTag.prop('files')[0];
    if (file) {
        $('.overlay').addClass('active undismissable');
        $('.loader').addClass('active');
        CHAT_UI.showLoadingIndicator();
        var fd = new FormData($(this)[0]);

        if(!file.type.includes("image")) { // video 保存
            CHAT.createVideoThumbnailAndUpload(file, function(resizeFile, thumbnailCreated) {
                if(resizeFile && thumbnailCreated) {
                    //ただ、画像の大きさが500pixel以下の場合はthumbnailは生成されない
                    fd.append('thumb', resizeFile)
                }
                CHAT.uploadImage(fd);
            })
            return;
        }
    }
});

/* --------------------------------------------------- */
/* Nav Bar Functions                                                                     */
/* --------------------------------------------------- */

$('#message-search').on('input', function(event) {
    // チャットキーワードを入力するとページ内にある単語をハイライトする。(mark.js 使用)
    if ($(this).val()) {
        $('.message_content').unmark();
        $('.message_content').mark($(this).val());

        if ($('[data-markjs=true]').length > 0) {
            // マーキングされている単語があった場合、最後の単語にスクロールを移動する。
            CHAT_UI.scrollToLastMarkedUnseen($(this).val());
        } else {
            // マーキングされている単語がない場合、下段にスクロールする。
            CHAT_UI.scrollToBottom();
        }
    } else {
        // チャットキーワードが空欄になるとマーキングを解除し、下段にスクロールする。
        $('.message_content').unmark();
        CHAT_UI.scrollToBottom();
    }
});

//次のマーキングされた単語にスクロールを移動する。
$('#pre-search').on('click', function(event) {
    CHAT_UI.scrollToLastMarkedUnseen(jQuery('#message-search').val());
});

// Exit Room
$('#exitRoom').on('click', function(event) {
    // 36174
    $("#exitRoomTitle").text(getLocalizedString("exitRoomTitle"));
    $("#exitRoomOk").text(getLocalizedString("yesTitle"));
    $("#noExit").text(getLocalizedString("cancelTitle"));

    $('#exitRoomConfirm').appendTo("body").modal({
        backdrop: 'static',
        keyboard: false
    })
    .on('click', '#exitRoomOk', function(e) {
        //loadingIndicatorを表示
        CHAT_UI.showLoadingIndicator();
        // チャットルームから退場する
        socket.emit('exitRoom');
        $('#dismiss').click();
        CHAT.saveRoomInfo('', '');
    });
});

// Side Bar
$('#sidebarCollapse').on('click', function() {
    // open sidebar
    $('#sidebar').addClass('active');
    // fade in the overlay
    $('.overlay').addClass('active');
    $('.collapse.in').toggleClass('in');
    $('a[aria-expanded=true]').attr('aria-expanded', 'false');
});

$('#dismiss, .overlay').on('click', function() {
    // hide sidebar
    $('#sidebar').removeClass('active');
    // hide overlay if dismissable
    $('.overlay:not(.undismissable)').removeClass('active');
});

//Invite User
//招待ボタンを押すとグループリストを持ってくる。(ボタンを動的に追加して微動作中)
$('#addUser').on('click', function(event) {
    //loadingIndicatorを表示
    CHAT_UI.showLoadingIndicator();
    let isInvite = true;
    CHAT.globalIsInvite = isInvite;
    socket.emit('getGroupList', isInvite);
});

//グループ画面での検索
$('#groupListKeyword').on('input', function(event) {
    // data-name値で当該キーワードが入っているグループのみを表示する。
    if ($(this).val()) {
        $('.group_list:not([data-name*="'+$(this).val()+'" i])').hide();
        $('.group_list[data-name*="'+$(this).val()+'" i]').show();
    } else {
        $('.group_list').show();
    }
});

$('#userListKeyword').on('input', function(event) {
    // data-name値で当該キーワードが入っているユーザーのみを表示する。
    if ($(this).val()) {
        $('.user_list:not([data-name*="'+$(this).val()+'" i])').hide();
        $('.user_list[data-name*="'+$(this).val()+'" i]').show();
    } else {
        $('.user_list').show();
    }
});

$('#selectListKeyword').on('input', function(event) {
    if ($(this).val()) {
        $('.select_user_list:not([data-name*="'+$(this).val()+'" i])').hide();
        $('.select_user_list[data-name*="'+$(this).val()+'" i]').show();
    } else {
        $('.select_user_list').show();
    }
});

/* ---------------------------------------------------------------------- */
/*                                                                                                                                                */
/*                                                                     Etc                                                                    */
/*                                                                                                                                                */
/* ---------------------------------------------------------------------- */

// Tab Open/Shown Event
$('a[data-toggle="pill"]').on('show.bs.tab', function(e) {
    var target = $(e.target).attr("href"); // e.target : activated tab
    switch(target) {
        case '#pills-chat':
            if (CHAT_UI.isLandscapeMode()) {
                $(".mesgs").addClass("landscape_mesgs");
            } else {
                $(".mesgs").removeClass("landscape_mesgs");
            }
            CHAT.globalIsInvite = true;
            $('.chatRoomIcon, .titleRoomName, #backButton').show();
            $('.roomListIcon, #userSelectionConfirmBtn, #newRoomName, #userSelectionDeleteBtn').hide();
            $('#homeButton').hide();

            $('.titleRoomName').text($('.titleRoomName').data('roomName'));
            $('#newRoomName').val('');
            $('#userSelectionLength').text('');
            CHAT.globalSelectedUserList = [];
            $('#bottomNav').hide();
            $('#backButton').off().on('click', function() {
                //loadingIndicatorを表示
                CHAT_UI.showLoadingIndicator();
                CHAT.saveRoomInfo();
                if (IS_ONLINE == 'true') {
                    socket.emit('leaveRoom', function() {
                        if (typeof(android) != "undefined") {
                            android.updateRoomList();
                        } else {
                            webkit.messageHandlers.updateRoomList.postMessage({"groupId":"0"});
                        }
                    });
                }
                CHAT_UI.refreshRoomList(chatRoomType.DM);
                CHAT_UI.dismissLoadingIndicator();
            });
            //loadingIndicatorを表示しない
            CHAT_UI.dismissLoadingIndicator();
            break;
        case '#pills-chatlist':
            $('.titleRoomName, #backButton').show();
            $('.chatRoomIcon, #backButton, #userSelectionConfirmBtn, #newRoomName, #userSelectionDeleteBtn').hide();
            $('#homeButton').show();
            $('#room-search').val('');
            $('#room-search').show();
            $('#room_list').show();
            // set Title
            let roomListTitle = getLocalizedString("roomListTitle")
            $('#bottomNav').show();
            $('.titleRoomName').text(roomListTitle);
            $('#newRoomName').val('');
            $('#userSelectionLength').text('');
            CHAT.globalSelectedUserList = [];

            break;
            
        case '#pills-contact':
            $('#myNamecard').html('');
            $('#homeButton').show();
            $("#backButton").hide();
            $('.titleRoomName').show();
            $('#myGroupArea').show();
            $('#allGroupArea').hide();
            $('#my_info').show();
            $('#bottomNav').show();
            break;

        case '#pills-user':
            $("#backButton").show();
            $("#userSelectionDeleteBtn").hide();
            $('#homeButton').hide();
            $('#bottomNav').hide();
            //loadingIndicatorを表示しない
            CHAT_UI.dismissLoadingIndicator();
            break;
        case '#pills-group':
            $("#backButton").show();
            $("#userSelectionDeleteBtn").hide();
            $('#homeButton').hide();
            $('#bottomNav').hide();
            //loadingIndicatorを表示しない
            CHAT_UI.dismissLoadingIndicator();
            break;
        case '#pills-confirm':
            $("#backButton").show();
            //loadingIndicatorを表示しない
            CHAT_UI.dismissLoadingIndicator();
            $('#homeButton').hide();
            $('#bottomNav').hide();
            $('.user_people').css("paddingLeft", "0px");
            break;
        case '#pills-communication':    // コミュニケーションのタブ
        case '#pills-setting':    // 設定のタブ
        case '#pills-profile':    // ユーザプロファイルのタブ
            $('#bottomNav').hide();
            $('.titleRoomName').show();
            $('.roomListIcon, .chatRoomIcon, #userSelectionConfirmBtn, #newRoomName, #userSelectionDeleteBtn').hide();
            $('#backButton').hide();
            break;
        default:
            $('.titleRoomName').show();
            $('.roomListIcon, .chatRoomIcon, #userSelectionConfirmBtn, #newRoomName, #userSelectionDeleteBtn').hide();
            $('#backButton').hide();
            break;
    }
});

// Tab Close/Hidden Event
$('a[data-toggle="pill"]').on('hide.bs.tab', function(e) {
    var target = $(e.target).attr("href"); // e.target : activated tab
    switch(target) {
        case '#pills-chat':
            $('#message-search').val('');
            break;
        case '#pills-chatlist':
            $('#room-search').val('');
            $('#room-search').show();
            break;
        case '#pills-group':
            $('#groupListKeyword').val('');
            break;
        case '#pills-contact':
            break;
        case '#pills-user':
            $('#userListKeyword').val('');
            break;
        case '#pills-confirm':
            $('#select_user_list').html('');
            $('#selectUserListKeyword').val('');
            $('.titleRoomName').show();
            $('.user_people').css("paddingLeft", "12%");
            break;
        case '#pills-communication':
        case '#pills-setting':
        case '#pills-profile':
            break;
        default:
            break;
    }
});

$('#pills-chat-tab').on('shown.bs.tab', function(e) {
    CHAT_UI.scrollToBottom();
});

$('#pills-user-tab').on('shown.bs.tab', function(e) {
    $('#userSelectionConfirmBtn').show();
});

$('#pills-confirm-tab').on('shown.bs.tab', function(e) {
    $('#userSelectionConfirmBtn').show();
    $('#userSelectionLength').text('');
    $('#userSelectionDeleteBtn').hide();
});

CHAT_UI.scrollToBottom = function() {
    const messages = $('.room_contents');
    const scrollHeight = messages.prop('scrollHeight');
    //messages.scrollTop(scrollHeight);
    $('html, body').animate({
        scrollTop: scrollHeight
    }, 500);
};

CHAT_UI.scrollToLastMarkedUnseen = function(value) {
    let target = $('[data-markjs=true]:not([data-seen=true])').last();
    let messages = $('#messages');
    if (target.length > 0) {
        messages.scrollTop(target.prop('offsetTop') - target.prop('offsetHeight') - messages.prop('offsetHeight') + target.parent().parent().height());
        target.attr('data-seen', true);
    } else {
        messages.scrollTop(0);
        $('.message_content').unmark();
        $('.message_content').mark(value);
    }
};

//loadingIndicatorを表示
CHAT_UI.showLoadingIndicator = function() {
    var h = $(window).height();
    $('#loader-bg ,#loader').height(h).css('display','block');
}

//loadingIndicatorを表示しない
CHAT_UI.dismissLoadingIndicator = function() {
    var h = $(window).height();
    $('#loader-bg ,#loader').height(h).css('display','none');
}

//画面の方向をcheck
CHAT_UI.isLandscapeMode = function() {
    if (CHAT_UTIL.isMobile()) {
        return false;
    }

    return $(window).width() > $(window).height()
}

CHAT_UI.setConfirmButtonEvent = function(isInvite) {
    let titleText = isInvite ? getLocalizedString("inviteUsersSubtitle") : getLocalizedString("createRoomSubtitle")
    let invitedUserText = getLocalizedString("invitedUser")
    if (!isInvite) {
        $('#newRoomName').show();
    }

    $('#userSelectionConfirmBtn').off().on('click', function(event) {
        //loadingIndicatorを表示
        CHAT_UI.showLoadingIndicator();
        CHAT_UI.showConfirmView(isInvite);
    });

    CHAT_UI.showConfirmView(isInvite);
    $('#inviteStatus').text(titleText);
    $('#invitedUsers').text(invitedUserText);
    $('#pills-confirm-tab').tab('show');
}

//ConfirmView initialize
CHAT_UI.showConfirmView = function(isInvite) {
    const template = $('#user-template').html();
    $('#select_user_list').html('');

    CHAT.globalSelectedUserList.forEach(function(user) {
        let html = Mustache.render(template, {
            id: user.shopMemberId,
            profileImage: user.profileImagePath,
            name: user.loginId
        });
        // TODO 次のコミットに参考事項
        // チャットルーム開設画面で参加ユーザー削除用チェックロジックが残っているので
        // 影響テスト後、削除予定。 kang-dh
        let obj = $(jQuery.parseHTML(html)).on('click',function() {
            $(this).find('.userCheckBox').toggleClass('active');
        });

        $('#select_user_list').append(obj);
    });

    let roomListTitle = getLocalizedString("createRoomTitle")
    $('.titleRoomName').text(roomListTitle)

    // Rotate
    if (CHAT_UI.isLandscapeMode()) {
        $(".user_list").addClass("col-6").removeClass("col-12");
        $(".squareBoxContent span").addClass("landscape_span");
    }

    $('#backButton').off().on('click', function() {
        //loadingIndicatorを表示
        CHAT_UI.showLoadingIndicator();
        socket.emit('getGroupList', isInvite)
    });

    $("#userSelectionConfirmBtn").off().on('click', function() {
        if (isInvite) {
            let userIdList = jQuery.makeArray($('#select_user_list .user_list').find('.userCheckBox')).map(function(e) {
                return e.dataset.id;
            });
            // ユーザーの名前(login id)リスト。
            let loginIdList = jQuery.makeArray($('#select_user_list .user_list').find('.userCheckBox')).map(function(e) {
                return e.dataset.name;
            });

            if(userIdList.length > 0 && loginIdList.length > 0) {
                //loadingIndicatorを表示
                CHAT_UI.showLoadingIndicator();
                socket.emit('inviteUsers', userIdList, loginIdList, function() {
                    $("#userSelectionDeleteBtn").hide();
                    $('#pills-chat-tab').tab('show');
                });
            }
        } else {
            if ($('#select_user_list .user_list').find('.userCheckBox').length > 0) {
                // #36130に対応
                const trimmedRoomName = $('#newRoomName').val().trim()
                if (trimmedRoomName.length == 0) {

                    // loadingIndicatorを表示
                    CHAT_UI.showLoadingIndicator();
                    let userIdList = jQuery.makeArray($('#select_user_list .user_list').find('.userCheckBox')).map(function(e) {
                        return e.dataset.id;
                    });
                    let userNameList = jQuery.makeArray($('#select_user_list .user_list').find('.userCheckBox')).map(function(e) {
                        return e.dataset.name;
                    });

                    //TODO DB作業が終わったら自分のユーザ名を表示するかを判断し、修正予定。
                    // 参加ユーザ名でルーム名を生成
                    let newRoomName = CHAT.globalLoginParameter.loginId + ',' + userNameList.join(',');

                    // ルーム名のURIencodingを行う
                    //const encodedRoomName = encodeURIComponent(newRoomName);



                    //todo android create room api
                    if (typeof(android) != "undefined") {
                        android.createChatRoom("1", userIdList.join(','), newRoomName, makeRoomFlg.MAKE_ROOM);
                    } else {
                        webkit.messageHandlers.createChatRoom.postMessage({"roomType": "1", "userIdList": userIdList.join(','), "roomName": newRoomName, "screenFlg": makeRoomFlg.MAKE_ROOM});
                    }


                    /*socket.emit('createNewRoom', userIdList, encodedRoomName, function(newRoomId) {
                        socket.emit('joinRoom', newRoomId, newRoomName, function() {
                            CHAT.saveRoomInfo(newRoomId, newRoomName);
                            $('#messages').html('');
                            $('.titleRoomName').text(newRoomName).data('roomName', newRoomName);
                            $("#userSelectionDeleteBtn").hide();
                            $('#pills-chat-tab').tab('show');
                        });
                    });*/

                    /*socket.on('createNewRoom', (shopMemberIdList, newRoomName, callback) => {
                        const user = onlineUsers.getUser(socket.id)
                        if(user) {
                            var loginIdListObj = new Object();
                            var newRoomNameObj = new Object();

                            loginIdListObj.type = 'loginIdList'
                            loginIdListObj.value = shopMemberIdList

                            newRoomNameObj.type = 'newRoomName'
                            newRoomNameObj.value = newRoomName

                                    var path = httpRequest.makeChatRoomManageUrlPath(user.shopName, constant.ROOM_CREATENEWROOM, user.sid, loginIdListObj, newRoomNameObj)
                                    winston.info('path' + path)
                                    httpRequest.readResult(path, (res) =>{
                                        const error = serverErrorHandler(res)
                                        if(error.errorFlag) {
                                            winston.error("Failed to [createNewRoom] process.")
                                            socket.emit("showServerError", error.errorMessage);
                                            return;
                                        }
                                        winston.info('create new room from server '+ util.inspect(res, false, null, false))
                                        callback(res.roomId)

                                        // ユーザーリストをアップデートする
                                        socket.emit(res.roomId).emit('updateUserList', res.userList, [user.shop_member_id])
                                    })
                                } else {
                                    socket.emit("retryJoinProcess")
                                    //join process
                                }
                    })*/





                } else if(trimmedRoomName.includes(';') || trimmedRoomName.includes('/') || trimmedRoomName.includes('?') || trimmedRoomName.includes(':') || trimmedRoomName.includes("@")
                     || trimmedRoomName.includes('&') || trimmedRoomName.includes('=') || trimmedRoomName.includes("+") || trimmedRoomName.includes('$') || trimmedRoomName.includes(",") || trimmedRoomName.includes('-')
                     || trimmedRoomName.includes('_') || trimmedRoomName.includes('.') || trimmedRoomName.includes('!') || trimmedRoomName.includes('~') || trimmedRoomName.includes('*') || trimmedRoomName.includes("\'")
                     || trimmedRoomName.includes('(') || trimmedRoomName.includes(')') || trimmedRoomName.includes('#') || trimmedRoomName.includes("\\") || trimmedRoomName.includes("\"") || trimmedRoomName.includes("`")) {
                    // #36147
                    // #36174
                    $("#customAlertTitle").text(getLocalizedString("invalidCharacter"));
                    $("#customAlertOk").text(getLocalizedString("yesTitle"));

                    $('#customAlert').appendTo("body").modal({
                        backdrop: 'static',
                        keyboard: false
                    })
                    .on('click', '#customAlertOk', function(e) {
                    });
                } else if (trimmedRoomName.length > 20) {
                    // #36142
                    var inputText = $('#newRoomName').val().trim(); // #36142 文字列の前又は後の空白文字列を削除

                    // #36174
                    $("#customAlertTitle").text(getLocalizedString("nameTooLong"));
                    $("#customAlertOk").text(getLocalizedString("yesTitle"));

                    $('#customAlert').appendTo("body").modal({
                        backdrop: 'static',
                        keyboard: false
                    })
                    .on('click', '#customAlertOk', function(e) {
                        $('#newRoomName').val(inputText.substr(0, $('#newRoomName').prop("maxlength")));
                    });

                } else {
                    //loadingIndicatorを表示
                    CHAT_UI.showLoadingIndicator();
                    let userIdList = jQuery.makeArray($('#select_user_list .user_list').find('.userCheckBox')).map(function(e) {
                        return e.dataset.id;
                    });

                    // ルーム名のtrimmingした後、URIencodingを行う
                    const encodedRoomName = encodeURIComponent(trimmedRoomName);
                    if (typeof(android) != "undefined") {
                        android.createChatRoom("1", userIdList.join(','), encodedRoomName, makeRoomFlg.MAKE_ROOM);
                    } else {
                        webkit.messageHandlers.createChatRoom.postMessage({"roomType": "1", "userIdList": userIdList.join(','), "roomName": newRoomName, "screenFlg": makeRoomFlg.MAKE_ROOM});
                    }
                }
            }
        }
    });

    $("#userSelectionDeleteBtn").hide();

    $("#userSelectionDeleteBtn").off().on('click', function() {
        // #36174
        $("#customConfirmTitle").text(getLocalizedString("memberDeleteTitle"));
        $("#customConfirmOk").text(getLocalizedString("roomDelete"));
        $("#customAlertCancel").text(getLocalizedString("cancelTitle"));

        $('#customConfirm').appendTo("body").modal({
            backdrop: 'static',
            keyboard: false
        })
        .on('click', '#customConfirmOk', function(e) {
            CHAT_UI.deleteButtonAction(isInvite);
        });

    });
}

CHAT_UI.deleteButtonAction = function(isInvite) {
    //配列の整理
    jQuery.makeArray($('#select_user_list .user_list').find(".userCheckBox.active")).map(function(e) {
        CHAT.globalSelectedUserList = CHAT.globalSelectedUserList.filter(function(element) {
            return e.dataset.name != element.loginId;
        });
    });

    CHAT_UI.showConfirmView(isInvite)
    $('#select_user_list .user_list').find('.userCheckBox').show();
}

CHAT_UI.htmlElementTextInitialize = function(languageCode) {
    moment.locale(languageCode);
    setLanguage(languageCode);
    $(".titleRoomName").text(getLocalizedString("roomListTitle"));
    $("#message-form").attr("placeholder", getLocalizedString("chat_placeholder"));
    $("#message-search").attr("placeholder",getLocalizedString("chat_search_placeholder"));
    $("#exitRoom").text(getLocalizedString("exitRoom")).append("<i class='fas fa-door-open'></i>")
    $("#participants").text(getLocalizedString("participants"))

    //$("#fileUploadButton").text(getLocalizedString("photo"))
    //$("#fileUploadButton2").text(getLocalizedString("video"))

    $("#okayLabel").text(getLocalizedString("okayLabel"))
    $("#completeLabel").text(getLocalizedString("completeLabel"))
    $("#thankLabel").text(getLocalizedString("thankLabel"))
    $("#startToWorkLabel").text(getLocalizedString("startToWorkLabel"))


    $("#groupListKeyword").attr("placeholder", getLocalizedString("groupSearch"))
    $("#contactListKeyword").attr("placeholder", getLocalizedString("contactSearch"))
    $("#room-search").attr("placeholder",$("#room-search").attr("placeholder")+getLocalizedString("room_search_placeholder"));
    $("#userListKeyword").attr("placeholder", getLocalizedString("userSearch"))
    $("#newRoomName").attr("placeholder", getLocalizedString("newRoomName"))

    $("#dmBtn").text(getLocalizedString("directMessageChatRoom"))
    $("#groupBtn").text(getLocalizedString("groupChatRoom"))

    $("#myGroupBtn").text(getLocalizedString("myGroup"))
    $("#allGroupBtn").text(getLocalizedString("allGroup"))

    //$("#groupPathSeperator").text(getLocalizedString("groupPath"))
    //$("#moveBtnSeperator").text(getLocalizedString("quickBtn"))
    //$("#rootGroupBtn").text(getLocalizedString("returnToRootGroup"))
    //$("#parentGroupBtn").text(getLocalizedString("returnToParentGroup"))
    //$("#childGroupSeperator").text(getLocalizedString("childGroup"))
    //$("#groupUserSeperator").text(getLocalizedString("groupUser"))




    $("#favorite-seperator").text(getLocalizedString("favorite"))
    $("#mygroup-seperator").text(getLocalizedString("mygroup"))

    $(".ttl_archive").text(getLocalizedString("archive"))
    $(".ttl_detail").text(getLocalizedString("detail"))
    $("#archiveFileName").text(getLocalizedString("archiveFileName"))
    $("#archiveInsertDate").text(getLocalizedString("archiveInsertDate"))
    $("#archiveRoomName").text(getLocalizedString("archiveRoomName"))
    $("#archiveSaveUser").text(getLocalizedString("archiveSaveUser"))
    $("#archiveAttendUser").text(getLocalizedString("archiveAttendUser"))
}

// 画像の読み込みが全て終わったタイミングでコールバック実行
// FIXME 追加読み込みの場合は差分の画像のみ監視すべきだが、現状新規入室時にしか対応出来ていない。
CHAT_UI.waitForLoadingImage = function(div, callback) {
    var imgs = div.find("img");
    var count = imgs.length;
    if (count==0)
        callback();
    var loaded = 0;
    imgs.one( "load" , function( e ) {
        // イメージが読み込まれた
        loaded++;
        if ( loaded === count ) {
            callback();
        }
    }).each( function() {
        if ( this.complete || this.readyState === readyState.COMPLETED ) {
            $(this).trigger("load");
        }

    });
}

$('#contactButton').on('click', function(event) {
    CHAT_UI.refreshContactScreen();
});

$('#chatButton').on('click', function(event) {
    CHAT_UI.refreshRoomList(chatRoomType.DM);
});

CHAT_UI.refreshContactScreen = function() {
    CHAT_UI.showLoadingIndicator();
    $('#userNameCard').modal('hide');
    $('#favoriteList').html('');
    $('#myGroupList').html('');
    //画面タイトル設定
    let contactListTitle = getLocalizedString("contactListTitle");
    $('#title').text(contactListTitle);


    // グループの様式を読み込む
    var groupTemplate;
    $.get({ url: "./template/template_group_list.html", async: false }
      , function(text) {
        groupTemplate = text;
    });

    // ユーザの様式を読み込む
    var userTemplate;
    $.get({ url: "./template/template_user_list.html", async: false }
      , function(text) {
        userTemplate = text;
    });

    var myNamecardTemplate;
    $.get({ url: "./template/template_my_name_card.html", async: false }
      , function(text) {
        myNamecardTemplate = text;
    });

    var groupUserTemplate;
    $.get({ url: "./template/template_group_user_list.html", async: false }
      , function(text) {
        groupUserTemplate = text;
    });

    if (IS_ONLINE == 'true') {
        if (typeof(android) != "undefined") {
            android.updateGroupInfo('0');
            android.updateMyInfo();
            android.updateGroupUser();
            android.updateFavorite();
        } else {
            webkit.messageHandlers.updateGroupInfo.postMessage("0");
            webkit.messageHandlers.updateMyInfo.postMessage({});
            webkit.messageHandlers.updateGroupUser.postMessage({});
            webkit.messageHandlers.updateFavorite.postMessage({});
        }
    }

    var myInfo = CHAT_DB.getMyInfo();
    myInfo.profileImagePath = CHAT.getProfileImgUrl(myInfo.profileUrl)



    let myNamecardHtml = Mustache.render(myNamecardTemplate, {
        loginId: myInfo.shopMemberId,
        profileImage: myInfo.profileImagePath,
        name: myInfo.shopMemberName,
        groupPathList: myInfo.groupPathList
    });
    let myNamecardObj = $(jQuery.parseHTML(myNamecardHtml)).on('click', function() {

    });

    $('#myProfileModal').html(myNamecardObj);
    $('#myName').text(myInfo.shopMemberName);
    $('#myImg').attr('src',myInfo.profileImagePath);

    //お気に入りグループ取得。
    var favoriteGroupList = CHAT_DB.getFavoriteGroups();
    favoriteGroupList.forEach(function(favoriteGroup) {
        let html = Mustache.render(groupTemplate, {
            name: favoriteGroup.groupName,
            id: favoriteGroup.groupId,
            isFavorite: true
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function() {
        });
        $('#favoriteList').append(obj);
    })
    //お気に入りユーザ取得。
    var favoriteUserList = CHAT_DB.getFavoriteUsers();
    favoriteUserList.forEach(function(favoriteUser) {
        favoriteUser.profileUrl = CHAT.getProfileImgUrl(favoriteUser.profileUrl);
        favoriteUser.isFavorite = true;
    });
    let html = Mustache.render(userTemplate, {
        userList: favoriteUserList
    });
    let obj = jQuery.parseHTML(html);
    $('#favoriteList').append(obj);

    var myGroupList = CHAT_DB.getMyGroupUsers();
    myGroupList.forEach(function(myGroup) {

        myGroup.groupUserList.forEach(function(groupUser) {
            groupUser.profileUrl = CHAT.getProfileImgUrl(groupUser.profileUrl)
        })
        let html = Mustache.render(groupUserTemplate, {
            groupName: myGroup.groupName,
            groupUserList: myGroup.groupUserList
        });
        let obj = $(jQuery.parseHTML(html)).on('click', function() {
        });

        $('#myGroupList').append(obj);
    })
    CHAT_UI.dismissLoadingIndicator();
}

CHAT_UI.refreshRoomList = function(roomType) {
    var beforeRoomType;
    if (typeof(android) != "undefined") {
        beforeRoomType = android.getBeforeRoomType();
    } else {
        beforeRoomType = CHAT_DB.getBeforeRoomType();
    }
    if (beforeRoomType != null) {
        roomType = beforeRoomType;
        if (typeof(android) != "undefined") {
            android.clearBeforeRoomType();
        } else {
            webkit.messageHandlers.clearBeforeRoomType.postMessage({});
        }
    }
    CHAT_UI.showLoadingIndicator();
    if (roomType == chatRoomType.DM) {
        $('#tabDM').prop('checked', true);
    } else {
        $('#tabGroup').prop('checked', true);
    }

    if (IS_ONLINE == 'true') {
        if (typeof(android) != "undefined") {
            android.updateRoomList();
        } else {
            webkit.messageHandlers.updateRoomList.postMessage({});
        }
    }
    var rooms = CHAT_DB.getRoomList(roomType, null);
    CHAT.globalIsInvite = false;
    // #36146に対応
   $('#groupChatList').empty();
   $('#dmChatList').empty();
    let roomListTitle = getLocalizedString("roomListTitle");
    $('#chatTitle').text(roomListTitle);
    if (rooms.length === 0) {
        // 検索結果がない場合のメッセージを追加
        let emptyListString = getLocalizedString("roomListEmptyString")
        switch(roomType) {
            case chatRoomType.GROUP:
                $('#groupChatList').append(`<center class="text-secondary">${emptyListString}</center>`);
                break;
            case chatRoomType.DM:
                $('#dmChatList').append(`<center class="text-secondary">${emptyListString}</center>`);
                break;
            default:
        }
    }

    var template;
    $.get({ url: "./template/template_room_list.html", async: false }
      , function(text) {
        template = text;
    });
    rooms.forEach(function(room) {
        room.profileImagePath = ASSET_PATH + 'images/user-profile.png'
        if (room.message) {
            room.message = room.message.toString()
        } else {
            room.message = getLocalizedString("noMessages")
        }
        var displayMsg;
        //TODO 協業の場合処理追加必要
        if (room.messageType == messageType.TEXT || room.messageType == messageType.TEXT) displayMsg = room.message;
        if (room.messageType == messageType.IMAGE || room.messageType == messageType.VIDEO) displayMsg = getLocalizedString("image");
        var attendUserName = [];
        room.attendUsers.forEach(function(user) {
            user.profileUrl = CHAT.getProfileImgUrl(user.profileUrl);
            attendUserName.push(user.shopMemberName);
        });
        var thumbnailCount = room.attendUsers.length > 4 ? 4 : room.attendUsers.length;
        if (room.chatRoomName == "") {
            room.chatRoomName = attendUserName.join(', ');
        }
        let html = Mustache.render(template, {
            thumbnailCount: thumbnailCount,
            roomName: room.chatRoomName,
            roomId: room.chatRoomId,
            profileImage: room.profileImagePath,
            lastMessage: displayMsg ,
            time: room.insertDate ? CHAT_UTIL.formatDate(room.insertDate).createdAt : '',
            unreadMsgCnt: room.unreadCount == 0 ? '' : room.unreadCount,
            userCnt: room.attendUsers.length + 1,
            attendUsers: room.attendUsers
        });
        // Click event
        let obj = $(jQuery.parseHTML(html)).on('click', function() {
           /* let roomId = $(this).data('roomId');
            let roomName = $(this).data('roomname');
            CHAT_UI.joinRoom(roomId,roomName);*/
            //TODO ルームに入る処理追加必要
        });
        // ルームグループごとに追加。
        switch(roomType) {
            case chatRoomType.GROUP:
                $('#groupChatList').append(obj);
                break;
            case chatRoomType.DM:
                $('#dmChatList').append(obj);
                break;
            default:
        }
    });

    if (CHAT_UI.isLandscapeMode()) {
        $(".chat_list").removeClass("col-12").addClass("col-6");
    }
    console.log('DONE');
    CHAT_UI.dismissLoadingIndicator();
};

CHAT_UI.joinRoom = function(roomId,roomName) {
    //native側に入場対象のroomId,roomNameを保存。(ルーム詳細画面初期化の時に使用。)
    if (typeof(android) != "undefined") {
        android.joinRoom(roomId,roomName);
    } else {
        webkit.messageHandlers.joinRoom.postMessage({"roomId": roomId, "roomName": roomName});
    }
};

CHAT_UI.loadMessages = function(roomId, roomName) {
    if (IS_ONLINE == 'true') {
        CHAT_UI.refreshForOnline();
        if (typeof(android) != "undefined") {
            android.updateMessages(roomId);
        } else {
            webkit.messageHandlers.updateMessages.postMessage(roomId);
        }
    } else {
        CHAT_UI.refreshForOffline();
    }
    var roomType;
    if (typeof(android) != "undefined") {
        roomType = android.getRoomType();
    } else {
        roomType = CHAT_DB.getRoomType();
    }
    if (roomType == chatRoomType.DM) {
        $('#roomMenu').removeClass('none');
    }
    var messages = CHAT_DB.getMessages(roomId);
    var usersInRoom = CHAT_DB.getUsersInRoom(roomId);

    $('#roomTitle').text(roomName).data('roomName', roomName);
    let jQueryMessages = $('#messages');
    // スクロールの変化を防ぐため以前画面の高さを保存する
    let beforeHeight = jQueryMessages.prop('scrollHeight');
    // メッセージ文字列の生成
    let workVal = "";
    var userTemplate;
    $.get({ url: "./template/template_user_list.html", async: false }
      , function(text) {
        userTemplate = text;
    });
    var userMessageTemplate;
    $.get({ url: "./template/template_user_message.html", async: false }
      , function(text) {
        userMessageTemplate = text;
    });
    var myMessageTemplate;
    $.get({ url: "./template/template_my_message.html", async: false }
      , function(text) {
        myMessageTemplate = text;
    });
    var systemMessageTemplate;
    $.get({ url: "./template/template_system_message.html", async: false }
      , function(text) {
        systemMessageTemplate = text;
    });
    var topUserListTemplate;
    $.get({ url: "./template/template_chatroom_user_list.html", async: false }
      , function(text) {
        topUserListTemplate = text;
    });
    var filterUserListTemplate;
    $.get({ url: "./template/template_chatroom_user_filter_list.html", async: false }
      , function(text) {
        filterUserListTemplate = text;
    });


    usersInRoom.forEach(function(user) {
        user.profileUrl = CHAT.getProfileImgUrl(user.profileUrl);
    });
    let html = Mustache.render(topUserListTemplate, {
         userList: usersInRoom
    });
    let obj = jQuery.parseHTML(html);
    $('#user_list').append(obj);

    let filterHtml = Mustache.render(filterUserListTemplate, {
         userList: usersInRoom
    });
    let filterObj = jQuery.parseHTML(filterHtml);
    $('#filter').append(filterObj);

    var checkBeforeDate = "";
    var beforeDate = "";
    messages.forEach(function(message) {
        let template = userMessageTemplate;
        if (message.shopMemberId == CHAT.globalLoginParameter.shopMemberId) {
             template = myMessageTemplate;
        }
        if (message.messageType == messageType.SYSTEM) {
            template = systemMessageTemplate;
        }
        let messageTime = CHAT_UTIL.formatDate(message.insertDate);
        // ユーザの様式を読み込む

        if (message.profileUrl) {
            message.profileUrl = CHAT.getProfileImgUrl(message.profileUrl)
        } else {
            message.profileUrl = CHAT.getProfileImgUrl("")
        }

         // #36147
         message.message = message.message.toString();
         var replacePath = message.message;
         replacePath = replacePath.replaceAll('?fileName=', '?sid=' + CHAT.globalLoginParameter.sid + '&fileName=');
         message.message = replacePath;
        /* if (message.message contain) {
         }*/

         var isToday = false;
         if (messageTime.createdAt.includes(':')) {
            isToday = true;
         }
         if (messageTime.createdAtDay != checkBeforeDate && checkBeforeDate != "") {
            let messageDay = CHAT_UTIL.systemDay(beforeDate);
            let html = Mustache.render(systemMessageTemplate, {
                year: messageDay.year + getLocalizedString('year'),
                month: messageDay.month + getLocalizedString('month'),
                day: messageDay.day + getLocalizedString('day'),
                dow: CHAT_UTIL.findDow(messageDay.dow)

            });
             workVal = html + workVal;
         }
         checkBeforeDate = messageTime.createdAtDay;
         beforeDate = message.insertDate;

         let html = Mustache.render(template, {
             text: message.message,
             from: message.loginId,
             shopMemberId: message.shopMemberId,
             profileImage: message.profileUrl,
             createdAtDay: messageTime.createdAtDay,
             createdAtTime: messageTime.createdAtTime,
             unreadCount: message.unreadCount,
             isToday: isToday
         });
         html = message.message.includes('attachedImages') || message.message.includes('attachedVideos') ? CHAT_UTIL.htmlDecode(html) : html;
         workVal = html + workVal;
    })

    // メッセージの画面描画
    jQueryMessages.prepend(workVal);
    if (beforeHeight !== 0) {
        // 追加のメッセージ読み込み時は読み込み前のスクロール位置を維持
        setTimeout(function() {
            jQueryMessages.scrollTop(jQueryMessages.prop('scrollHeight') - beforeHeight);
        }, 400);
    } else {
        // 新規に入室の場合は最下部へスクロール
        CHAT_UI.waitForLoadingImage(jQueryMessages, CHAT_UI.scrollToBottom);
        // タブレット等、画面サイズが大きい場合、スクロール出来なくならないよう追加で10件メッセージを取得
        if ($(window).height() > jQueryMessages.height()) {
            $('#messages').scroll();
        }
    }
    CHAT_UI.waitForLoadingImage(jQueryMessages, CHAT_UI.scrollToBottom);
    // ユーザ削除ボタン表示しない
    $("#userSelectionDeleteBtn").hide();
    CHAT_UI.scrollToBottom();
};


$('#tabDM').on('click', function(e) {
    CHAT_UI.refreshRoomList(chatRoomType.DM);
});

$('#tabGroup').on('click', function(e) {
    CHAT_UI.refreshRoomList(chatRoomType.GROUP);
});


$('#tabAllGroup').on('click', function(e) {
    CHAT_UI.refreshAllGroupSearch('0');
});

$('#tabMyGroup').on('click', function(e) {
    $('#contactSearch').attr('placeholder', getLocalizedString('userSearch'));
    CHAT_UI.refreshContactScreen();
});

$('#tabMyGroupOnMakeRoom').on('click', function(e) {
    CHAT_UI.refreshMyGroupForMakeRoom();
});

$('#tabAllGroupOnMakeRoom').on('click', function(e) {
    CHAT_UI.refreshAllGroupForMakeRoom('0');
});

$('#tabMyGroupOnAddUser').on('click', function(e) {
    CHAT_UI.refreshMyGroupForAddUser();
});

$('#tabAllGroupOnAddUser').on('click', function(e) {
    CHAT_UI.refreshAllGroupForAddUser('0');
});
$('#makeRoomConfirmBtn').on('click', function(e) {
    if (typeof(android) != "undefined") {
        android.saveSelectedUserList(CHAT.globalSelectedUserList.join(","));
    } else {
        var userList = CHAT.globalSelectedUserList.join(",");
        webkit.messageHandlers.saveSelectedUserList.postMessage(userList);
    }
    $('#makeRoomForm').submit();
});

$('#addUserConfirmBtn').on('click', function(e) {
    if (typeof(android) != "undefined") {
        android.saveSelectedUserList(CHAT.globalSelectedUserList.join(","));
    } else {
        var userList = CHAT.globalSelectedUserList.join(",");
        webkit.messageHandlers.saveSelectedUserList.postMessage(userList);
    }
    $('#addUserForm').submit();
});

CHAT_UI.roomDisplayOff = function() {
    if (typeof(android) != "undefined") {
        android.roomDisplayOff();
    } else {
        webkit.messageHandlers.roomDisplayOff.postMessage({});
    }
}

CHAT_UI.favoriteUserChange = function(shopMemberId, star) {
    if ($(star).hasClass('active')) {
        CHAT_UI.removeFavoriteUser(shopMemberId);
    } else if ($(star).hasClass('disable')) {
        CHAT_UI.insertFavoriteUser(shopMemberId);
    }
}

CHAT_UI.favoriteGroupChange = function(groupId, star) {
    if ($(star).hasClass('active')) {
        CHAT_UI.removeFavoriteGroup(groupId);
    } else if ($(star).hasClass('disable')) {
        CHAT_UI.insertFavoriteGroup(groupId);
    }
}

CHAT_UI.removeFavoriteUser = function(shopMemberId) {
    CHAT_UI.showLoadingIndicator();
    $('#userNameCard').modal('hide');
    $('#myNameCard').modal('hide');
    var result;
    if (typeof(android) != "undefined") {
        result = android.removeFavoriteUser(shopMemberId);
    } else {
        result = CHAT_DB.removeFavoriteUser(shopMemberId);
    }
    if (!result) {
        $('.shopmember_'+shopMemberId).addClass('active');
        $('.shopmember_'+shopMemberId).removeClass('disable');
    } else {
        $('.shopmember_'+shopMemberId).removeClass('active');
        $('.shopmember_'+shopMemberId).addClass('disable');
    }
    CHAT_UI.dismissLoadingIndicator();
};

CHAT_UI.insertFavoriteUser = function(shopMemberId) {
    $('#userNameCard').modal('hide');
    $('#myNameCard').modal('hide');
    var result;
    if (typeof(android) != "undefined") {
        result = android.addFavoriteUser(shopMemberId);
    } else {
        result = CHAT_DB.addFavoriteUser(shopMemberId);
    }
    if (!result) {
        $('.shopmember_'+shopMemberId).addClass('disable');
        $('.shopmember_'+shopMemberId).removeClass('active');
        CHAT_UI.dismissLoadingIndicator();
        return;
    } else {
        $('.shopmember_'+shopMemberId).removeClass('disable');
        $('.shopmember_'+shopMemberId).addClass('active');
    }
    CHAT_UI.dismissLoadingIndicator();
};

CHAT_UI.removeFavoriteGroup = function(groupId) {
    if (typeof(android) != "undefined") {
        android.removeFavoriteGroup(groupId);
    } else {
        webkit.messageHandlers.removeFavoriteGroup.postMessage(groupId);
    }
    $('.group_'+groupId).removeClass('active');
    $('.group_'+groupId).addClass('disable');
    CHAT_UI.dismissLoadingIndicator();
};

CHAT_UI.insertFavoriteGroup = function(groupId) {
    CHAT_UI.showLoadingIndicator();
    var result;
    if (typeof(android) != "undefined") {
        result = android.addFavoriteGroup(groupId);
    } else {
        result = CHAT_DB.addFavoriteGroup(groupId);
    }
    if (!result) {
        $('.group_'+groupId).addClass('disable');
        $('.group_'+groupId).removeClass('active');
        CHAT_UI.dismissLoadingIndicator();
        return;
    } else {
        $('.group_'+groupId).removeClass('disable');
        $('.group_'+groupId).addClass('active');
    }
    CHAT_UI.dismissLoadingIndicator();
};

//全グループ検索画面表示。
CHAT_UI.refreshAllGroupSearch = function(paramGroupId) {
    var groupId = paramGroupId;
    CHAT_UI.showLoadingIndicator();
    $('#userNameCard').modal('hide');
    $('.cancel').addClass('none');
    $('.search_form input').removeClass('focus');
    $('.search_form input').val('');
    $('.search_form form').removeClass();
    $('.content').removeClass('none');
    $('.overlay_src_msg').empty();
    $('#contactSearch').attr('placeholder', getLocalizedString('searchUserAndGroup'));
    $('#tabAllGroup').prop('checked', true);
    
    //オンライン状態であればサーバから情報更新。
    if (IS_ONLINE == 'true') {
        if (typeof(android) != "undefined") {
            android.updateGroupInfo(groupId);
        } else {
            webkit.messageHandlers.updateGroupInfo.postMessage(groupId);
        }
    }

    //画面エリアを初期化。
    $('#rootGroupBtn').off();
    $('#parentGroupBtn').off();
    $('#childGroupListArea').html('');
    $('#userInGroupList').html('');
    $('#groupPathArea').html('');

    //DBからグループ情報を取得。
    var result = CHAT_DB.getGroupInfo(groupId);

    //上位グループ、トップグループ遷移ボタンのイベント追加。
    if (typeof result.parentGroupId !== 'undefined') {
        $('#parentGroupBtn').on('click', function() {
            CHAT_UI.refreshAllGroupSearch(result.parentGroupId);
        });
    }
    if (typeof result.rootGroupId !== 'undefined') {
        if (paramGroupId == 0) { groupId = result.rootGroupId }
        $('#rootGroupBtn').on('click', function() {
            CHAT_UI.refreshAllGroupSearch(result.rootGroupId);
        });
    }
    if (groupId == result.rootGroupId || paramGroupId == '0') {
        $('#rootGroupArea').addClass('none');
        $('#parentGroupArea').addClass('none');
    } else {
        $('#rootGroupArea').removeClass('none');
        $('#parentGroupArea').removeClass('none');
    }
    //該当グループのパースを表示。
    var groupPathTemplate;
    $.get({ url: "./template/template_group_path.html", async: false }
      , function(text) {
        groupPathTemplate = text;
    });

    result.groupPathList.forEach(function(groupPath) {
        let html = Mustache.render(groupPathTemplate, {
            name: groupPath.groupName,
            id: groupPath.groupId
        });
        let obj = jQuery.parseHTML(html);
        $('#groupPathArea').append(obj);
    })

    //該当グループの下位グループ表示。
    var groupTemplate;
    $.get({ url: "./template/template_group_list.html", async: false }
      , function(text) {
        groupTemplate = text;
    });
    result.childGroupList.forEach(function(childGroup) {
        let html = Mustache.render(groupTemplate, {
            name: childGroup.groupName,
            id: childGroup.groupId,
            isFavorite: childGroup.isFavorite
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function() {

        });
        $('#childGroupListArea').append(obj);
    })

    //該当グループの所属ユーザを表示。
    var userTemplate;
    $.get({ url: "./template/template_user_list.html", async: false }
      , function(text) {
        userTemplate = text;
    });
    result.groupUserList.forEach(function(groupUser) {
        groupUser.profileUrl = CHAT.getProfileImgUrl(groupUser.profileUrl)
    })
    let html = Mustache.render(userTemplate, {
        userList: result.groupUserList
    });
    let obj = jQuery.parseHTML(html);
    $('#userInGroupList').append(obj);
    CHAT_UI.dismissLoadingIndicator();
}



CHAT_UI.startChat = function(userShopMemberId,userName) {
    CHAT_UI.showLoadingIndicator();
    var userIdList = [];
    userIdList.push(userShopMemberId);

    // 参加ユーザ名でルーム名を生成
    let newRoomName = CHAT.globalLoginParameter.loginId + ',' +userName;
    if (typeof(android) != "undefined") {
        android.createChatRoom(chatRoomType.DM, userIdList.join(','),newRoomName, makeRoomFlg.NAME_CARD);
    } else {
        webkit.messageHandlers.createChatRoom.postMessage({"roomType": "1", "userIdList": userIdList.join(','), "roomName": newRoomName, "screenFlg": makeRoomFlg.NAME_CARD});
    }
    CHAT_UI.hideNamecard(nameCardAreaId.USER);
};

CHAT_UI.startVoice = function() {
};



CHAT_UI.makeNameCard = function(shopMemberId) {
    if (CHAT.globalLoginParameter.shopMemberId == shopMemberId) {
        return;
    }
    var nameCardInfo = CHAT_DB.getNameCardData(shopMemberId);
    var namecardTemplate;
    $.get({ url: "./template/template_user_name_card.html", async: false }
      , function(text) {
        namecardTemplate = text;
    });
    nameCardInfo.profileUrl = CHAT.getProfileImgUrl(nameCardInfo.profileUrl);
    let namecardHtml = Mustache.render(namecardTemplate, {
        shopMemberId: nameCardInfo.shopMemberId,
        profileUrl: nameCardInfo.profileUrl,
        name: nameCardInfo.shopMemberName,
        groupPathList: nameCardInfo.groupPathList,
        chat: getLocalizedString("chat"),
        voice: getLocalizedString("voice"),
        favorite: getLocalizedString("addFavorite"),
        isFavorite: nameCardInfo.isFavorite
    });

    let namecardObj = $(jQuery.parseHTML(namecardHtml)).on('click', function() {
    });

    $('#userProfileModal').html(namecardObj);
    $('#userNameCard').modal('show');
};

CHAT_UI.toggleCategory = function(category) {
  $(category).toggleClass("open");
  $(category).next().slideToggle();
};


// アーカイブ一覧
CHAT_UI.refreshArchiveScreen = function() {
    // loadingIndicatorを表示
    CHAT_UI.showLoadingIndicator();

    // 初期化
    $('#archiveList').html('');

    // アーカイブの様式を読み込む
    const archiveTemplate = $('#archive-template').html();

    // アーカイブ一覧取得
    if (IS_ONLINE == 'true') {
        CHAT_DB.updateArchiveList();
    }

    // ローカルDBのデータを表示
    var archiveList = CHAT_DB.getArchiveList();
    if (typeof archiveList == 'undefined') {
        CHAT_UI.dismissLoadingIndicator();
        return;
    }
    archiveList.forEach(function(archive) {
        var typeImage = "";
        switch(archive.archiveType) {
            case 0: // 画像
                typeImage = "icon/icon_collabo_picture.png";
                break;
            case 1: // 動画
                typeImage = "icon/icon_collabo_videocam.png";
                break;
            case 2: // 音声
                typeImage = "icon/icon_collabo_headset.png";
                break;
            case 3: // 文書
                typeImage = "icon/icon_collabo_document.png";
                break;
            default: // その他
                typeImage = "";
        }
        let html = Mustache.render(archiveTemplate, {
            archiveId: archive.archiveId,
            fileName: archive.archiveName,
            insertDate: archive.archiveDate,
            typeImage: typeImage
        });
        let obj = $(jQuery.parseHTML(html)).on('click', function() {
        });
        $('#archiveList').append(obj);
    });
    
    // loadingIndicatorを非表示
    CHAT_UI.dismissLoadingIndicator();
};


// アーカイブ詳細
CHAT_UI.refreshArchiveDetailScreen = function(archiveId) {
    // loadingIndicatorを表示
    CHAT_UI.showLoadingIndicator();

    // 初期化
    $('#archiveDetail').html('');
    // アーカイブ詳細の様式を読み込む
    const archiveDetailTemplate = $('#archive-detail-template').html();
    if (IS_ONLINE == 'true') {
        CHAT_DB.updateArchiveDetail(archiveId);
    }
    
    // アーカイブ詳細取得
    var archive = CHAT_DB.getArchiveDetail(archiveId);

    // チャットルーム情報を取得
    var roomId = archive.roomId;

    //保存ユーザ情報を取得
    var userInfo = CHAT_DB.getUserInfo(archive.saveUserId);
    userInfo.profileUrl = CHAT.getProfileImgUrl(userInfo.profileUrl);

    // アーカイブ情報を表示
    var html = Mustache.render(archiveDetailTemplate, {
        fileName: archive.archiveName,
        insertDate: archive.archiveDate,
        chatRoomName: archive.roomName,
        chatRoomId: archive.roomId,
        profileImage: userInfo.profileUrl,
        userName: userInfo.shopMembername,
        userId: userInfo.shopMemberId
    });

    var obj = $(jQuery.parseHTML(html)).on('click', function() {
    });
    $('#archiveDetail').append(obj);

    // プレイヤーの切り替え
    var archiveFilePath = CHAT.createGetDataUrl(archive.filePath, archive.roomId);
    switch(archive.archiveType) {
        case "0": // 画像
        case 0:
            $('#archive_player').prepend('<img class="archive_player" src="'+archiveFilePath+'" />');
            break;
        case "1": // 動画
        case 1:
            $('#archive_player').prepend('<video class="archive_player" src=' + archiveFilePath + ' controls autoplay muted playsinline></video>');
            break;
        case "2": // 音声
        case 2:
            $('#archive_player').prepend('<audio class="archive_audio_player" src=' + archiveFilePath + ' controls></audio>');
            $('#archive_player').prepend('<img class="archive_player" src=' + "./img/capture.png" + ' />');
            break;
        case "3": // 文書
        case 3:
            // リリースに文書とその他は含めないため今回は非表示
            break;
        default:
            // リリースに文書とその他は含めないため今回は非表示
    }

    // ユーザの様式を読み込む
    const archiveUserTemplate = $('#archive-user-template').html();

    // 参加ユーザ情報を表示
    let attendUserList = archive.attendUserIds;
    attendUserList = JSON.parse(archive.attendUserIds);

    attendUserList.forEach(function(user) {

        var userInfo = CHAT_DB.getUserInfo(user);
        userInfo.profileUrl = CHAT.getProfileImgUrl(userInfo.profileUrl);
        var html = Mustache.render(archiveUserTemplate, {
            profileImage: userInfo.profileUrl,
            userName: userInfo.shopMemberName
        });

        var obj = $(jQuery.parseHTML(html)).on('click', function() {
            // ネームカード表示
            CHAT_UI.makeNameCard(user);
        });

        $('#attendUser').append(obj);
    })

    CHAT_UI.htmlElementTextInitialize(navigator.language);

    // チャットルームへのリンク付け
    document.getElementById('joinChatRoom').onclick = function() {
        CHAT_UI.joinRoom(archive.roomId, archive.roomName);
    }

    // loadingIndicatorを非表示
    CHAT_UI.dismissLoadingIndicator();
};


CHAT_UI.refreshMyGroupForMakeRoom = function() {
    $(".modal-backdrop").remove();
    $('#favoriteListForMakeRoom').html('');
    $('#myGroupListForMakeRoom').html('');
    //画面タイトル設定
    let contactListTitle = getLocalizedString("userSearch");
    $('#title').text(contactListTitle);

    // グループの様式を読み込む
    var groupTemplate;
    $.get({ url: "./template/template_make_room_group_list.html", async: false }
      , function(text) {
        groupTemplate = text;
    });

    // ユーザの様式を読み込む
    var userTemplate;
    $.get({ url: "./template/template_make_room_user_list.html", async: false }
      , function(text) {
        userTemplate = text;
    });

    var groupUserTemplate;
    $.get({ url: "./template/template_make_room_group_user_list.html", async: false }
      , function(text) {
        groupUserTemplate = text;
    });

    if (IS_ONLINE == 'true') {
        if (typeof(android) != "undefined") {
            android.updateGroupInfo('0');
            android.updateMyInfo();
            android.updateGroupUser();
            android.updateFavorite();
        } else {
            webkit.messageHandlers.updateGroupInfo.postMessage("0");
            webkit.messageHandlers.updateMyInfo.postMessage({});
            webkit.messageHandlers.updateGroupUser.postMessage({});
            webkit.messageHandlers.updateFavorite.postMessage({});
        }
    }

    //お気に入りグループ取得。
    var favoriteGroupList = CHAT_DB.getFavoriteGroups();
    favoriteGroupList.forEach(function(favoriteGroup) {
        let html = Mustache.render(groupTemplate, {
            name: favoriteGroup.groupName,
            id: favoriteGroup.groupId,
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function() {
        });
        $('#favoriteListForMakeRoom').append(obj);
    })
    //お気に入りユーザ取得。
    var favoriteUserList = CHAT_DB.getFavoriteUsers();
    favoriteUserList.forEach(function(favoriteUser) {
        favoriteUser.profileUrl = CHAT.getProfileImgUrl(favoriteUser.profileUrl);
        let findObj = CHAT.globalSelectedUserList.find(function(shopMemberId) {
            return shopMemberId == favoriteUser.shopMemberId;
        })
        if (findObj) {
            favoriteUser.checked = 'checked';
        }
    });
    let html = Mustache.render(userTemplate, {
        userList: favoriteUserList
    });
    let obj = jQuery.parseHTML(html);
    $('#favoriteListForMakeRoom').append(obj);

    /*favoriteUserList.forEach(function(favoriteUser) {
        favoriteUser.profileImagePath = CHAT.getProfileImgUrl(favoriteUser.profileUrl)
        let html = Mustache.render(userTemplate, {
            shopMemberId: favoriteUser.shopMemberId,
            profileImage: favoriteUser.profileImagePath,
            name: favoriteUser.shopMemberName,
            isFavorite: true
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function() {
        });

        $('#favoriteList').append(obj);
    })*/

    var myGroupList = CHAT_DB.getMyGroupUsers();
    myGroupList.forEach(function(myGroup) {

        myGroup.groupUserList.forEach(function(groupUser) {
            groupUser.profileUrl = CHAT.getProfileImgUrl(groupUser.profileUrl)
            let findObj = CHAT.globalSelectedUserList.find(function(shopMemberId) {
                return shopMemberId == groupUser.shopMemberId;
            })
            if (findObj) {
                groupUser.checked = 'checked';
            }
        })
        let html = Mustache.render(groupUserTemplate, {
            groupName: myGroup.groupName,
            groupUserList: myGroup.groupUserList
        });
        let obj = $(jQuery.parseHTML(html)).on('click', function() {
        });

        $('#myGroupListForMakeRoom').append(obj);
    })
}

CHAT_UI.refreshAllGroupForMakeRoom = function(paramGroupId) {
    var groupId = paramGroupId;
    $('.cancel').addClass('none');
    $('.search_form input').removeClass('focus');
    $('.search_form input').val('');
    $('.search_form form').removeClass();
    $('.content').removeClass('none');
    $('.overlay_src_msg').empty();

    $('#tabAllGroupOnMakeRoom').prop('checked', true);

    //オンライン状態であればサーバから情報更新。
    if (IS_ONLINE == 'true') {
        if (typeof(android) != "undefined") {
            android.updateGroupInfo(groupId);
        } else {
            webkit.messageHandlers.updateGroupInfo.postMessage(groupId);
        }
    }

    //画面エリアを初期化。
    $('#parentGroupBtnForMakeRoom').off();
    $('#rootGroupBtnForMakeRoom').off();
    $('#childGroupListAreaForMakeRoom').html('');
    $('#userInGroupListForMakeRoom').html('');
    $('#groupPathAreaForMakeRoom').html('');

    //DBからグループ情報を取得。
    var result = CHAT_DB.getGroupInfo(groupId);

    //上位グループ、トップグループ遷移ボタンのイベント追加。
    if (typeof result.parentGroupId !== 'undefined') {
        $('#parentGroupBtnForMakeRoom').on('click', function() {
            CHAT_UI.refreshAllGroupForMakeRoom(result.parentGroupId);
        });
    }
    if (typeof result.rootGroupId !== 'undefined') {
        if (paramGroupId == 0) { groupId = result.rootGroupId }
        $('#rootGroupBtnForMakeRoom').on('click', function() {
            CHAT_UI.refreshAllGroupForMakeRoom(result.rootGroupId);
        });
    }
    if (groupId == result.rootGroupId || paramGroupId == '0') {
        $('#rootGroupArea').addClass('none');
        $('#parentGroupArea').addClass('none');
    } else {
        $('#rootGroupArea').removeClass('none');
        $('#parentGroupArea').removeClass('none');
    }
    //該当グループのパースを表示。
    var groupPathTemplate;
    $.get({ url: "./template/template_make_room_group_path.html", async: false }
      , function(text) {
        groupPathTemplate = text;
    });

    var groupPathCount = 0;
    result.groupPathList.forEach(function(groupPath) {
        if (!(groupPathCount < (result.groupPathList.length - 3))) {
            let html = Mustache.render(groupPathTemplate, {
                name: groupPath.groupName,
                id: groupPath.groupId
            });
            let obj = jQuery.parseHTML(html);
            $('#groupPathAreaForMakeRoom').append(obj);
        }
        groupPathCount++;
    })

    //該当グループの下位グループ表示。
    var groupTemplate;
    $.get({ url: "./template/template_make_room_group_list.html", async: false }
      , function(text) {
        groupTemplate = text;
    });

    result.childGroupList.forEach(function(childGroup) {
        let html = Mustache.render(groupTemplate, {
            name: childGroup.groupName,
            id: childGroup.groupId,
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function() {

        });
        $('#childGroupListAreaForMakeRoom').append(obj);
    })

    //該当グループの所属ユーザを表示。
    var userTemplate;
    $.get({ url: "./template/template_make_room_user_list.html", async: false }
      , function(text) {
        userTemplate = text;
    });
    result.groupUserList.forEach(function(groupUser) {
        groupUser.profileUrl = CHAT.getProfileImgUrl(groupUser.profileUrl)
        let findObj = CHAT.globalSelectedUserList.find(function(shopMemberId) {
            return shopMemberId == groupUser.shopMemberId;
        })
        if (findObj) {
            groupUser.checked = 'checked';
        }
    })
    let html = Mustache.render(userTemplate, {
        userList: result.groupUserList
    });
    let obj = jQuery.parseHTML(html);
    $('#userInGroupListForMakeRoom').append(obj);
};

CHAT_UI.checkForMakeChat = function(checkMemberId) {
    let findObj = CHAT.globalSelectedUserList.find(function(shopMemberId) {
        return shopMemberId == checkMemberId;
    })
    if (findObj) {
        // remove
        CHAT.globalSelectedUserList = CHAT.globalSelectedUserList.filter(function(shopMemberId) {
            return checkMemberId != shopMemberId;
        });
        $('.checkbox' + checkMemberId).prop("checked", false).trigger("change");
    } else {
        // add
        CHAT.globalSelectedUserList.push(checkMemberId);
        $('.checkbox' + checkMemberId).prop("checked", true).trigger("change");
    }

    let cnt = CHAT.globalSelectedUserList.length;
    if (CHAT.globalSelectedUserList.length > 0) {
        $('.select_member_num').text(cnt);
    } else {
        $('.select_member_num').text('0');
    }
};

CHAT_UI.showMakeRoomConfirmView = function() {
    $('#selectedUserList').html('');

    var userTemplate;
    $.get({ url: "./template/template_make_room_confirm_user_list.html", async: false }
      , function(text) {
        userTemplate = text;
    });

    var selectedUserList = CHAT_DB.loadSelectedUsers();

    selectedUserList.forEach(function(user){
         let html = Mustache.render(userTemplate, {
                     id: user.shopMemberId,
                     profileImage: CHAT.getProfileImgUrl(user.profileUrl),
                     name: user.shopMemberName
                 });
         let obj = jQuery.parseHTML(html);
         $('#selectedUserList').append(obj);
     })

     $("#makeRoomBtn").off().on('click', function() {
                 // #36130に対応
         const trimmedRoomName = $('#newRoomName').val().trim();
         if (trimmedRoomName.length == 0) {

             // loadingIndicatorを表示
             CHAT_UI.showLoadingIndicator();
             let userIdList = new Array();
             let userNameList = new Array();

             selectedUserList.forEach(function(user){
                userIdList.push(user.shopMemberId);
                userNameList.push(user.shopMemberName);
             })

             // 参加ユーザ名でルーム名を生成
             let newRoomName = CHAT.globalLoginParameter.loginId + ',' + userNameList.join(',');
             if (typeof(android) != "undefined") {
                 android.createChatRoom("1", userIdList.join(','), newRoomName, makeRoomFlg.MAKE_ROOM);
             } else {
                webkit.messageHandlers.createChatRoom.postMessage({"roomType": "1", "userIdList": userIdList.join(','), "roomName": newRoomName, "screenFlg": makeRoomFlg.MAKE_ROOM});
             }
         } else if(trimmedRoomName.includes(';') || trimmedRoomName.includes('/') || trimmedRoomName.includes('?') || trimmedRoomName.includes(':') || trimmedRoomName.includes("@")
              || trimmedRoomName.includes('&') || trimmedRoomName.includes('=') || trimmedRoomName.includes("+") || trimmedRoomName.includes('$') || trimmedRoomName.includes(",") || trimmedRoomName.includes('-')
              || trimmedRoomName.includes('_') || trimmedRoomName.includes('.') || trimmedRoomName.includes('!') || trimmedRoomName.includes('~') || trimmedRoomName.includes('*') || trimmedRoomName.includes("\'")
              || trimmedRoomName.includes('(') || trimmedRoomName.includes(')') || trimmedRoomName.includes('#') || trimmedRoomName.includes("\\") || trimmedRoomName.includes("\"") || trimmedRoomName.includes("`")) {
             // #36147
             // #36174
             $("#customAlertTitle").text(getLocalizedString("invalidCharacter"));
             $("#customAlertOk").text(getLocalizedString("yesTitle"));

             $('#customAlert').appendTo("body").modal({
                 backdrop: 'static',
                 keyboard: false
             })
             .on('click', '#customAlertOk', function(e) {
             });
         } else if (trimmedRoomName.length > 20) {
             // #36142
             var inputText = $('#newRoomName').val().trim(); // #36142 文字列の前又は後の空白文字列を削除

             // #36174
             $("#customAlertTitle").text(getLocalizedString("nameTooLong"));
             $("#customAlertOk").text(getLocalizedString("yesTitle"));

             $('#customAlert').appendTo("body").modal({
                 backdrop: 'static',
                 keyboard: false
             })
             .on('click', '#customAlertOk', function(e) {
                 $('#newRoomName').val(inputText.substr(0, $('#newRoomName').prop("maxlength")));
             });

         } else {
             //loadingIndicatorを表示
             CHAT_UI.showLoadingIndicator();
             let userIdList = new Array();

             selectedUserList.forEach(function(user){
                userIdList.push(user.shopMemberId);
             })

             // ルーム名のtrimmingした後、URIencodingを行う
             const encodedRoomName = encodeURIComponent(trimmedRoomName);
             if (typeof(android) != "undefined") {
                android.createChatRoom("1", userIdList.join(','), trimmedRoomName, makeRoomFlg.MAKE_ROOM);
             } else {
                webkit.messageHandlers.createChatRoom.postMessage({"roomType": "1", "userIdList": userIdList.join(','), "roomName": newRoomName, "screenFlg": makeRoomFlg.MAKE_ROOM});
             }
         }
     });
}

CHAT_UI.showAddUserConfirmView = function() {
    $('#selectedUserList').html('');

    var userTemplate;
    $.get({ url: "./template/template_add_user_confirm_user_list.html", async: false }
        , function(text) {
            userTemplate = text;
        }
    );

    var selectedUserList = CHAT_DB.loadSelectedUsers();

    console.log("check = " + selectedUserList);
    selectedUserList.forEach(function(user){
         let html = Mustache.render(userTemplate, {
                 id: user.shopMemberId,
                 profileImage: CHAT.getProfileImgUrl(user.profileUrl),
                 name: user.shopMemberName
         });
         let obj = jQuery.parseHTML(html);
         $('#selectedUserList').append(obj);
    })

    $("#addUserBtn").off().on('click', function() {
        CHAT_UI.showLoadingIndicator();
        let userIdList = new Array();
        selectedUserList.forEach(function(user){
            userIdList.push(user.shopMemberId);
        })
        if (typeof(android) != "undefined") {
            android.inviteUsers(userIdList.join(','));
        } else {
            webkit.messageHandlers.inviteUsers.postMessage({"userIdList": userIdList.join(',')});
        }
     });
}

CHAT_UI.refreshMyGroupForAddUser = function() {
    $(".modal-backdrop").remove();
    $('#favoriteListForMakeRoom').html('');
    $('#myGroupListForMakeRoom').html('');
    //画面タイトル設定
    let contactListTitle = getLocalizedString("userSearch");
    $('#title').text(contactListTitle);

    // グループの様式を読み込む
    var groupTemplate;
    $.get({ url: "./template/template_make_room_group_list.html", async: false }
      , function(text) {
        groupTemplate = text;
    });

    // ユーザの様式を読み込む
    var userTemplate;
    $.get({ url: "./template/template_make_room_user_list.html", async: false }
      , function(text) {
        userTemplate = text;
    });

    var groupUserTemplate;
    $.get({ url: "./template/template_make_room_group_user_list.html", async: false }
      , function(text) {
        groupUserTemplate = text;
    });

    if (IS_ONLINE == 'true') {
        if (typeof(android) != "undefined") {
            android.updateGroupInfo('0');
            android.updateMyInfo();
            android.updateGroupUser();
            android.updateFavorite();
        } else {
            webkit.messageHandlers.updateGroupInfo.postMessage("0");
            webkit.messageHandlers.updateMyInfo.postMessage({});
            webkit.messageHandlers.updateGroupUser.postMessage({});
            webkit.messageHandlers.updateFavorite.postMessage({});
        }
    }

    //お気に入りグループ取得。
    var favoriteGroupList = CHAT_DB.getFavoriteGroups();
    favoriteGroupList.forEach(function(favoriteGroup) {
        let html = Mustache.render(groupTemplate, {
            name: favoriteGroup.groupName,
            id: favoriteGroup.groupId,
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function() {
        });
        $('#favoriteListForMakeRoom').append(obj);
    })
    //お気に入りユーザ取得。
    var favoriteUserList = CHAT_DB.getFavoriteUsersNotInRoom();
    favoriteUserList.forEach(function(favoriteUser) {
        favoriteUser.profileUrl = CHAT.getProfileImgUrl(favoriteUser.profileUrl);
        let findObj = CHAT.globalSelectedUserList.find(function(shopMemberId) {
            return shopMemberId == favoriteUser.shopMemberId;
        })
        if (findObj) {
            favoriteUser.checked = 'checked';
        }
    });
    let html = Mustache.render(userTemplate, {
        userList: favoriteUserList
    });
    let obj = jQuery.parseHTML(html);
    $('#favoriteListForMakeRoom').append(obj);

    var myGroupList = CHAT_DB.getMyGroupUsersNotInRoom();
    myGroupList.forEach(function(myGroup) {

        myGroup.groupUserList.forEach(function(groupUser) {
            groupUser.profileUrl = CHAT.getProfileImgUrl(groupUser.profileUrl)
            let findObj = CHAT.globalSelectedUserList.find(function(shopMemberId) {
                return shopMemberId == groupUser.shopMemberId;
            })
            if (findObj) {
                groupUser.checked = 'checked';
            }
        })
        let html = Mustache.render(groupUserTemplate, {
            groupName: myGroup.groupName,
            groupUserList: myGroup.groupUserList
        });
        let obj = $(jQuery.parseHTML(html)).on('click', function() {
        });

        $('#myGroupListForMakeRoom').append(obj);
    })
}

CHAT_UI.refreshAllGroupForAddUser = function(paramGroupId) {
    var groupId = paramGroupId;
    $('.cancel').addClass('none');
    $('.search_form input').removeClass('focus');
    $('.search_form input').val('');
    $('.search_form form').removeClass();
    $('.content').removeClass('none');
    $('.overlay_src_msg').empty();

    $('#tabAllGroupOnAllUser').prop('checked', true);

    //オンライン状態であればサーバから情報更新。
    if (IS_ONLINE == 'true') {
        if (typeof(android) != "undefined") {
            android.updateGroupInfo(groupId);
        } else {
            webkit.messageHandlers.updateGroupInfo.postMessage(groupId);
        }
    }

    //画面エリアを初期化。
    $('#parentGroupBtnForMakeRoom').off();
    $('#rootGroupBtnForMakeRoom').off();
    $('#childGroupListAreaForMakeRoom').html('');
    $('#userInGroupListForMakeRoom').html('');
    $('#groupPathAreaForMakeRoom').html('');

    //DBからグループ情報を取得。
    var result = CHAT_DB.getGroupInfoForAddUser(groupId);

    //上位グループ、トップグループ遷移ボタンのイベント追加。
    if (typeof result.parentGroupId !== 'undefined') {
        $('#parentGroupBtnForMakeRoom').on('click', function() {
            CHAT_UI.refreshAllGroupForAddUser(result.parentGroupId);
        });
    }
    if (typeof result.rootGroupId !== 'undefined') {
        if (paramGroupId == 0) { groupId = result.rootGroupId }
        $('#rootGroupBtnForMakeRoom').on('click', function() {
            CHAT_UI.refreshAllGroupForAddUser(result.rootGroupId);
        });
    }
    if (groupId == result.rootGroupId || paramGroupId == '0') {
        $('#rootGroupArea').addClass('none');
        $('#parentGroupArea').addClass('none');
    } else {
        $('#rootGroupArea').removeClass('none');
        $('#parentGroupArea').removeClass('none');
    }
    //該当グループのパースを表示。
    var groupPathTemplate;
    $.get({ url: "./template/template_make_room_group_path.html", async: false }
      , function(text) {
        groupPathTemplate = text;
    });

    var groupPathCount = 0;
    result.groupPathList.forEach(function(groupPath) {
        if (!(groupPathCount < (result.groupPathList.length - 3))) {
            let html = Mustache.render(groupPathTemplate, {
                name: groupPath.groupName,
                id: groupPath.groupId
            });
            let obj = jQuery.parseHTML(html);
            $('#groupPathAreaForMakeRoom').append(obj);
        }
        groupPathCount++;
    })

    //該当グループの下位グループ表示。
    var groupTemplate;
    $.get({ url: "./template/template_make_room_group_list.html", async: false }
      , function(text) {
        groupTemplate = text;
    });

    result.childGroupList.forEach(function(childGroup) {
        let html = Mustache.render(groupTemplate, {
            name: childGroup.groupName,
            id: childGroup.groupId,
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function() {

        });
        $('#childGroupListAreaForMakeRoom').append(obj);
    })

    //該当グループの所属ユーザを表示。
    var userTemplate;
    $.get({ url: "./template/template_make_room_user_list.html", async: false }
      , function(text) {
        userTemplate = text;
    });
    result.groupUserList.forEach(function(groupUser) {
        groupUser.profileUrl = CHAT.getProfileImgUrl(groupUser.profileUrl)
        let findObj = CHAT.globalSelectedUserList.find(function(shopMemberId) {
            return shopMemberId == groupUser.shopMemberId;
        })
        if (findObj) {
            groupUser.checked = 'checked';
        }
    })
    let html = Mustache.render(userTemplate, {
        userList: result.groupUserList
    });
    let obj = jQuery.parseHTML(html);
    $('#userInGroupListForMakeRoom').append(obj);
};

CHAT_UI.refreshForOnline = function() {
    IS_ONLINE = 'true';
    $('.craeteRoomButton').show();
    $('#messageSend').removeClass('disabled');
    $('#messageSend').attr('disabled', false);
    $('#favoriteButton').attr('disabled', false);
    $('#roomMenu').show();
    $('.attach_file').show();
    $('.fa-download').show();
    $('.chat_room_footer').show();
    if (typeof $('#roomTitle').val() != 'undefined') {
        CHAT_SOCKET.connectSocket();
        socket.emit('join', CHAT.globalLoginParameter, function() {
        });
    }
}

CHAT_UI.refreshForOffline = function() {
    IS_ONLINE = 'false';
    $('.craeteRoomButton').hide();
    $('#messageSend').addClass('disabled');
    $('#messageSend').attr('disabled', true);
    $('#favoriteButton').attr('disabled', true);
    $('#roomMenu').hide();
    $('.attach_file').hide();
    $('.fa-download').hide();
    $('.chat_room_footer').hide();
}