/* --------------------------------------------------- */
/* Functions                                           */
/* --------------------------------------------------- */
let coview_api = new CoviewApi();
var isDocument = false;
var isBoard = false;
let isLeaved = false;
let timeInterval = null;
var backgroundFileName;
var isIos;

$(function () {
  var coviewApiActive = coview_api.Init({
    testSTRParam: "param1",
    testNUMParam: 77,
    testBOOLParam: false,
    coview_api_srv_addr: "https://biztaskyell.abookcloud.com",
    coview_wrap_id: "coviewShare",
    coview_api_key: "8dda7092c5820d663",
  });

  // special button IN Chat ui
  $("#coviewShareMainBtn").on("click", function (e) {
    e.stopPropagation();
    if ($(".coview_share_dropdown_bar").is(":visible") == true) {
      Coview_shareDropdownHide();

      if ($(".coview_share_photo_select_bubble").is(":visible") == true) {
        $(".coview_share_photo_select_bubble").slideUp();
      }
    } else {
      $(".coview_share_dropdown_bar").slideDown();
    }
  });

  $("#coviewShareCloseButton").on("click", function (e) {
    coview_api.LeaveRoom();
    $(".coview_share_area").hide();
  });

  $("body").on("click", function () {
    Coview_shareDropdownHide();

    if ($(".coview_share_photo_select_bubble").is(":visible") == true) {
      $(".coview_share_photo_select_bubble").slideUp();
    } else {
      $(".coview_share_dropdown_bar").slideDown();
    }
  });

  $(document).on("click", ".coview_share_request", function () {
    console.log("globalUserInfo", globalUserInfo);
    if ($(this).hasClass(collaborationTypeKey.VIDEO) == true) {
      globalUserInfo.coWorkType = collaborationTypeKey.VIDEO;
      $(".coview_share_title_name").text("LIVE");
    } else if ($(this).hasClass(collaborationTypeKey.CAMERA) == true) {
      globalUserInfo.coWorkType = collaborationTypeKey.CAMERA;
      $(".coview_share_title_name").text("ライブラリ");
    } else if ($(this).hasClass(collaborationTypeKey.AUDIO) == true) {
      globalUserInfo.coWorkType = collaborationTypeKey.AUDIO;
      $(".coview_share_title_name").text("音声通話");
    }

    coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();
  });

  /* --------------------------------------------------- */
  /* Video, photo, chat, doc                             */
  /* --------------------------------------------------- */
  $("#coviewShareChat").on("click", function () {
    console.log("ON click coviewShareChat");
  });

  $("#coviewSharePhoto").on("click", function (e) {
    e.stopPropagation();
    console.log("ON click coviewSharePhoto");

    if ($(".coview_share_photo_select_bubble").is(":visible") == true) {
      $(".coview_share_photo_select_bubble").slideUp();
    } else {
      $(".coview_share_photo_select_bubble").slideDown();
    }
  });

  $("#coviewSharePhotoCamera").on("click", function () {
    $(".coview_share_photo_select_bubble").hide();
    globalUserInfo.coWorkType = collaborationTypeKey.CAMERA;
    coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();

    $(".coview_share_title_name").text("カメラ");
  });
  $("#coviewSharePhotoGallery").on("click", function () {
    $(".coview_share_photo_select_bubble").hide();
    globalUserInfo.coWorkType = "gallery";
    coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();

    $(".coview_share_title_name").text("ライブラリ");
  });

  $("#coviewShareAudio").on("click", function () {
    Coview_connect_audio_collaboration();
  });

  $("#coviewShareLive").on("click", function () {
    console.log("ON click coviewShareLive");
    globalUserInfo.coWorkType = "video";
    console.log("globalUserInfo", globalUserInfo);

    coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
    Coview_moveToVideoShareArea();

    $(".coview_share_title_name").text("LIVE");
  });

  coview_api.addEventListener("ready", function () {
    console.log("=============> READY : ready for coview api");
    Coview_addLoginId(globalUserInfo.loginId);
    coview_api.Login(globalUserInfo.loginId);
    initCollaborationUI(joinCollaborationType)
    fw.socket.on('message', async function(data) {
      console.log('====> message::data: ', data);
      if (data.type ==="CHANGE_COLLABORATION") {
        if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
          if (CHAT_UTIL.isIOS()) {
            webkit.messageHandlers.exitMeetingRoom.postMessage({});
          } else if (CHAT_UTIL.isAndroid()) {
            android.exitMeetingRoom();
          }
        }

        if (CHAT_UTIL.isAndroid() && data.payload.collaborationType == COLLABORATION_TYPE.DOCUMENT && androidVersion < ANDROID_SDK_VERSION.O) {
          alert(getLocalizedString('not_support_version'));
          joinCollaborationType = COLLABORATION_TYPE.CAMERA;
        } else {
          joinCollaborationType = data.payload.collaborationType;
        }
        joinMeetingId = data.payload.newMeetingId;
        initCollaborationUI(joinCollaborationType);

        if (CHAT_UTIL.isIOS()) {
          webkit.messageHandlers.joinChangedCollaboration.postMessage({"joinCollaborationType": joinCollaborationType, "meetingId": data.payload.newMeetingId});
          webkit.messageHandlers.joinMeetingRoom.postMessage(data.payload.newMeetingId);
        } else if (CHAT_UTIL.isAndroid()) {
          android.joinChangedCollaboration(joinCollaborationType, data.payload.newMeetingId);
          if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
            android.joinMeetingRoom(data.payload.newMeetingId);
          }
        }
      } else if (data.type ==="SHARE_FILE") {
        if (joinCollaborationType != COLLABORATION_TYPE.CAMERA) {
          initCollaborationUI(COLLABORATION_TYPE.CAMERA);
          joinCollaborationType = COLLABORATION_TYPE.CAMERA;
          fw.sendToMsg('others', 'SHARE_FILE_HOST', {"collaborationType": COLLABORATION_TYPE.CAMERA});
        }
      } else if (data.type ==="SHARE_FILE_HOST") {
        if (joinCollaborationType != COLLABORATION_TYPE.CAMERA && g_isMainMan) {
          initCollaborationUI(COLLABORATION_TYPE.CAMERA);
          joinCollaborationType = COLLABORATION_TYPE.CAMERA;
        }
      } else if (data.type === "CAPTURE_REQUEST" && g_isMainMan) {
        if (confirm(data.payload.name + getLocalizedString("request_capture"))) {
          captureAndShareImage(CMS_SERVER_URL + '/chatapi/file/uploadArchive', data.payload.name);
        }
      } else if (data.type === "HOST_CHANGE_REQUEST") {
        if (data.payload.loginId == globalUserInfo.loginId) {
          fw.sendToMsg('others', 'HOST_CHANGE_RESPONSE', {"isAndroid": CHAT_UTIL.isAndroid(), "isAble" : androidVersion >= ANDROID_SDK_VERSION.O, "loginId": CHAT.globalLoginParameter.loginId});
        }
      } else if (data.type === "HOST_CHANGE_RESPONSE") {
        var isAndroid = data.payload.isAndroid;
        var isAble = data.payload.isAble
        if (g_isMainMan && isAndroid && !isAble && joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
          alert(getLocalizedString('err_target_android_version_not_support'));
        } else {
          Coview_changeHost(getFermiLoginId(data.payload.loginId));
        }
      } else if (data.type === "API_SEND_OWNER_CHANGE_COMPLETE") {
        if ($('#recordBtn').hasClass('bg_red')) {
          recordStop();
        }
        penOff();
      } else if (data.type === "CHANGE_HOST_APPLY") {
        if(confirm(getLocalizedString('norify_request_host_change',data.payload.hostId))) {
          Coview_changeHost(getFermiLoginId(data.payload.hostId));
        }
      }
    });
  });

  coview_api.addEventListener("start", function () {
    console.log("=============> START : share start");
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("allbye", function () {
    console.log("=============> ALL BYE : share allbye");
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("guestbye", function () {
    console.log("=============> GUEST BYE : share guestbye");
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("hostbye", function () {
    console.log("=============> HOST BYE : share hostbye");
    alert(getLocalizedString("inform_exit_host_collaboration"));
    Coview_exitCollaboration();
    $("#loadingIndicator").removeClass("full_active");
  });

  coview_api.addEventListener("destroy", function () {
    console.log("=============> DESTROY : share destroy");
    coview_api.LeaveRoom();
    $(".coview_share_area").hide();
    $("#loadingIndicator").removeClass("full_active");
  });
    
  var meetingId;
    
  coview_api.addEventListener("message", async function (event, json) {
    console.log("+++ addEventListener", json);
    console.log("processMessage api = ", json.api);
    if (isLeaved) return;
    let loginIdList = new Array();
    switch (json.api) {
      case "LoginResponse":
        if (globalUserInfo.coWorkType == collaborationTypeKey.DOCUMENT) {
          isDocument = true;
          globalUserInfo.coWorkType = collaborationTypeKey.AUDIO;
        }
        if (globalUserInfo.coWorkType == collaborationTypeKey.BOARD) {
          isBoard = true;
          globalUserInfo.coWorkType = collaborationTypeKey.CAMERA;
        }
        hostSearchInterval();
        if (collaborationJoinFlg == "1") {
          coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
          if (isDocument) {
            if (CHAT_UTIL.isIOS()) {
              webkit.messageHandlers.startContentView.postMessage({});
            } else if (CHAT_UTIL.isAndroid()) {
              android.startContentView();
            }
          }
        } else if (collaborationJoinFlg == "0") {
          coview_api.CreateRoom(
            globalUserInfo.roomId,
            globalUserInfo.coWorkType
          );
          if (isDocument) {
            if (CHAT_UTIL.isIOS()) {
              meetingId = CHAT_DB.createContentView();
            } else if (CHAT_UTIL.isAndroid()) {
              meetingId = android.createContentView();
            }
          }
        } else if (collaborationJoinFlg == "2") {
          coview_api.JoinRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
        }
        Coview_moveToVideoShareArea();

        break;
      case "CreateRoomResponse":
        if (json.resultCode == 200) {
          var coviewInviteMessage;
          if (isDocument) {
            coviewInviteMessage =
              "" +
              messageSeperator +
              messageType.COMMUNICATIONSTART +
              messageSeperator +
              CHAT_UTIL.getCollaborationType(collaborationTypeKey.DOCUMENT) +
              messageSeperator +
              meetingId;
          } else if (isBoard) {
            coviewInviteMessage =
              "" +
              messageSeperator +
              messageType.COMMUNICATIONSTART +
              messageSeperator +
              COLLABORATION_TYPE.BOARD;
          } else {
            coviewInviteMessage =
              "" +
              messageSeperator +
              messageType.COMMUNICATIONSTART +
              messageSeperator +
              CHAT_UTIL.getCollaborationType(globalUserInfo.coWorkType);
          }
          socket.emit(
            "createMessage",
            {
              text: coviewInviteMessage,
            },
            0
          );
          if (isBoard) {
            $('#open_file_upload').on("click",function(e){
                e.preventDefault();
            });
          }
        } else {
        }
        break;
      case "JoinRoomInfoResponse":
        if (json.resultCode == 200) {
        } else {
          alert(
            "Not exist sharing call (" +
              json.resultCode +
              ")\nPlease using share menu."
          );
          coview_api.LeaveRoom();
          $(".coview_share_area").hide();
          $("#loadingIndicator").removeClass("full_active");
        }
        break;
      case "JoinRoomResponse":
        if (json.resultCode == 200) {
          hostSearchInterval();
          for (let key in g_participants) {
            loginIdList.push(key);
          }
          CHAT_UI.refreshJoinedCollaboration(loginIdList);
        } else {
        }
        break;
      case "RoomMemberJoinedEvent":
        for (let key in g_participants) {
          loginIdList.push(key);
        }
        CHAT_UI.refreshJoinedCollaboration(loginIdList);
        break;
      case "RoomMemberLeavedEvent":
        for (let key in g_participants) {
          loginIdList.push(key);
        }
        CHAT_UI.refreshJoinedCollaboration(loginIdList);
        break;
      case "HostRequest":
        // to be called by
        // wc_api.dispatchEvent (new Event ("message"), {"HostRequest":"userID"});
        console.log("consoleLog", json);
        break;
      case "fileChange":
        LoadMobileShareFile(json.fileName);
        backgroundFileName = json.fileName;
        console.log("fileChange", json);
        break;
      case "ReceiveMediaResponse":
        if (isBoard && g_isMainMan) {
          wc_api.dispatchEvent (new Event ("message"), {"api":"fileChange","fileName":backgroundFileName});
        }
        break;
      default:
        console.log("Unrecognized api", json);
        break;
    }
  });
});

function Coview_shareDropdownHide() {
  $(".coview_share_dropdown_bar").slideUp();
  $(".coview_share_photo_select_bubble").slideUp();
}

function Coview_moveToVideoShareArea() {
  $("#loadingIndicator").addClass("full_active");
  $(".coview_share_area").show();
  $("#collabo_main").removeClass("none");
}

function changeCollaboration(changeCollaborationType) {
  var newMeetingId = 0;
  if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT) {
    if (CHAT_UTIL.isIOS()) {
        webkit.messageHandlers.exitMeetingRoom.postMessage({});
    } else if (CHAT_UTIL.isAndroid()) {
        android.exitMeetingRoom();
    }
  }
  if (CHAT_UTIL.isIOS()) {
    webkit.messageHandlers.setJoinCollaborationType.postMessage(changeCollaborationType);
  } else if (CHAT_UTIL.isAndroid()) {
    if (changeCollaborationType == COLLABORATION_TYPE.DOCUMENT && androidVersion < ANDROID_SDK_VERSION.O) {
      alert(getLocalizedString('not_support_version'));
      return;
    }
    android.setJoinCollaborationType(changeCollaborationType);
  }
  joinCollaborationType = changeCollaborationType;
  if ($('#recordBtn').hasClass('bg_red')) {
    recordStop();
  }
  initCollaborationUI(changeCollaborationType);
  switch (changeCollaborationType) {
    case COLLABORATION_TYPE.AUDIO:
      coview_api.ChangeCollaboration('audio');
      break;
    case COLLABORATION_TYPE.CAMERA:
      coview_api.ChangeCollaboration('image');
      break;
    case COLLABORATION_TYPE.VIDEO:
      coview_api.ChangeCollaboration('video');
      break;
    case COLLABORATION_TYPE.DOCUMENT:
      coview_api.ChangeCollaboration('audio');
      if (CHAT_UTIL.isIOS()) {
        newMeetingId = CHAT_DB.createContentView();
      } else if (CHAT_UTIL.isAndroid()) {
        newMeetingId = android.createContentView();
        console.log('newMeetingId = ' + newMeetingId);
      }
      break;
    case COLLABORATION_TYPE.BOARD:
      coview_api.ChangeCollaboration('audio');
      break;
  }
  penOff();
  if (CHAT_UTIL.isIOS()) {
    webkit.messageHandlers.changeCollaboration.postMessage({"changeCollaborationType": changeCollaborationType, "meetingId": newMeetingId});
  } else if (CHAT_UTIL.isAndroid()) {
    android.changeCollaboration(changeCollaborationType, newMeetingId);
  }
  fw.sendToMsg('others', 'CHANGE_COLLABORATION', {"collaborationType": changeCollaborationType, "newMeetingId": newMeetingId});
}

function initCollaborationUI(changeCollaborationType){
  if ($('.user_btn').hasClass("hide")) {
    $('.user_btn').click();
  }
  if ($('.menu_btn').hasClass("hide")) {
    $(".menu_btn").click();
  }
  if (CHAT_UTIL.isIOS) {
    roomType = CHAT_DB.getRoomType();
    if (roomType == chatRoomType.DM) {
      $('.add_user_btn').removeClass('none');
    }
  }
  $("link[href='./css/collaboration_board.css']").remove();
  penOff();
  switch (changeCollaborationType) {
    case COLLABORATION_TYPE.AUDIO:
      $('.collaboration_contents').addClass('none');
      $('.voice_contents').removeClass('none');
      var w = $('.user_btn').width();
      $('.user_btn').toggleClass("hide");
      $("#overlay_user_list.overlay")
        .toggleClass("slidein")
        .css({ transform: "translateX(" & -w & ")" });
      $("#collabo_main").toggleClass("noscroll");
      if ($("#overlay_user_list.overlay").hasClass("noscroll")) {
        $("#overlay_user_list.overlay").removeClass("noscroll");
      } else {
        $("#overlay_user_list.overlay").addClass("noscroll");
      }
      break;

    case COLLABORATION_TYPE.CAMERA:
      $('.collaboration_contents').addClass('none');
      $('.picture_contents').removeClass('none');
      break;

    case COLLABORATION_TYPE.VIDEO:
      $('.collaboration_contents').addClass('none');
      $('.video_contents').removeClass('none');
      break;

    case COLLABORATION_TYPE.DOCUMENT:
      $('.collaboration_contents').addClass('none');
      $('.document_contents').removeClass('none');
      var w = $('.user_btn').width();
      $('.user_btn').toggleClass("hide");
      $("#overlay_user_list.overlay")
        .toggleClass("slidein")
        .css({ transform: "translateX(" & -w & ")" });
      $("#collabo_main").toggleClass("noscroll");
      if ($("#overlay_user_list.overlay").hasClass("noscroll")) {
        $("#overlay_user_list.overlay").removeClass("noscroll");
      } else {
        $("#overlay_user_list.overlay").addClass("noscroll");
      }
      break;

    case COLLABORATION_TYPE.BOARD:
      $('.collaboration_contents').addClass('none');
      $('.board_contents').removeClass('none');
      $('head').append('<link rel="stylesheet" href="./css/collaboration_board.css">');
      break;
  }
}

function Coview_exitCollaboration(isDocument = false) {
  if (isDocument) {
    if (CHAT_UTIL.isIOS()) {
      webkit.messageHandlers.exitMeetingRoom.postMessage({});
    } else if (CHAT_UTIL.isAndroid()) {
      android.exitMeetingRoom();
    }
  }
  if ($('#recordBtn').hasClass('bg_red')) {
    recordStop();
  }
  clearInterval(timeInterval);
  coview_api.LeaveRoom();
  if (coview_api.getRoomUsers()) {
    if (CHAT_UTIL.isIOS()) {
      webkit.messageHandlers.finishCollaboration.postMessage({});
    } else if (CHAT_UTIL.isAndroid()) {
      android.finishCollaboration() 
    }
  };
  isLeaved = true;
  if (collaborationJoinFlg != '2') {
    CHAT_UI.joinRoom(
      CHAT.globalLoginParameter.roomId,
      CHAT.globalLoginParameter.name
    );
  } else {
    if (typeof android != "undefined") {
      android.openCommunicationHome();
    } else {
      webkit.messageHandlers.openCommunicationHome.postMessage({});
    }
  }
}

function Coview_changeHost(userId) {
  console.log("Change Host To " + userId);
  changeOwnerSend(userId);
}

function Coview_addLoginId(loginId) {
  console.log("addUser loginId = " + loginId);
  var url = "https://biztaskyell.abookcloud.com/auth/getuser";
  $.ajax({
    url : url,
    method : 'post',
    data : {
      id : loginId
    },
    success : function (result) {
      console.log("result", result);
      if (result.statusCode != 200) {
        coview_api.addUser(loginId);
      }
    },
    error : function (err) {
      console.log(err.toString());
    }
  });
}

function applyForHostChange() {
  if (joinCollaborationType == COLLABORATION_TYPE.DOCUMENT && androidVersion < ANDROID_SDK_VERSION.O) {
    alert(getLocalizedString('not_support_version'));
    return;
  }
  fw.sendToMsg('others', 'CHANGE_HOST_APPLY', {"hostId": CHAT.globalLoginParameter.loginId});
};

function Coview_connect_audio_collaboration() {
  globalUserInfo.coWorkType = collaborationTypeKey.AUDIO;
  coview_api.CreateRoom(globalUserInfo.roomId, globalUserInfo.coWorkType);
  Coview_moveToVideoShareArea();

  $(".coview_share_title_name").text("音声通話");
}

function hostSearchInterval() {
  let hostName = "";
  function hostSearch() {
    if (g_isMainMan) {
      $("#collaboration_user_" + CHAT.globalLoginParameter.loginId).addClass("host");
      $('.host_contents').removeClass('none');
      if (joinCollaborationType == COLLABORATION_TYPE.CAMERA) {
        $('.photo_select_button').removeClass('none');
      }
      if (joinCollaborationType == COLLABORATION_TYPE.VIDEO) {
        $('.video_contents_host').removeClass('none');
        $('.video_contents_user').addClass('none');
      }
      if (CHAT_UTIL.isIOS()) isIos = true;
    } else {
      $("#collaboration_user_" + CHAT.globalLoginParameter.loginId).removeClass("host");
      $('.host_contents').addClass('none');
      if (joinCollaborationType == COLLABORATION_TYPE.CAMERA) {
        $('.photo_select_button').addClass('none');
      }
      if (joinCollaborationType == COLLABORATION_TYPE.VIDEO) {
        $('.video_contents_user').removeClass('none');
        $('.video_contents_host').addClass('none');
      }
    }
    if (hostName != g_isMainManUsername) {
      if (hostName != "") {
        $("#collaboration_user_" + getReplacedLoginId(hostName)).removeClass("host");
      }
      $("#collaboration_user_" + getReplacedLoginId(g_isMainManUsername)).addClass("host");
      hostName = g_isMainManUsername;
    } else {
      if (hostName == "") {
        if (!$("#collaboration_user_" + CHAT.globalLoginParameter.loginId).hasClass("host") && coview_api.getRoomUsers()) {
          $("#collaboration_user_" + CHAT.globalLoginParameter.loginId).addClass("host");
        }
      } else {
        if (!$("#collaboration_user_" + getReplacedLoginId(hostName)).hasClass('host')) {
          $("#collaboration_user_" + getReplacedLoginId(hostName)).addClass("host");
        }

      }
    }
  }
  timeInterval = setInterval(hostSearch, 2000);
}

function hostChangeRequest(loginId) {
    fw.sendToMsg('others', 'HOST_CHANGE_REQUEST', {"loginId": getFermiLoginId(loginId)});
}

function getFermiLoginId(loginId) {
  return globalUserInfo.shopName + '_' + loginId;
}

function getReplacedLoginId(loginId) {
  return  loginId.replaceAll(globalUserInfo.shopName + '_', '');
}

function captureAndShareImage(urls, changeHostName) {
  addCaptureEffect();
  $(this).removeClass("on");
  var w,h;
  var video = document.getElementById("localVideo");
  var canvas = document.createElement('canvas');
  if (clientOrientaionState == 1) {
    canvas.width  = w = 680;
    canvas.height = h = 515;
  } else {
    canvas.width  = w = 386;
    canvas.height = h = 515;
  }
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, w, h);
    ctx.drawImage(document.getElementById("canvasRemote"), 0, 0, w, h);
  }
  canvas.toBlob(function(blob) {
    var newImg = document.createElement('img')
    var url = URL.createObjectURL(blob);
    canvasRemote.style.backgroundImage = "url('"+ URL.createObjectURL(blob) + "')";
    canvasRemote.style.backgroundSize  = "contain";
    $(canvasRemote).attr("height", $(snapshots[cpatureViewIndex]).attr("height"));
    $(canvasRemote).attr("width", $(snapshots[cpatureViewIndex]).attr("width"));
    console.log ('url', URL.createObjectURL(blob));
    if ($(".canvas_wrap").css("width").replace("px","") / $(".canvas_wrap").css("height").replace("px","") < $(canvas).attr("width") / $(canvas).attr("height")) {
      var h = $(".canvas_wrap").css("width").replace("px","") * ($(canvas).attr("height") / $(canvas).attr("width"));
      var w = $(".canvas_wrap").css("width").replace("px","");
      $(canvasRemote).css("height", h);
      $(canvasRemote).css("width", w);
      $(canvasRemote).css("margin-top", (-h/2));
      $(canvasRemote).css("margin-left", (-w/2));
    } else {
      var h = $(".canvas_wrap").css("height").replace("px","");
      var w = $(".canvas_wrap").css("height").replace("px","") / ($(canvas).attr("height") / $(canvas).attr("width"));
      $(canvasRemote).css("height", h);
      $(canvasRemote).css("width", w);
      $(canvasRemote).css("margin-top", (-h/2));
      $(canvasRemote).css("margin-left", (-w/2));
    }
    $(".canvas_wrap").css("background-color", "#000");
    $(".clear_img").show();
    SetShareMenuState("on");
    WithImageShareBtnState("on");

    //Fermi側にイメージ保存。
    var formData = new FormData();
    var uploadFileName = "capture_share_" + g_webroom + "_" + g_shareCount + ".png"
    g_shareCount++;
    formData.append("imgFile", blob, uploadFileName);

    var uploadUrl = location.protocol + "//" + location.hostname + ":" + location.port + "/upload/create";
    if (!location.port) {
      uploadUrl = location.protocol + "//" + location.hostname + "/upload/create";
    }
    $.ajax({
      type: 'post',
      url: g_coviewapiserverADDR + "/upload/create",
      data: formData,
      processData: false,
      contentType: false,
      success: function(res) {
        setTimeout(function() {
          SendFileShare(uploadFileName);
          $("#coviewCaptureCtrBtn").hide();
          $("#coviewRecCtrBtn").hide();
          $(".coview_share_title_name").text("LIVE(CAPTURE IMAGE)");
          $(".coview_on_media_btn_back").show();
          //アーカイブ保存。
          ArchiveFileManage(blob,uploadFileName,urls);
        }, 1500);
      },
      error: function(err) {
        console.log(err);
      }
    });
  });
}