     @on "core:cancel", => @detach()
 
   handleEvents: ->
-    @imgEditor.hiddenInput.on "focusout", => @setImage(@imgEditor.getText())
+    @imgEditor.hiddenInput.on "focusout", =>
+      @displayImagePreview(@imgEditor.getText())
     @openImg.on "click", => @openImageDialog()
 
   onConfirm: ->
-    imgPath = @imgEditor.getText()
-    imgTitle = @titleEditor.getText()
-    if @isValidImageFile(imgPath)
-      @editor.insertText("![#{imgTitle}][#{imgPath}]")
+    img =
+      src: @imgEditor.getText()
+      alt: @titleEditor.getText()
+      width: @widthEditor.getText()
+      height: @heightEditor.getText()
+
+    @editor.insertText(@generateImageTag(img))
     @detach()
 
   detach: ->

    @previouslyFocusedElement = $(':focus')
    @editor = atom.workspace.getActiveEditor()
    atom.workspaceView.append(this)
    @imgEditor.focus()

  openImageDialog: ->
    files = dialog.showOpenDialog(properties: ['openFile'])
    return unless files

    file = files[0]
    if @isValidImageFile(file)
      @imgEditor.setText(file)
      @setImage(file)
      @message.text("Image: #{@imageWidth} x #{@imageHeight}")
    else
      @message.text("Error: Invalid Image File.")

  setImage: (file) ->
    return unless @isValidImageFile(file)
    @imageSrc = file
    @image.attr("src", file)
    @image.load =>
      @imageWidth = @image.context.naturalWidth
      @imageHeight = @image.context.naturalHeight

  moveLocalImage: (file) ->
    return unless isLocalImageFile(file)

  isValidImageFile: (file) ->
    path.extname(file) in imageExtensions

path = require "path"
fs = require "fs-plus"

imageExtensions = [".jpg", ".png", ".gif", ".bmp"]

module.exports =
class InsertImageView extends View
  imageOnPreview: null
  editor: null
  previouslyFocusedElement: null

