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

includeJs("./js/chat-ui-clickEvents.js");
includeJs("./js/chat-ui-collaboration.js");

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

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

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

//上にスクロールすると新しいメッセージを呼ぶ処理。
$("#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();
};

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

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
            createChatRoom(
              ChatRoomType.DM,
              userIdList,
              newRoomName,
              MakeRoomFlag.MAKE_ROOM,
              false
            );
          } 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);
            createChatRoom(
              ChatRoomType.DM,
              userIdList,
              encodedRoomName,
              MakeRoomFlag.MAKE_ROOM,
              false
            );
          }
        }
      }
    });

  $("#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();
};
var GetFileBlobUsingURL = function (url, convertBlob) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url);
  xhr.responseType = "blob";
  xhr.addEventListener("load", function () {
    console.log(xhr.response);
    convertBlob(xhr.response);
  });
  xhr.send();
};
var blobToFile = function (blob, name) {
  blob.lastModifiedDate = new Date();
  blob.name = name;
  return blob;
};
var GetFileObjectFromURL = function (filePathOrUrl, convertBlob) {
  GetFileBlobUsingURL(filePathOrUrl, function (blob) {
    convertBlob(blobToFile(blob, "testFile.mp4"));
  });
};

CHAT_UI.videoEncodeFail = function () {
  alert(getLocalizedString("error_send_video"));
  CHAT_UI.dismissLoadingIndicator();
};

CHAT_UI.videoEncodeEnd = function (encodedUri) {
  var fileName = encodedUri.split("/")[encodedUri.split("/").length - 1];
  var fileURL = "file:" + encodedUri;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", fileURL);
  xhr.responseType = "blob";
  xhr.addEventListener("load", function () {
    var formData = new FormData();
    formData.append("image", xhr.response, fileName);
    formData.append("sid", CHAT.globalLoginParameter.sid);
    formData.append("roomId", CHAT.globalLoginParameter.roomId);
    jQuery
      .ajax({
        async: true,
        url: CMS_SERVER_URL + "/chatapi/file/upload",
        type: "post",
        data: formData,
        contentType: false,
        processData: false,
        error: function () {
          alert(getLocalizedString("error_send_video"));
          CHAT_UI.dismissLoadingIndicator();
        },
      })
      .done(function (res) {
        if (CHAT_UTIL.isAndroid()) {
          android.removeEncodedVideo(encodedUri);
        }
        var imgPath =
          CMS_SERVER_URL +
          "/chatapi/file/getImage?fileName=" +
          res.fileName +
          "&roomId=" +
          CHAT.globalLoginParameter.roomId;
        var imageName = res.fileName;

        // uploadFileの判断
        var extension = imageName
          .substr(imageName.lastIndexOf(".") + 1)
          .toLowerCase();

        if (res.thumbnailPath && res.thumbnailPath.length > 0) {
          imgPath =
            CMS_SERVER_URL +
            "/chatapi/file/getImage?fileName=" +
            res.thumbImageFileName +
            "&roomId=" +
            CHAT.globalLoginParameter.roomId;
        }
        let downloadPath =
          CMS_SERVER_URL +
          "/chatapi/file/download?fileName=" +
          imageName +
          "&roomId=" +
          CHAT.globalLoginParameter.roomId;
        var videoSrc =
          CMS_SERVER_URL +
          "/chatapi/file/getImage?fileName=" +
          res.fileName +
          "&roomId=" +
          CHAT.globalLoginParameter.roomId;
        const totalDiv = $("<div/>", { id: "attachedImages" });
        const videoTag = $("<video/>", {
          controls: "true",
          width: "auto",
          style: "max-width:100%",
        });
        const source = $("<source/>", { src: videoSrc });
        const downloadIcon = $("<a/>", {
          href: downloadPath,
          class: "fa fa-download",
          download: res.fileName,
        });
        videoTag.append(source);
        totalDiv.append(videoTag);
        totalDiv.append(downloadIcon);
        let text = totalDiv.prop("outerHTML");
        let encodedText;
        try {
          encodedText = encodeURIComponent(text);
        } catch (e) {
          encodedText = text;
        }
        socket.emit(
          "createMessage",
          {
            text: encodedText + messageSeperator + MessageType.VIDEO,
          },
          1
        );

        $(".overlay").removeClass("active undismissable");
        $(".loader").removeClass("active");
        CHAT_UI.dismissLoadingIndicator();
      });
  });
  xhr.send();
};

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.waitForLoadingVideo = function (div, callback) {
  CHAT_UI.showLoadingIndicator();
  //    var imgs = document.getElementsByTagName("video");
  var video = div.find("video");
  var count = video.length;
  if (count == 0) callback();
  var loaded = 0;
  video.each(function () {
    this.addEventListener("loadeddata", function (e) {
      loaded++;
      if (loaded === count) {
        callback();
        CHAT_UI.dismissLoadingIndicator();
      }
    });
  });
};

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

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

  // グループの様式を読み込む
  const groupTemplate = getTemplate(TemplateURL.GROUP_LIST);
  // ユーザの様式を読み込む
  var userTemplate = getTemplate(TemplateURL.USER_LIST);

  var myNamecardTemplate = getTemplate(TemplateURL.MY_NAME_CARD);

  var groupUserTemplate = getTemplate(TemplateURL.GROUP_USER_LIST);
  updateContactInfo();

  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) {
  if (IS_ONLINE == "true") {
    CHAT_UI.refreshForOnline();
  } else {
    CHAT_UI.refreshForOffline();
  }
  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 = getTemplate(TemplateURL.ROOM_LIST);

  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 協業の場合処理追加必要
    switch (room.messageType) {
      case MessageType.TEXT:
        displayMsg = room.message;
        break;
      case MessageType.IMAGE:
        displayMsg = getLocalizedString("image");
        break;
      case MessageType.VIDEO:
        displayMsg = getLocalizedString("video");
        break;
      case MessageType.COMMUNICATIONSTART:
        displayMsg = getLocalizedString("collaboration_start");
        break;
      case MessageType.COMMUNICATIONEND:
        displayMsg = getLocalizedString("collaboration_end");
        break;
      default:
        break;
    }
    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(", ");
    }
    var unreadMessageCount = room.unreadCount == 0 ? "" : room.unreadCount;
    if (unreadMessageCount > 999) {
      unreadMessageCount = "999+";
    }
    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: unreadMessageCount,
      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:
    }
  });

  console.log("DONE");
  CHAT_UI.dismissLoadingIndicator();
};

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

