let tmpImage = new Image();
tmpImage.src = $("#myImage").attr("src");

tmpImage.onload = function () {
  // Get original Image Dimensions
  $("body").append(tmpImage);
  imageWidth = $(tmpImage).width();
  imageHeight = $(tmpImage).height();
  imageAspect = imageWidth / imageHeight;

  $(tmpImage).remove();
};

// -------------- Zoom in & Zoom out Image -------------
let isToggled = false; // initial state (zoomed-out)

// Change the size of the image
function updateImageSize() {
  $("#myImage").css({
    width: isToggled ? imageWidth / 2 : "100%",
    height: isToggled ? imageHeight / 2 : "100%",
    cursor: isToggled ? "zoom-out" : "zoom-in",
  });
}
// Toggle the state
$("#myImage").click(function (e) {
  if (!isToggled) {
    var wrapper_width = $("#myImage").width();
    var wrapper_height = $("#myImage").height();

    // Get old image width and height before resize
    var Image_width = wrapper_width;
    var Image_height = wrapper_height;

    if (Image_height * imageAspect < Image_width) {
      Image_width = Image_height * imageAspect;
    } else {
      Image_height = Image_width / imageAspect;
    }

    offsetX = (wrapper_width - Image_width) / 2;
    offsetY = (wrapper_height - Image_height) / 2;

    var parentOffset = $(this).parent().offset();

    var relX = e.pageX - parentOffset.left;
    var relY = e.pageY - parentOffset.top;
    // Check if clicked inside image
    if (
      relX > offsetX &&
      relX < wrapper_width - offsetX &&
      relY > offsetY &&
      relY < wrapper_height - offsetY
    ) {
      isToggled = !isToggled;
      updateImageSize();

      AddedX = ((relX - offsetX) / Image_width) * 120 - 60;
      AddedY = ((relY - offsetY) / Image_height) * 120 - 60;

      var scrollX =
        (relX - offsetX) * ((imageWidth - wrapper_width + 10) / Image_width) +
        AddedX;
      var scrollY =
        (relY - offsetY) *
          ((imageHeight - wrapper_height + 10) / Image_height) +
        AddedY;

      $("#inner_container").scrollLeft(scrollX);
      $("#inner_container").scrollTop(scrollY);
    }
  } else {
    isToggled = !isToggled;
    updateImageSize();
  }
});
