var INPUT_ATTACHMENT_CLASS = '.m-input-attachment';
var FILE_ERROR_CLASS = '.m-file-error';
var ADDITIONAL_LINK_CLASS = '.m-add-additional-link';
var REMOVE_BUTTON_CLASS = '.m-remove-button';
var LABEL_ELEMENT = 'label';
var SPAN_ELEMENT = 'span';
var CHANGE_EVENT = 'change';
var CLICK_EVENT = 'click';
var DATA_MULTIPLE_CAPTION_ATTRIBUTE = 'data-multiple-caption';
var VISIBLE_VALUE = ':visible';
var HAS_FOCUS_CLASS = 'has-focus';
var FOCUS = 'focus';
var BLUR = 'blur';
var DELIMITER = '\\';
var COUNT = '{count}';
var BLANK_STRING = '';
var SALESFORCE_FILE_SIZE_LIMIT = 25000000;

/**
 * @description Called when the document is ready.
 */
$(document).ready(function() {
   bindFileAttachmentElements();
});

/**
 * @description Binds the .input-attachment change event and sets the text
 *              on the label associated with the input to the name of the file being uploaded.
 *              Additionally shows an error if the file size surpasses 25MB.
 */
function bindFileAttachmentElements() {
	$(INPUT_ATTACHMENT_CLASS).each(function() {
		var input = $(this),
			label = input.next(LABEL_ELEMENT),
			errorLabel = input.nextAll(FILE_ERROR_CLASS).first(),
			removeButton = input.parent().next().find(REMOVE_BUTTON_CLASS);
			labelVal = label.html();
			
		input.on(CHANGE_EVENT, function(e) {
			var fileName = BLANK_STRING;

			if (this.files && this.files.length > 1) {
				fileName = (this.getAttribute(DATA_MULTIPLE_CAPTION_ATTRIBUTE) || BLANK_STRING).replace(COUNT, this.files.length);
			} else if(e.target.value) {
				fileName = e.target.value.split(DELIMITER).pop();
			}

			if (fileName) {
				label.find(SPAN_ELEMENT).html(fileName);
			} else {
				label.html(labelVal);
			}
			
			// Show the Remove button
			removeButton.show();
				
			// Check if the file size is over the limit
			if (this.files[0].size > SALESFORCE_FILE_SIZE_LIMIT) {
				errorLabel.show();
			} else {
				errorLabel.hide();
			}

			// Hide the Add Additional button as soon as the user starts uploading
			disableAddAdditionalLink();
		});
		
		removeButton.on(CLICK_EVENT, function(event) {
			event.preventDefault();
			$(this).parent().parent().remove();
		});

		// Firefox bug fix
		input
		.on(FOCUS, function(){ input.addClass(HAS_FOCUS_CLASS); })
		.on(BLUR, function(){ input.removeClass(HAS_FOCUS_CLASS); });
	});
}

/**
 * @description Hides the Add Additional Files button.
 */
function disableAddAdditionalLink() {
    $(ADDITIONAL_LINK_CLASS).hide();
}