CHAT_UI.loadMessages = function (roomId, joinRoomName) {
  roomName = joinRoomName;
  var now = new Date();
  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");

  var userTemplate = getTemplate(TemplateURL.USER_LIST);

  var topUserListTemplate = getTemplate(TemplateURL.CHATROOM_USER_LIST);

  var filterUserListTemplate = getTemplate(
    TemplateURL.CHATROOM_USER_FILTER_LIST
  );

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

  CHAT_UI.prependMessage(messages);

  CHAT_UI.waitForLoadingImage(jQueryMessages, CHAT_UI.scrollToBottom);
  CHAT_UI.waitForLoadingVideo(jQueryMessages, CHAT_UI.scrollToBottom);
  // ユーザ削除ボタン表示しない
  $("#userSelectionDeleteBtn").hide();

  if (CHAT_UTIL.isIOS()) {
    $(window).on('load', function() {
      CHAT_UI.scrollToBottom();
    });
  }
};


CHAT_UI.prependMessage = function(messages) {
  var now = new Date();
  let jQueryMessages = $("#messages");
  // スクロールの変化を防ぐため以前画面の高さを保存する
  let beforeHeight = jQueryMessages.prop("scrollHeight");
  // メッセージ文字列の生成
  let workVal = "";
  var userTemplate = getTemplate(TemplateURL.USER_LIST);

  var userMessageTemplate = getTemplate(TemplateURL.USER_MESSAGE);

  var myMessageTemplate = getTemplate(TemplateURL.MY_MESSAGE);

  var systemMessageTemplate = getTemplate(TemplateURL.SYSTEM_MESSAGE);

  var openCollaborationMessageTemplate = getTemplate(
    TemplateURL.OPEN_COLLABORATION_MESSAGE
  );
  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;
    }
    if (
      message.messageType == MessageType.COMMUNICATIONSTART ||
      message.messageType == MessageType.COMMUNICATIONEND
    ) {
      template = openCollaborationMessageTemplate;
    }
    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 isOtherYear = false;
    var isToday = false;
    if (messageTime.createdAt.includes(":")) {
      isToday = true;
    }
    if (now.getFullYear() != message.insertDate.substring(0, 4)) {
      isOtherYear = 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;

    if (
      message.messageType == MessageType.COMMUNICATIONSTART ||
      message.messageType == MessageType.COMMUNICATIONEND
    ) {
      var collaborationInfo;
      var userInCollaboration;
      if (CHAT_UTIL.isIOS()) {
        collaborationInfo = JSON.parse(message.message);
        userInCollaboration = JSON.parse(
          CHAT_DB.getUserInfoList(collaborationInfo.userList)
        );
      } else if (CHAT_UTIL.isAndroid()) {
        collaborationInfo = JSON.parse(message.message);
        userInCollaboration = JSON.parse(
          android.getUserInfoList(collaborationInfo.userList)
        );
      }
      var meetingId = 0;
      if (typeof collaborationInfo.meetingId != "undefined") {
        meetingId = collaborationInfo.meetingId;
      }
      userInCollaboration.forEach(function (user) {
        user.profileUrl = CHAT.getProfileImgUrl(user.profileUrl);
      });
      let html = Mustache.render(template, {
        messageId: message.messageId,
        roomName: roomName,
        userCount: userInCollaboration.length,
        userList:
          userInCollaboration.length > 3
            ? userInCollaboration.slice(0, 3)
            : userInCollaboration,
        insertDate: message.insertDate,
        collaborationType: collaborationInfo.collaborationType,
        meetingId: meetingId,
        isToday: isToday,
        createdAtDay: messageTime.createdAtDay,
        createdAtTime: messageTime.createdAtTime,
        createdAtYear:
          message.insertDate.substring(0, 4) + getLocalizedString("year") + " ",
        isOtherYear: isOtherYear,
        isEnded:
          message.messageType == MessageType.COMMUNICATIONEND ? true : false,
      });
      html =
        message.message.includes("attachedImages") ||
        message.message.includes("attachedVideos")
          ? CHAT_UTIL.htmlDecode(html)
          : html;
      workVal = html + workVal;
    } else {
      let html = Mustache.render(template, {
        text: message.message,
        from: message.loginId,
        messageId: message.messageId,
        shopMemberId: message.shopMemberId,
        profileImage: message.profileUrl,
        createdAtDay: messageTime.createdAtDay,
        createdAtTime: messageTime.createdAtTime,
        createdAtYear:
          message.insertDate.substring(0, 4) + getLocalizedString("year") + " ",
        unreadCount: message.unreadCount,
        isOtherYear: isOtherYear,
        isToday: isToday,
      });
      html =
        message.message.includes("attachedImages") ||
        message.message.includes("attachedVideos")
          ? CHAT_UTIL.htmlDecode(html)
          : html;
      workVal = html + workVal;
    }
  });
  // メッセージの画面描画
  jQueryMessages.prepend(workVal);
}

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) {
  CHAT_UI.showLoadingIndicator();
  var result;
  if (typeof android != "undefined") {
    result = android.removeFavoriteGroup(groupId);
  } else {
    result = CHAT_DB.removeFavoriteGroup(groupId);
  }
  if (!result) {
    $(".group_" + groupId).addClass("active");
    $(".group_" + groupId).removeClass("disable");
  } else {
    $(".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");
  } else {
    $(".group_" + groupId).removeClass("disable");
    $(".group_" + groupId).addClass("active");
  }
  CHAT_UI.dismissLoadingIndicator();
};

