String.prototype.replaceAll = function (org, dest) {
  return this.split(org).join(dest);
};

function includeJs(jsFilePath) {
  var js = document.createElement("script");

  js.type = "text/javascript";
  js.src = jsFilePath;

  document.body.appendChild(js);
}

function getTemplate(url) {
  var template;
  $.get({ url: url, async: false }, function (text) {
    template = text;
  });
  return template;
}

function getNoResultMessage() {
  const noResultMsg = $("<div/>", {
    width: "auto",
    style: "text-align: center",
  });
  noResultMsg.append(getLocalizedString("noResult"));
  return noResultMsg;
}

// アコーディオン
$(".category").on("click", function () {
  $(this).toggleClass("open");
  $(this).next().slideToggle();
});

$(".home_btn").on("click", function () {
  NativeBridgeDelegate.goHome();
});

document.addEventListener("DOMContentLoaded", function () {
  console.log("peacekim:: DOMContentLoaded on common.js");

  // ローディング表示
  $("footer a").click(function (event) {
    const a = $(this);
    event.preventDefault();
    Common.showLoadingIndicator();

    setTimeout(function () {
      window.location.href = a[0].href;
    }, 1000);
  });

  // 共通検索フォーム　キャンセルボタン表示
  $('.search_form input[type="search"]').click(function () {
    $(this).addClass("focus");
    // キャンセルボタン表示
    $(".cancel").removeClass("none");
    $(".search_form form").addClass("d-flex flex-row h-100 align-items-center");
    $(".content").addClass("none");
    $(".craeteRoomButton").addClass("none");
  });

  // 共通検索フォーム　キャンセルボタン押下イベント
  $(".search_form .cancel").click(function () {
    $(this).addClass("none");
    $(".search_form input").removeClass("focus");
    $(".search_form input").val("");
    $(".search_form form").removeClass();
    $(".content").removeClass("none");
    $(".overlay_src_msg").empty();
    $(".craeteRoomButton").removeClass("none");
  });
});

document.addEventListener("readystatechange", () => {
  console.log("peacekim:: document.readyState: " + document.readyState);
  switch (document.readyState) {
    case "interactive":
      break;
    case "complete":
      if (typeof initialLoading != "undefined" && initialLoading) {
        break;
      }
      Common.dismissLoadingIndicator();
      break;
  }
});

var Common = {};

//loadingIndicatorを表示
Common.showLoadingIndicator = function () {
  console.log("peacekim:: Common.showLoadingIndicator");
  NativeBridgeDelegate.showLoadingIndicator();
};

//loadingIndicatorを表示しない
Common.dismissLoadingIndicator = function () {
  console.log("peacekim:: Common.dismissLoadingIndicator");
  NativeBridgeDelegate.hideLoadingIndicator();
};

Common.refreshForOnline = function () {
  Common.showLoadingIndicator();
  console.log("peacekim:: Common.refreshForOnline");
  serverInfo.isOnline = true;
  $(".footer_item a").removeClass("ui-state-disabled");
  if (typeof ChatList != "undefined") {
    ChatList.refreshForOnline();
  }
  if (typeof ChatRoom != "undefined") {
    ChatRoom.refreshForOnline();
  }
  if (typeof Namecard != "undefined") {
    Namecard.refreshForOnline();
  }
  if (document.readyState == "complete") {
    Common.dismissLoadingIndicator();
  }
};

Common.refreshForOffline = function () {
  console.log("peacekim:: Common.refreshForOffline");
  serverInfo.isOnline = false;
  $(".footer_item a").addClass("ui-state-disabled");
  if (typeof ChatList != "undefined") {
    ChatList.refreshForOffline();
  }
  if (typeof ChatRoom != "undefined") {
    ChatRoom.refreshForOffline();
  }
  if (typeof CollaborationUI != "undefined") {
    CollaborationUI.refreshForOffline();
  }
  if (typeof Namecard != "undefined") {
    Namecard.refreshForOffline();
  }
};

// #36170 画像パスが存在しない場合はデフォルトの画像を返す
// 存在する場合はプロフィール画像取得用APIのURLを生成して返す
Common.getProfileImgUrl = function (path) {
  console.log("peacekim:: Common.getProfileImgUrl");
  if (path == undefined || path == "") {
    return "./img/noImage.png";
  } else if (path.includes("/mnt")) {
    const userInfo = path.split("/").reverse();

    if (deviceInfo.isiOS()) {
      const receivedString = NativeBridgeDataSource.getCachedImage(userInfo[1]);
      if (receivedString == "" || receivedString == undefined) {
        return Common.generateProfileImgURLFromServer(userInfo[0], userInfo[1]);
      }
      return "data:image/"+userInfo[0].split('.').pop()+";base64," + receivedString;
    }
    return Common.generateProfileImgURLFromServer(userInfo[0], userInfo[1]);
  } else {
    return path;
  }
};

Common.generateProfileImgURLFromServer = function (fileName, loginID) {
  return (
    serverInfo.cmsURL +
    "/chatapi/user?profileFileName=" +
    fileName +
    "&profileGetLoginId=" +
    loginID +
    "&sid=" +
    currentUserInfo.sid +
    "&cmd=12"
  );
};

Common.startCollaboration = function (collaborationType) {
  console.log(
    "peacekim:: Common.startCollaboration type: " + collaborationType
  );
  if (deviceInfo.isAndroid()) {
    if (
      collaborationType == COLLABORATION_TYPE.DOCUMENT &&
      deviceInfo.androidVersion < ANDROID_SDK_VERSION.O
    ) {
      alert(getLocalizedString("not_support_version"));
      Common.dismissLoadingIndicator();
      return;
    }
  }

  if ($(".collabo_area.start").length != 0) {
    if (!confirm(getLocalizedString("already_exist_collaboration"))) {
      Common.dismissLoadingIndicator();
      return;
    }
  }

  CHAT_SOCKET.emitCollaborationFinishMessage();
  NativeBridgeDelegate.finishAllCollaboration();
  NativeBridgeDelegate.startCollaboration(collaborationType);
  Common.dismissLoadingIndicator();
};
