$(document).ready(function () {

  var show_success = function(successful, msg) {
    var flashDiv = document.createElement('div', {});

    // create button to close to alert
    var closeButton = document.createElement('button');
    closeButton.setAttribute('class', 'close');
    closeButton.setAttribute('data-dismiss', 'alert');
    closeButton.setAttribute('type', 'button');
    closeButton.textContent = 'x';


    var divClass = successful ? 'alert-success' :  'alert-danger';

    var divBaseClass = "alert fade in ";
    flashDiv.setAttribute('class', divBaseClass.concat(divClass));
    flashDiv.textContent = msg;
    flashDiv.append(closeButton);

    var existingFlashDiv = document.getElementsByClassName('alert-success')[0];
    $(flashDiv).insertAfter($(existingFlashDiv));
  }

  var upload_image = function(data, url) {

    $.ajax({
      url: url,
      type: 'PUT',
      data: data,
      cache: false,
      contentType: "image/png",
      processData: false,
      success: function(data, textStatus, jqXHR){
        show_success(true, "Image has been uploaded successfully.")
      },
      error: function(jqXHR, textStatus, error) {
        show_success(false, "Image upload failed, please try again.")
      }
    })
  }

  $('button[name=upload_image]').on("click", function(event) {
    event.preventDefault()
    var form = $("form#new_attachments_hosted_image")
    var data = form.find('input[id=attachments_hosted_image_data]')[0].files[0]
    var url = form.find('input[id=attachments_hosted_image_s3_url]')[0].value

    upload_image(data, url)
  });

});