//全グループ検索画面表示。
CHAT_UI.refreshAllGroupSearch = function (paramGroupId) {
  var groupId = paramGroupId;
  if (window.location.pathname.includes("chat_room")) {
    if (groupId == "") return;
    if (typeof android != "undefined") {
      android.setToMoveGroupId(groupId);
    } else {
      webkit.messageHandlers.setToMoveGroupId.postMessage(groupId);
    }
    window.location.href = "contact.html";
  }

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

  //オンライン状態であればサーバから情報更新。
  updateGroupInfo(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");
  }
  //該当グループのパースを表示。
  const groupPathTemplate = getTemplate(TemplateURL.GROUP_PATH);
  result.groupPathList.forEach(function (groupPath) {
    let html = Mustache.render(groupPathTemplate, {
      name: groupPath.groupName,
      id: groupPath.groupId,
    });
    let obj = jQuery.parseHTML(html);
    $("#groupPathArea").append(obj);
  });

  //該当グループの下位グループ表示。
  const groupTemplate = getTemplate(TemplateURL.GROUP_LIST);
  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);
  });

  //該当グループの所属ユーザを表示。
  const userTemplate = getTemplate(TemplateURL.USER_LIST);

  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;
  createChatRoom(
    ChatRoomType.DM,
    userIdList,
    newRoomName,
    MakeRoomFlag.NAME_CARD,
    false
  );
};

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

  // 参加ユーザ名でルーム名を生成
  let newRoomName = CHAT.globalLoginParameter.loginId + "," + userName;
  createChatRoom(
    ChatRoomType.DM,
    userIdList,
    newRoomName,
    MakeRoomFlag.NAME_CARD,
    true
  );
};

