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

$(function() {
    let navbarHeight = document.getElementsByClassName("navbar")[0].offsetHeight
    let searchBarHeight = document.getElementsByClassName("search-bar-fixed")[0].offsetHeight
    let footerHeight = document.getElementsByClassName("footer-nav")[0].offsetHeight
    $(".tab-pane").css('padding', `${navbarHeight + 'px'} 0px 0px`)

    /* チャットルーム一覧画面スクロール範囲
     * 画面の高さ - (画面上部タイトルの高さ + ルーム名検索欄の高さ) */
    $(".inbox_chat").css('max-height', `calc(100vh - ${(navbarHeight + searchBarHeight + footerHeight) + 'px'})`)

    $('.roomListIcon').hide();
    $('#userSelectionDeleteBtn').hide();
    //$('#createChatRoom').hide();
});

// 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);
    CHAT_UI.refreshGroupSearch('0', 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') {
            android.updateRoomList();
            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;
	}
}

//メッセージ送信
$('#message-form').on('keypress', function(event){
    if (event.which == 13) {
        // Enterキーの処理
        $('#message-send-btn').click();
    }
});

// 送信ボタンの処理
$('#message-send-btn').on('click', function (e){
    e.preventDefault();
    const messageTextBox = $('#message-form');
    const message = messageTextBox.val().length > 0 ? encodeURIComponent(messageTextBox.val() + " ") : "";
    messageTextBox.val('');

    if (message.length > 0) {
        socket.emit(
            'createMessage', { text: message }
            , 0
        );
    }
    $('#message-form').focus();
});

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

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

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

$('#imageInputTag2').on('change', function(){
    $('#image-form2').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)

        })
    }
});

$('#image-form2').on('submit', function(e){
    e.preventDefault();
    const imageInputTag2 = $('#imageInputTag2');
    const file = imageInputTag2.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                                                                     */
/* --------------------------------------------------- */

// Gallery Button
// ギャラリーボタンを押すと最後の写真をクリックさせる。 (ボタン非活性化中)
$('#imageGalleryButton').on('click', function(){
    $('[data-lightbox=attachedImages]:last').click();
});

//lightbox Configuration
lightbox.option({
    'resizeDuration': 0,
    'imageFadeDuration': 0,
    'fadeDuration': 300,
    'alwaysShowNavOnTouchDevices': true
});

$('#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() {
                        android.updateRoomList();
                    });
                }
                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();
            $('#newRoomName').val('');
            $('#userSelectionLength').text('');
            CHAT.globalSelectedUserList = [];
            $('#allGroupArea').hide();
            $('#my_info').show();
            $('#bottomNav').show();
            break;

        case '#pills-archive':
            $('#homeButton').show();
            $("#backButton").hide();
            $('.titleRoomName').show();
            $('#archive_list').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-archive':
			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 = $('#messages');
    const scrollHeight = messages.prop('scrollHeight');
    messages.scrollTop(scrollHeight);
};

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() {
    $("#loadingIndicator").addClass('active undismissable');
}

//loadingIndicatorを表示しない
CHAT_UI.dismissLoadingIndicator = function() {
    $("#loadingIndicator").removeClass('active undismissable');
}

