You've got your container set to 500px max width and your img width to 100% so if you set the vertical height of the image to a value that requires a width > 500px to maintain the original aspect ration then your image will be cut off.
So either make the width of the container totally flexible or you can load the image into an Image object from which you can access the actual width and height properties of the image. Calculate the original aspect ratio. Then in your code set up a function that calculates the new dimensions of the image, maintaining the original aspect ratio, when you input either a new width or height. If the new width of the image is greater than the max width of the container then set the width of the image to the max width and set the height to the appropriate value for the max width and image's aspect raito.