CHAT_UI.makeNameCard = function (shopMemberId) {
  if (CHAT.globalLoginParameter.shopMemberId == shopMemberId) {
    return;
  }
  var nameCardInfo = CHAT_DB.getNameCardData(shopMemberId);
  var namecardTemplate = getTemplate(TemplateURL.USER_NAME_CARD);

  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.refreshArchiveDetailScreen = function (archiveId) {
  // loadingIndicatorを表示
  CHAT_UI.showLoadingIndicator();

  // 初期化
  $("#archiveDetail").html("");

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

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

  // アーカイブ情報を表示
  const 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);

  // プレイヤーの切り替え
  const 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:
      if (CHAT_UTIL.isIOS()) {
        $("#archive_player").prepend(
          '<video class="archive_player" controls autoplay muted playsinline controlsList="nodownload"><source src="' +
            archiveFilePath +
            '" type="video/mp4"><source src="' +
            archiveFilePath +
            '" type="video/ogv"><source src="' +
            archiveFilePath +
            '" type="video/webm"></video>'
        );
      } else {
        $("#archive_player").prepend(
          '<video class="archive_player" src=' +
            archiveFilePath +
            ' controls autoplay muted playsinline controlsList="nodownload"></video>'
        );
      }
      break;
    case "2": // 音声
    case 2:
      if (CHAT_UTIL.isIOS()) {
        $("#archive_player").prepend(
          '<audio class="archive_audio_player" controls controlsList="nodownload"><source src="' +
            archiveFilePath +
            '" type="audio/wav"><source src="' +
            archiveFilePath +
            '" type="audio/ogg"></audio>'
        );
      } else {
        $("#archive_player").prepend(
          '<audio class="archive_audio_player" src=' +
            archiveFilePath +
            ' controls controlsList="nodownload"></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;
  if (typeof android != "undefined") {
    // ios実装不要
    attendUserList = JSON.parse(archive.attendUserIds);
  }

  attendUserList.forEach(function (user) {
    if (user == "") { return; }
    var userInfo = CHAT_DB.getUserInfo(user);
    userInfo.profileUrl = CHAT.getProfileImgUrl(userInfo.profileUrl);
    const html = Mustache.render(archiveUserTemplate, {
      profileImage: userInfo.profileUrl,
      userName: userInfo.shopMemberName,
    });

    const 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 = getTemplate(TemplateURL.MAKE_ROOM_GROUP_LIST);

  // ユーザの様式を読み込む
  var userTemplate = getTemplate(TemplateURL.MAKE_ROOM_USER_LIST);

  var groupUserTemplate = getTemplate(TemplateURL.MAKE_ROOM_GROUP_USER_LIST);

  updateContactInfo();

  //お気に入りグループ取得。
  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);

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

  //オンライン状態であればサーバから情報更新。
  updateGroupInfo(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 = getTemplate(TemplateURL.MAKE_ROOM_GROUP_PATH);

  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 = getTemplate(TemplateURL.MAKE_ROOM_GROUP_LIST);

  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 = getTemplate(TemplateURL.MAKE_ROOM_USER_LIST);

  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.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.svg";
        break;
      case 1: // 動画
        typeImage = "icon/icon_collabo_videocam.svg";
        break;
      case 2: // 音声
        typeImage = "icon/icon_collabo_headset.svg";
        break;
      case 3: // 文書
        typeImage = "icon/icon_collabo_document.svg";
        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.showMakeRoomConfirmView = function () {
  $("#selectedUserList").html("");

  var userTemplate = getTemplate(TemplateURL.MAKE_ROOM_CONFIRM_USER_LIST);

  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(",");
        createChatRoom(
          ChatRoomType.DM,
          userIdList,
          newRoomName,
          MakeRoomFlag.MAKE_ROOM,
          false
        );
      } 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);
        });

        // TODO: check why here using trimmedroomname instead of encodedRoomName
        // ルーム名のtrimmingした後、URIencodingを行う
        const encodedRoomName = encodeURIComponent(trimmedRoomName);
        createChatRoom(
          ChatRoomType.DM,
          userIdList,
          trimmedRoomName,
          MakeRoomFlag.MAKE_ROOM,
          false
        );
      }
    });
};

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

  var userTemplate = getTemplate(TemplateURL.ADD_USER_CONFIRM_USER_LIST);
  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);
  });

  $("#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(","), false);
      } 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 = getTemplate(TemplateURL.ADD_USER_GROUP_LIST);

  // ユーザの様式を読み込む
  var userTemplate = getTemplate(TemplateURL.ADD_USER_USER_LIST);
  var groupUserTemplate = getTemplate(TemplateURL.ADD_USER_GROUP_USER_LIST);

  updateContactInfo();

  //お気に入りグループ取得。
  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();

  $("#tabAllGroupOnAddUser").prop("checked", true);

  //オンライン状態であればサーバから情報更新。
  updateGroupInfo(groupId);

  //画面エリアを初期化。
  $("#parentGroupBtnForAddUser").off();
  $("#rootGroupBtnForAddUser").off();
  $("#childGroupListAreaForAddUser").html("");
  $("#userInGroupListForAddUser").html("");
  $("#groupPathAreaForAddUser").html("");

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

  //上位グループ、トップグループ遷移ボタンのイベント追加。
  if (typeof result.parentGroupId !== "undefined") {
    $("#parentGroupBtnForAddUser").on("click", function () {
      CHAT_UI.refreshAllGroupForAddUser(result.parentGroupId);
    });
  }
  if (typeof result.rootGroupId !== "undefined") {
    if (paramGroupId == 0) {
      groupId = result.rootGroupId;
    }
    $("#rootGroupBtnForAddUser").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 = getTemplate(TemplateURL.ADD_USER_GROUP_PATH);
  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);
      $("#groupPathAreaForAddUser").append(obj);
    }
    groupPathCount++;
  });

  //該当グループの下位グループ表示。
  var groupTemplate = getTemplate(TemplateURL.ADD_USER_GROUP_LIST);

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

    let obj = $(jQuery.parseHTML(html)).on("click", function () {});
    $("#childGroupListAreaForAddUser").append(obj);
  });

  //該当グループの所属ユーザを表示。
  const userTemplate = getTemplate(TemplateURL.ADD_USER_USER_LIST);
  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);
  $("#userInGroupListForAddUser").append(obj);
};