//画面の方向を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.shopMemberName
        });
        // 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();
        CHAT_UI.refreshGroupSearch("0", 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
                    android.createChatRoom("1", userIdList.join(','), newRoomName);


                    /*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);
                    android.createChatRoom("1",userIdList.join(','),encodedRoomName);

                }
            }
        }
    });

    $("#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"))
}

// 画像の読み込みが全て終わったタイミングでコールバック実行
// 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){
    let isCreate = false;
    let isInvite = false;
    CHAT_UI.refreshContactScreen(isCreate, isInvite);
});

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

<<<<<<< HEAD
=======
<<<<<<< HEAD
CHAT_UI.refreshGroupSearch = function(groupId, isInvite) {
    CHAT_UI.showLoadingIndicator();
    $('#pills-contact-tab').tab('show');

    //画面タイトル設定
    let memberSelectTitle = getLocalizedString("userSearch")
    $('.titleRoomName').text(memberSelectTitle);

    if (IS_ONLINE == 'true') {
        android.updateGroupInfo(groupId);
    }
    $('#rootGroupBtn').off();
    $('#parentGroupBtn').off();

    $('#backButton').show();
    $('#homeButton').hide();

    $('#newRoomName, .roomListIcon, .chatRoomIcon').hide();
    $('#userSelectionConfirmBtn').show();
    $("#userSelectionConfirmBtn").off().on('click', function(){
        CHAT_UI.setConfirmButtonEvent(isInvite);
    });

    var result = CHAT_DB.getGroupInfo(groupId);

    $('#childGroupList').html('');
    $('#userInGroupList').html('');
    $('#groupPathArea').html('');

    if (typeof result.parentGroupId !== 'undefined') {
        console.log(result.parentGroupId);
        $('#parentGroupBtn').on('click', function() {
            CHAT_UI.refreshGroupSearch(result.parentGroupId, isInvite);
        });
    }
    if (typeof result.rootGroupId !== 'undefined') {
        console.log(result.rootGroupId);
        $('#rootGroupBtn').on('click', function() {
            CHAT_UI.refreshGroupSearch(result.rootGroupId, isInvite);
        });
    }

    const groupNaviTemplate = $('#group-navigater-template').html();
    var groupCount = 0;
    result.groupPathList.forEach(function(groupPath) {
        if (groupCount != 0) {
            $('#groupPathArea').append("<label class='group-navigater'> > </label>");
        }
        let html = Mustache.render(groupNaviTemplate, {
            name: groupPath.groupName,
            id: groupPath.groupId
        });
        let obj = $(jQuery.parseHTML(html)).on('click', function(){
            CHAT_UI.refreshGroupSearch(groupPath.groupId, isInvite);
        });
        groupCount++;
        $('#groupPathArea').append(obj);
    })

    const groupTemplate = $('#group-template').html();
    result.childGroupList.forEach(function(childGroup) {
        let html = Mustache.render(groupTemplate, {
            name: childGroup.groupName,
            id: childGroup.groupId
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function(){
            CHAT_UI.refreshGroupSearch(childGroup.groupId, isInvite);
        });
        $('#childGroupList').append(obj);
    })

    const userTemplate = $('#user-template').html();
    result.groupUserList.forEach(function(groupUser) {
        groupUser.profileImagePath = CHAT.getProfileImgUrl(groupUser.profileUrl)
        let html = Mustache.render(userTemplate, {
            id: groupUser.shopMemberId,
            profileImage: groupUser.profileImagePath,
            name: groupUser.shopMemberName
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function(){
            //TODO need onClick Action
            if (IS_ONLINE == 'true') {
                if ($(this).find('.userCheckBox.active').length > 0) {
                    // remove
                    CHAT.globalSelectedUserList = CHAT.globalSelectedUserList.filter(function(element) {
                        return groupUser.shopMemberId != element.shopMemberId;
                    });
                } else {
                    // add
                    CHAT.globalSelectedUserList.push({shopMemberName:groupUser.shopMemberName, shopMemberId : groupUser.shopMemberId, profileImagePath: groupUser.profileImagePath});
                }
                $(this).find('.userCheckBox').toggleClass('active');

                if (CHAT.globalSelectedUserList.length > 0) {
                    $('#userSelectionLength').text(CHAT.globalSelectedUserList.length);
                } else {
                    $('#userSelectionLength').text('');
                }
            }

        });
        let findObj = CHAT.globalSelectedUserList.find(function(selectedUser) {
            return selectedUser.shopMemberId == groupUser.shopMemberId;
        })

        if (findObj) {
            $(obj).find('.userCheckBox').toggleClass('active');
        }

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

    $('#backButton').off().on('click', function() {
        // loadingIndicatorを表示
        CHAT_UI.showLoadingIndicator();
        if (isInvite) {
            $('#pills-chat-tab').tab('show');
        } else {
            if (IS_ONLINE == 'true') {
                android.updateRoomList();
                CHAT_UI.refreshRoomList(chatRoomType.DM);
                CHAT_UI.dismissLoadingIndicator();
            }
        }
    });

    $('#myGroupBtn').off().on('click', function() {
        let isCreate = true;
        CHAT_UI.refreshContactScreen(isCreate, isInvite);
    });

    CHAT_UI.dismissLoadingIndicator();
    $('.userCheckBox').show();
    $('#groupButtonArea').show();
    $('#allGroupArea').show();
    $('#myGroupArea').hide();
}
>>>>>>> origin/develop_createRoom_UI
$('#archiveButton').on('click', function(event){
    CHAT_UI.refreshArchiveScreen();
});

<<<<<<< HEAD
CHAT_UI.refreshContactScreen = function() {
=======
CHAT_UI.refreshContactScreen = function(isCreate, isInvite) {

>>>>>>> origin/develop_createRoom_UI
    //loadingIndicatorを表示
    $('#my_info').html('');
    $('#favorite_list').html('');
    $('#my_group_list').html('');
    CHAT_UI.showLoadingIndicator();
    if (isCreate != true) {
        $('#pills-contact-tab').tab('show');
        //画面タイトル設定
        let contactListTitle = getLocalizedString("contactListTitle");
        $('.titleRoomName').text(contactListTitle);
        $('#backButton').hide();
        $('#homeButton').show();
        $('#userSelectionConfirmBtn').hide();
    }
    $('#myGroupArea').show();
    $('#allGroupArea').hide();


    // グループの様式を読み込む
    const groupTemplate = $('#group-template').html();

    // ユーザの様式を読み込む
    const userTemplate = $('#user-template').html();
    const myNamecardTemplate = $('#my-namecard-template').html();
    const userNamecardTemplate = $('#namecard-template').html();
    if (IS_ONLINE == 'true') {
        android.updateGroupInfo('0');
        android.updateMyInfo();
        android.updateGroupUser();
    }

    if (isCreate != true) {
        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(){

        });
        $('#myNamecard').append(myNamecardObj);

        let html = Mustache.render(userTemplate, {
            id: myInfo.shopMemberId,
            profileImage: myInfo.profileImagePath,
            name: myInfo.shopMemberName
        });

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

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

    var groupUserList = CHAT_DB.getMyGroupUsers();
    groupUserList.forEach(function(groupUser) {
        groupUser.profileImagePath = CHAT.getProfileImgUrl(groupUser.profileUrl)
        let html = Mustache.render(userTemplate, {
            id: groupUser.shopMemberId,
            profileImage: groupUser.profileImagePath,
            name: groupUser.shopMemberName
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function(){
            console.log('click');
            if (isCreate != true) {
                CHAT_UI.makeNameCard(groupUser.shopMemberId);
            } else {
                if ($(this).find('.userCheckBox.active').length > 0) {
                    // remove
                    CHAT.globalSelectedUserList = CHAT.globalSelectedUserList.filter(function(element) {
                        return groupUser.shopMemberId != element.shopMemberId;
                    });
                } else {
                    // add
                    CHAT.globalSelectedUserList.push({shopMemberName:groupUser.shopMemberName, shopMemberId : groupUser.shopMemberId, profileImagePath: groupUser.profileImagePath});
                }
                $(this).find('.userCheckBox').toggleClass('active');

                if (CHAT.globalSelectedUserList.length > 0) {
                    $('#userSelectionLength').text(CHAT.globalSelectedUserList.length);
                } else {
                    $('#userSelectionLength').text('');
                }
            }
        });

        let findObj = CHAT.globalSelectedUserList.find(function(selectedUser) {
            return selectedUser.shopMemberId == groupUser.shopMemberId;
        })

        if (findObj) {
            $(obj).find('.userCheckBox').toggleClass('active');
        }

        $('#my_group_list').append(obj);
    })
    var favoriteCount = 0;
    var favoriteGroupList = CHAT_DB.getFavoriteGroups();
    favoriteGroupList.forEach(function(favoriteGroup) {
        let html = Mustache.render(groupTemplate, {
            name: favoriteGroup.groupName
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function(){
            //TODO need onClick Action
            if (isCreate != true) {
            } else {
                CHAT_UI.refreshGroupSearch(favoriteGroup.groupId, isInvite);
            }
        });
        favoriteCount++
        $('#favorite_list').append(obj);
    })

    var favoriteUserList = CHAT_DB.getFavoriteUsers();
    favoriteUserList.forEach(function(favoriteUser) {
        favoriteUser.profileImagePath = CHAT.getProfileImgUrl(favoriteUser.profileUrl)
        let html = Mustache.render(groupTemplate, {
            id: favoriteUser.shopMemberId,
            profileImage: favoriteUser.profileImagePath,
            name: favoriteUser.shopMemberName
        });

        let obj = $(jQuery.parseHTML(html)).on('click', function(){
            //TODO need onClick Action
            if (isCreate != true) {
            } else {
                if ($(this).find('.userCheckBox.active').length > 0) {
                    // remove
                    CHAT.globalSelectedUserList = CHAT.globalSelectedUserList.filter(function(element) {
                        return favoriteUser.shopMemberId != element.shopMemberId;
                    });
                } else {
                    // add
                    CHAT.globalSelectedUserList.push({shopMemberName:favoriteUser.shopMemberName, shopMemberId : favoriteUser.shopMemberId, profileImagePath: favoriteUser.profileImagePath});
                }
                $(this).find('.userCheckBox').toggleClass('active');

                if (CHAT.globalSelectedUserList.length > 0) {
                    $('#userSelectionL ength').text(CHAT.globalSelectedUserList.length);
                } else {
                    $('#userSelectionLength').text('');
                }
            }
        });

        let findObj = CHAT.globalSelectedUserList.find(function(selectedUser) {
            return selectedUser.shopMemberId == favoriteUser.shopMemberId;
        })

        if (findObj) {
            $(obj).find('.userCheckBox').toggleClass('active');
        }
        favoriteCount++
        $('#favorite_list').append(obj);
    })

    if (favoriteCount == 0) {
        $('#favorite_list').hide();
        $('#favorite-seperator').hide();
    } else {
        $('#favorite_list').show();
        $('#favorite-seperator').show();
    }

    if (isCreate == true) {
        $('.userCheckBox').show();
        $('#allGroupBtn').off().on('click', function() {
            CHAT_UI.refreshGroupSearch("0", isInvite);
        });
    } else {
        $('.userCheckBox').hide();
        $('#allGroupBtn').off().on('click', function() {
            CHAT_UI.refesshAllGroupSearch("0");
        });
    };

    CHAT_UI.dismissLoadingIndicator();
}

CHAT_UI.refreshRoomList = function(roomType) {
    var rooms = CHAT_DB.getRoomList(roomType);
    CHAT.globalIsInvite = false;
    activeRoomId = null;
    // #36146に対応
    let keywordSearchMode = false;
    if ($('#room-search').val().length > 0) {
        keywordSearchMode = true;
    }
   $('#room_list').html('');
    let roomListTitle = getLocalizedString("roomListTitle");
    $('.titleRoomName').text(roomListTitle);
    if (rooms.length === 0) {
        // 検索結果がない場合のメッセージを追加
        if (!keywordSearchMode) {
            let emptyListString = getLocalizedString("roomListEmptyString")
            $('#room_list').append(`<center class="text-secondary">${emptyListString}</center>`);
        } else {
            let emptyListString = getLocalizedString("searchRoomListEmptyString")
            $('#room_list').append(`<center class="text-secondary">${emptyListString}</center>`);
        }
    }
    // チャットルームの様式を読み込む
    const template = $('#room-template').html();
    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.SYSTEM) displayMsg = getLocalizedString("image");
        let html = Mustache.render(template, {
            roomName: room.chatRoomName,
            roomId: room.chatRoomId,
            profileImage: room.profileImagePath,
            active: activeRoomId === room.chatRoomId ? 'active_chat' : null, // 現在、入っているルームだとhilight表示
            lastMessage: displayMsg ,
            time: room.insertDate ? CHAT_UTIL.formatDate(room.insertDate).createdAt : '',
            unreadMsgCnt: room.unreadCount == 0 ? '' : room.unreadCount,
            userCnt: room.userCount
        });
        // 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 ルームに入る処理追加必要
        });
        // チャットルームリストに追加する
        $('#room_list').append(obj);
    });
    if (rooms.length > 0) {
        if (!keywordSearchMode) {
            $(".roomListIcon").show()
            $('#roomDeleteButton, #arrangeRooms').show()
        } else {
            $(".roomListIcon").show()
            $('#roomDeleteButton, #arrangeRooms').hide()
        }
    } else {
        if (!keywordSearchMode) {
            $(".roomListIcon").hide()
        } else {
            $(".roomListIcon").show()
            $('#roomDeleteButton, #arrangeRooms').hide()
        }
    }
    $('#createChatRoom').show();
    if (CHAT_UI.isLandscapeMode()) {
        $(".chat_list").removeClass("col-12").addClass("col-6");
    }
    $("#userSelectionDeleteBtn").hide();

    // チャットルームリスト画面に遷移
    $('#pills-chatlist-tab').tab('show');

    // loadingIndicatorを表示しない
    CHAT_UI.dismissLoadingIndicator();
};

CHAT_UI.joinRoom = function(roomId,roomName) {
    if (IS_ONLINE == 'true') {
        android.updateMessages(roomId);
        socket.emit('joinRoom', roomId, roomName, function() {
        });
    }
    var messages = CHAT_DB.getMessages(roomId);
    CHAT_UI.loadMessages(messages, roomId, roomName)

};

CHAT_UI.loadMessages = function(messages, roomId, roomName) {
    $('#messages').html('');
    $('.titleRoomName').text(roomName).data('roomName', roomName);
    $("#message-search").attr("placeholder", getLocalizedString("chat_search_placeholder"));
    let jQueryMessages = $('#messages');
        // スクロールの変化を防ぐため以前画面の高さを保存する
        let beforeHeight = jQueryMessages.prop('scrollHeight');
        // メッセージ文字列の生成
        let workVal = "";
        messages.forEach(function(message) {
            let template = $('#message-template').html();
            if (message.selfFlg == 1) {
                 template = $('#message-template-me').html();
            }
            let messageTime = CHAT_UTIL.formatDate(message.insertDate);

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

             // #36147
             message.message = message.message.toString();
             var replacePath = message.message;
             replacePath = replacePath.replaceAll('/acms',CHAT_SERVER_URL+'/acms');
             message.message = replacePath;
             let html = Mustache.render(template, {
                 text: message.message,
                 from: message.loginId,
                 shopMemberId: message.shopMemberId,
                 profileImage: message.profileImagePath,
                 createdAtDay: messageTime.createdAtDay,
                 createdAtTime: messageTime.createdAtTime
             });
             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();
            }
        }

        // ユーザ削除ボタン表示しない
        $("#userSelectionDeleteBtn").hide();

        CHAT_UI.dismissLoadingIndicator();// add some...

        // チャットに遷移する
        $('#pills-chat-tab').tab('show');
};


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

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



CHAT_UI.showNamecard = function(id) {
    $('#'+id).appendTo("body").modal({
        backdrop: 'static',
        keyboard: false
    })
}

CHAT_UI.hideNamecard = function(id) {
    $('#'+id).modal('hide');
}

CHAT_UI.showUserNamecard = function(shopMemberId) {

//    $('#myNamecard').appendTo("body").modal({
//        backdrop: 'static',
//        keyboard: false
//    })
}

<<<<<<< HEAD
=======
$('#allGroupBtn').on('click', function (e){
    CHAT_UI.refesshAllGroupSearch('0')
});

CHAT_UI.refesshAllGroupSearch = function(groupId) {
    const userNamecardTemplate = $('#namecard-template').html();
    if (IS_ONLINE == 'true') {
        android.updateGroupInfo(groupId);
    }
    $('#rootGroupBtn').off();
    $('#parentGroupBtn').off();

    var result = CHAT_DB.getGroupInfo(groupId);

    $('#childGroupList').html('');
    $('#userInGroupList').html('');
    $('#groupPathArea').html('');

    if (typeof result.parentGroupId !== 'undefined') {
        console.log(result.parentGroupId);
        $('#parentGroupBtn').on('click', function() {
            CHAT_UI.refesshAllGroupSearch(result.parentGroupId);
        });
    }
    if (typeof result.rootGroupId !== 'undefined') {
        console.log(result.rootGroupId);
        $('#rootGroupBtn').on('click', function() {
            CHAT_UI.refesshAllGroupSearch(result.rootGroupId);
        });
    }


    const groupNaviTemplate = $('#group-navigater-template').html();
    var groupCount = 0;
    result.groupPathList.forEach(function(groupPath) {
        if (groupCount != 0) {
            $('#groupPathArea').append("<label class='group-navigater'> > </label>");
        }
        let html = Mustache.render(groupNaviTemplate, {
            name: groupPath.groupName,
            id: groupPath.groupId
        });
        let obj = $(jQuery.parseHTML(html)).on('click', function(){
            CHAT_UI.refesshAllGroupSearch(groupPath.groupId);
        });
        groupCount++;
        $('#groupPathArea').append(obj);
    })

    const groupTemplate = $('#group-template').html();
    result.childGroupList.forEach(function(childGroup) {
            let html = Mustache.render(groupTemplate, {
                name: childGroup.groupName,
                id: childGroup.groupId
            });

            let obj = $(jQuery.parseHTML(html)).on('click', function(){
                CHAT_UI.refesshAllGroupSearch(childGroup.groupId);
            });
            $('#childGroupList').append(obj);
        })

    const userTemplate = $('#user-template').html();
    result.groupUserList.forEach(function(groupUser) {
            groupUser.profileImagePath = CHAT.getProfileImgUrl(groupUser.profileUrl)
            let html = Mustache.render(userTemplate, {
                id: groupUser.shopMemberId,
                profileImage: groupUser.profileImagePath,
                name: groupUser.shopMemberName
            });

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

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

    $('#myGroupBtn').off().on('click', function (e){
        $('#myGroupArea').show();
        $('#allGroupArea').hide();
    });

    $('.userCheckBox').hide();
    $('#myGroupArea').hide();
    $('#allGroupArea').show();
}

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

    // 参加ユーザ名でルーム名を生成
    let newRoomName = CHAT.globalLoginParameter.loginId + ',' +userName;
    android.createChatRoom(chatRoomType.DM, userIdList.join(','),newRoomName);
    CHAT_UI.hideNamecard(nameCardAreaId.USER);
};

CHAT_UI.startVoice = function () {
    //add Android Chat click
    console.log("VoiceClick");
};

CHAT_UI.changeFavorite = function () {
    //add Android Chat click
    console.log("FavoriteClick");
};

CHAT_UI.removeFavoriteUser = function (shopMemberId) {
    //add Android Chat click
    console.log("removeFU");
};

CHAT_UI.insertFavoriteUser = function (shopMemberId) {
    //add Android Chat click
    console.log("insertFU");
};

CHAT_UI.changeFavorite = function () {
    //add Android Chat click
    console.log("FavoriteClick");
};

CHAT_UI.makeNameCard = function (shopMemberId) {
    console.log('makeNameCard Click');
    var nameCardInfo = CHAT_DB.getNameCardData(shopMemberId);
    console.log(nameCardInfo);

    const userNamecardTemplate = $('#namecard-template').html();
    let namecardHtml = Mustache.render(userNamecardTemplate, {
        loginId: nameCardInfo.shopMemberId,
        profileImage: nameCardInfo.profileImagePath,
        name: nameCardInfo.shopMemberName,
        groupPathList: nameCardInfo.groupPathList,
        chat: getLocalizedString("chat"),
        voice: getLocalizedString("voice"),
        favorite: getLocalizedString("addFavorite")
    });

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

    $('#userNamecard').html(namecardObj);
    CHAT_UI.showNamecard('userNamecard');
};

CHAT_UI.makeNameCardInChatRoom = function (chatRoomId) {
    console.log('makeNameCard Click');
    var nameCardInfo = CHAT_DB.getNameCardData(chatRoomId);
    console.log(nameCardInfo);

    const userNamecardTemplate = $('#namecard-template').html();
    let namecardHtml = Mustache.render(userNamecardTemplate, {
        loginId: nameCardInfo.shopMemberId,
        profileImage: nameCardInfo.profileImagePath,
        name: nameCardInfo.shopMemberName,
        groupPathList: nameCardInfo.groupPathList,
        chat: getLocalizedString("chat"),
        voice: getLocalizedString("voice"),
        favorite: getLocalizedString("addFavorite")
    });

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

    $('#userNamecard').html(namecardObj);
    CHAT_UI.showNamecard('userNamecard');
};

CHAT_UI.refesshAllGroupSearchFaborite = function(groupId) {
    const userNamecardTemplate = $('#namecard-template').html();
    if (IS_ONLINE == 'true') {
        android.updateGroupInfo(groupId);
    }
    $('#rootGroupBtn').off();
    $('#parentGroupBtn').off();

    var result = CHAT_DB.getGroupInfo(groupId);

    $('#childGroupList').html('');
    $('#userInGroupList').html('');
    $('#groupPathArea').html('');

    if (typeof result.parentGroupId !== 'undefined') {
        console.log(result.parentGroupId);
        $('#parentGroupBtn').on('click', function() {
            CHAT_UI.refesshAllGroupSearch(result.parentGroupId);
        });
    }
    if (typeof result.rootGroupId !== 'undefined') {
        console.log(result.rootGroupId);
        $('#rootGroupBtn').on('click', function() {
            CHAT_UI.refesshAllGroupSearch(result.rootGroupId);
        });
    }


    const groupNaviTemplate = $('#group-navigater-template').html();
    var groupCount = 0;
    result.groupPathList.forEach(function(groupPath) {
        if (groupCount != 0) {
            $('#groupPathArea').append("<label class='group-navigater'> > </label>");
        }
        let html = Mustache.render(groupNaviTemplate, {
            name: groupPath.groupName,
            id: groupPath.groupId
        });
        let obj = $(jQuery.parseHTML(html)).on('click', function(){
            CHAT_UI.refesshAllGroupSearch(groupPath.groupId);
        });
        groupCount++;
        $('#groupPathArea').append(obj);
    })

    const groupTemplate = $('#group-template').html();
    result.childGroupList.forEach(function(childGroup) {
            let html = Mustache.render(groupTemplate, {
                name: childGroup.groupName,
                id: childGroup.groupId
            });

            let obj = $(jQuery.parseHTML(html)).on('click', function(){
                CHAT_UI.refesshAllGroupSearch(childGroup.groupId);
            });
            $('#childGroupList').append(obj);
        })

    const userTemplate = $('#user-template').html();
    result.groupUserList.forEach(function(groupUser) {
            groupUser.profileImagePath = CHAT.getProfileImgUrl(groupUser.profileUrl)
            let html = Mustache.render(userTemplate, {
                id: groupUser.shopMemberId,
                profileImage: groupUser.profileImagePath,
                name: groupUser.shopMemberName
            });

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

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

    $('#myGroupArea').hide();
    $('#allGroupArea').show();
}
>>>>>>> origin/develop_createRoom_UI
CHAT_UI.refreshArchiveScreen = function() {
	// loadingIndicatorを表示
	CHAT_UI.showLoadingIndicator();

	//画面タイトル設定
	let archiveListTitle = getLocalizedString("archiveListTitle");
	$('.titleRoomName').text(archiveListTitle);

	// 初期化
	$('#archive_list').html('');
	$('#pills-archive-tab').tab('show');

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

	if (IS_ONLINE == 'true') {
		CHAT_DB.updateArchiveList();
	}

	// アーカイブ一覧取得＆表示
	var archiveList = CHAT_DB.getArchiveList();

	archiveList.forEach(function(archive) {
		var archiveType = '';
		var css = '';
		switch(archive.archiveType) {
			case 0:
				archiveType = getLocalizedString("archiveTypeImage");
				css = 'type_image';
				break;
			case 1:
				archiveType = getLocalizedString("archiveTypeMovie");
				css = 'type_movie';
				break;
			case 2:
				archiveType = getLocalizedString("archiveTypeSound");
				css = 'type_sound';
				break;
			case 3:
				// 今回のリリースに文書とその他は含めないため非表示
				archiveType = getLocalizedString("archiveTypeDocument");
				css = 'type_document';
				break;
			default:
				// 今回のリリースに文書とその他は含めないため非表示
				archiveType = getLocalizedString("archiveTypeOther");
				css = 'type_other';
		}

		let html = Mustache.render(archiveTemplate, {
			id: archive.archiveId,
			fileName: archive.archiveName,
			thumbnailImage: archive.archiveUrl,
			insertDate: archive.archiveDate,
			archiveType: archiveType,
			archiveTypeCSS: css
		});

		let obj = $(jQuery.parseHTML(html)).on('click', function() {
			// アーカイブ詳細画面へ遷移
			$('#homeButton').hide();
			$('.titleRoomName').show();
			$('#archive_list').hide();
			$('#archive_detail').show();
			$('#bottomNav').hide();
			$("#backButton").show();
			$('#backButton').off().on('click', function() {
				// アーカイブ一覧に戻る
				$('#homeButton').show();
				$("#backButton").hide();
				$('.titleRoomName').show();
				$('#archive_detail').hide();
				$('#archive_list').show();
				$('#bottomNav').show();
			});
			// データの受け渡し
			CHAT_UI.refreshArchiveDetailScreen(archive.archiveId);
		});

		$('#archive_list').append(obj);
		$('.archive_list').css('border-bottom', '1px solid #c4c4c4');
	})

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

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

	//画面タイトル設定
	let archiveDetailTitle = getLocalizedString("archiveDetailTitle");
	$('.titleRoomName').text(archiveDetailTitle);

	// 初期化
	$('#archive_detail').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 roomInfo = CHAT_DB.getChatRoomInfo(roomId);

   	// アーカイブ情報を表示
   	let html = Mustache.render(archiveDetailTemplate, {
		fileNameTitle: getLocalizedString("fileNameTitle"),
		fileName: archive.archiveName,
		saveDateTitle: getLocalizedString("saveDateTitle"),
 		insertDate: archive.archiveDate,
		roomNameTitle: getLocalizedString("roomNameTitle"),
   		chatRoomName: roomInfo.chatRoomName,
		saveUserTitle: getLocalizedString("saveUserTitle"),
 		attendUserTitle: getLocalizedString("attendUserTitle")
  	});
	let obj = $(jQuery.parseHTML(html));
	$('#archive_detail').append(obj);

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

	// チャットルームへのリンク付け
 	document.getElementById('joinChatRoom').onclick = function() {
 		socket.emit('joinRoom', roomId, roomInfo.chatRoomName, function () {
  			$('#archive_detail').html('');
			$('#messages').html('');
			$('.titleRoomName').text(roomInfo.chatRoomName).data('roomName', roomInfo.chatRoomName);
			$('#pills-chat-tab').tab('show');
		});
	}

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

	// 保存ユーザ情報を表示
	let saveUserList = archive.saveUserId;
	saveUserList.forEach(function(user) {
		// TODO ユーザIDからユーザ情報を取得
		let html = Mustache.render(archiveUserTemplate, {
 			profileImage: "プロフィール画像",
 			userName: "ユーザ名"
 		});

 		let obj = $(jQuery.parseHTML(html)).on('click', function() {
			//TODO ネームカードのポップアップを出す処理
		});

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

	// 参加ユーザ情報を表示
	let attendUserList = archive.attendUserId;
	attendUserList.forEach(function(user) {
		// TODO ユーザIDからユーザ情報を取得
		let html = Mustache.render(archiveUserTemplate, {
 			profileImage: "プロフィール画像",
 			userName: "ユーザ名"
 		});

 		let obj = $(jQuery.parseHTML(html)).on('click', function() {
			//TODO ポップアップを出す処理
		});

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

	// loadingIndicatorを非表示
	CHAT_UI.dismissLoadingIndicator();
}
<<<<<<< HEAD
=======
>>>>>>> origin/develop_apply_design_chat
>>>>>>> origin/develop_createRoom_UI
