window.addInputFiles = function(inputEl) {
    $inputEl = $(inputEl);
    var clearedFileInput = $inputEl.clone().val('');
    var attachmentsContainer = $inputEl.parents(".attachments-container");

    if ($.ajaxSettings.xhr().upload && inputEl.files) {
        // upload files using ajax
        uploadAndAttachFiles(inputEl.files, inputEl);
        $inputEl.remove();
    } else {
        // browser not supporting the file API, upload on form submission
        var attachmentId;
        var aFilename = inputEl.value.split(/\/|\\/);
        attachmentId = addFile(inputEl, {
            name: aFilename[ aFilename.length - 1 ]
        }, false);
        if (attachmentId) {
            $inputEl.attr({
                name: 'attachments[' + attachmentId + '][file]',
                style: 'display:none;'
            }).appendTo('#attachments_' + attachmentId);
        }
    }
    attachmentsContainer.children(".add_attachment").prepend(clearedFileInput);
};

window.addFile = function(inputEl, file, eagerUpload) {
    $inputEl = $(inputEl);
    var limit = (typeof window.ATTACHMENT_LIMIT === typeof undefined ? 10 : window.ATTACHMENT_LIMIT);

    var attachmentsContainer = $inputEl.closest('.attachments-container')
    var fields = attachmentsContainer.find('#attachments_fields');
    var tagName = attachmentsContainer.attr("data-tag-name");

    if (fields.children().length < limit) {

        var attachmentId = addFile.nextAttachmentId++;

        var fileSpan = $('<span>', {
            id: 'attachments_' + attachmentId
        });

        fileSpan.append($('<input>', {
            type: 'text',
            'class': 'filename readonly ' + ($inputEl.data('description-is') ? 'half' : 'full'),
            name: tagName + '[' + attachmentId + '][filename]',
            readonly: 'readonly'
        } ).val(file.name));
        if ($inputEl.data('description-is')) {
            fileSpan.append($('<input>', {
                type: 'text',
                'class': 'description',
                name: tagName + '[' + attachmentId + '][description]',
                maxlength: 255,
                placeholder: $inputEl.data('description-placeholder'),
                required: $inputEl.data('description-is-required')
            } ).toggle(!eagerUpload));
        };
        fileSpan.append($('<a>&nbsp</a>').attr({
            href: "#",
            'class': 'remove-upload icon icon-del'
        }).click(removeFile).toggle(!eagerUpload));
        var customVersionAttID = $(inputEl).data("custom-version-for-attachment-id");
        if (customVersionAttID) {
            fileSpan.append($("<input>",{type: "hidden", value: customVersionAttID, name: tagName + '[' + attachmentId + '][custom_version_for_attachment_id]'}));
        }
        fileSpan.appendTo(fields);

        if(eagerUpload) {
            ajaxUpload(file, attachmentId, fileSpan, inputEl);
        }

        return attachmentId;
    }
    return null;
};
addFile.nextAttachmentId = 1;

window.handleFileDropEvent = function(e) {
    if (typeof(e.dataTransfer) === 'undefined') return;
    var self = $(this);
    self.removeClass('fileover');
    blockEventPropagation(e);

    var selector = self.find('input:file.file_selector');
    if(selector.length === 0) {
      selector = self.closest('.attachments-container').find('input:file.file_selector');
    }
    if ($.inArray('Files', e.dataTransfer.types) > -1) {
        uploadAndAttachFiles(e.dataTransfer.files, selector);
    }
};

window.setupFileDrop = function() {
    if (window.File && window.FileList && window.ProgressEvent && window.FormData && window.FileReader) {

        $.event.fixHooks.drop = {
            props: [ 'dataTransfer' ]
        };

        $('form').has('input:file').each(function () {
            var self = $(this);
            if (!self.data().fileDropsInitialized) {
                self.on({
                    dragover: dragOverHandler,
                    dragleave: dragOutHandler,
                    drop: handleFileDropEvent
                });
                self.data().fileDropsInitialized = true;
            }
        });
    }
};

window.uploadBlob = function(blob, uploadUrl, attachmentId, options) {
  var attachmentsContainer = $('#attachments_' + attachmentId).closest('.attachments-container');
  var tagName = attachmentsContainer.attr('data-tag-name');
  var dummyFileSelector = 'input[name="attachments[dummy][file]"]'
  var customVersionAttachmentId = null;

  if ($('div.modal').is(':visible')) {
    customVersionAttachmentId = parseInt($('div.modal').find(dummyFileSelector).attr('data-custom-version-for-attachment-id'));
  } else if ($(dummyFileSelector).is(':visible')) {
    customVersionAttachmentId = parseInt($(dummyFileSelector).attr('data-custom-version-for-attachment-id'));
  }

  var actualOptions = $.extend({
    loadstartEventHandler: $.noop,
    progressEventHandler: $.noop
  }, options);

  uploadUrl = uploadUrl + '?attachment_id=' + attachmentId;
  if (blob instanceof window.File) {
    uploadUrl += '&filename=' + encodeURIComponent(blob.name);
    if (tagName) {
       uploadUrl += '&tag_name=' + tagName;
    }
    if (customVersionAttachmentId) {
      uploadUrl += '&custom_version_for_attachment_id=' + customVersionAttachmentId;
    }
  }

  return $.ajax(uploadUrl, {
    type: 'POST',
    contentType: 'application/octet-stream',
    beforeSend: function(jqXhr, settings) {
      jqXhr.setRequestHeader('Accept', 'application/js');
      // attach proper File object
      settings.data = blob;
    },
    xhr: function() {
      var xhr = $.ajaxSettings.xhr();
      xhr.upload.onloadstart = actualOptions.loadstartEventHandler;
      xhr.upload.onprogress = actualOptions.progressEventHandler;
      return xhr;
    },
    data: blob,
    cache: false,
    processData: false
  });
}

function unbindSetupFileDrop() {
    $('form div.box').each(function() {
        $(this).off('dragover').off('dragleave').off('drop');
    });
};

$(document).ready(function() {
    unbindSetupFileDrop();
    setupFileDrop();
});