CHAT_UI.refreshForOnline = function () {
  IS_ONLINE = "true";
  $(".craeteRoomButton").off("click", CHAT_UI.offlineHandler);
  $(".craeteRoomButton").css("opacity", "1.0");
  $(".footer_item a").removeClass("ui-state-disabled");
  $("#videoUploadButton").removeClass("ui-state-disabled");
  $("#imageInputButton").removeClass("ui-state-disabled");
  $("#messageSend").prop("disabled", false);
  $("#messageInput").prop("disabled", false);
  $("#messageInput").prop("placeholder", "メッセージを入力してください");
  $("#favoriteButton").prop("disabled", false);
  $("#room_name_change_button").removeClass("ui-state-disabled");
  $("#add_user_button").removeClass("ui-state-disabled");
  $(".fa-download").show();
  if (typeof $("#roomTitle").val() != "undefined") {
    CHAT_SOCKET.connectSocket();
    socket.emit("join", CHAT.globalLoginParameter, function () {});
  }
};

CHAT_UI.refreshForOffline = function () {
  IS_ONLINE = "false";
  $(".craeteRoomButton").on("click", CHAT_UI.offlineHandler);
  $(".craeteRoomButton").css("opacity", "0.3");
  $(".footer_item a").addClass("ui-state-disabled");
  $("#videoUploadButton").addClass("ui-state-disabled");
  $("#imageInputButton").addClass("ui-state-disabled");
  $("#messageSend").prop("disabled", true);
  $("#messageInput").prop("disabled", true);
  $("#messageInput").prop("placeholder", "");
  $("#favoriteButton").prop("disabled", true);
  $("#room_name_change_button").addClass("ui-state-disabled");
  $("#add_user_button").addClass("ui-state-disabled");
  $(".fa-download").hide();
  if (typeof coview_api == "undefined") {
    return;
  }
  var alertString = "";
  if (g_isMainMan) {
    alertString = getLocalizedString("err_weak_network_exit_collaboration");
  } else {
    alertString = getLocalizedString("err_weak_network_exit_collaboration");
  }
  alert(alertString);
  if (CHAT_UTIL.isIOS()) {
    webkit.messageHandlers.finishCollaboration.postMessage({});
  }
  if (collaborationJoinFlg != "2") {
    CHAT_UI.joinRoom(
      CHAT.globalLoginParameter.roomId,
      CHAT.globalLoginParameter.name
    );
  } else {
    if (typeof android != "undefined") {
      android.openCommunicationHome();
    } else {
      webkit.messageHandlers.openCommunicationHome.postMessage({});
    }
  }
};

CHAT_UI.offlineHandler = function (e) {
  e.preventDefault();
};

CHAT_UI.displayExistRoom = function (roomId) {
  if (confirm("error_already_exist_same_user")) {
    if (CHAT_UTIL.isIOS()) {
      webkit.messageHandlers.joinRoom.postMessage({ roomId: roomId });
    } else if (CHAT_UTIL.isAndroid()) {
      android.joinRoom(roomId, "");
    }
  }
  return;
};

var createChatRoom = function (
  chatRoomType,
  userIDList,
  newRoomName,
  screenFlag,
  isVoice
) {
  //todo android create room api
  if (typeof android != "undefined") {
    android.createChatRoom(
      chatRoomType,
      userIDList.join(","),
      newRoomName,
      screenFlag,
      isVoice
    );
  } else {
    webkit.messageHandlers.createChatRoom.postMessage({
      roomType: chatRoomType,
      userIdList: userIDList.join(","),
      roomName: newRoomName,
      screenFlag: screenFlag,
      isVoice: isVoice,
    });
  }
};

var updateContactInfo = function () {
  if (IS_ONLINE == "true") {
    if (typeof android != "undefined") {
      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 updateGroupInfo = function (groupID) {
  if (IS_ONLINE == "true") {
    if (typeof android != "undefined") {
      android.updateGroupUser();
    } else {
      webkit.messageHandlers.updateGroupInfo.postMessage(groupID);
    }
  }
};
