/* global _ */
/*
* hf.fileUploads(fieldSelector)
* Arguments: A jQuery selector for the div wrapper of the squiz question which contains the file upload fields.
*
*/
var hydrantForm
((function(hf) {
hf.fileUploads = function(field) {
var base = this
base.$wrapper = $(field)
base.$attachButton = base.$wrapper.find('.saw-attach-file')
base.$fileList = base.$wrapper.find('ul.file-list')
base.$fileUploadFields = base.$wrapper.find('.form-upload-file-fields')
var VALID_EXTENSIONS = ['.jpg', '.jpeg', '.pdf', '.gif', '.doc', '.docx', '.png', '.tiff']
base.findUnsusedFileInput = function() {
var input = _.find(base.$wrapper.find('.form-upload-file-fields input:file'), function(inp) {
return $(inp).val() === ''
})
if (typeof input === 'undefined') {
return false
}
return input
}
base.humanFileSize = function(bytes, si) {
var thresh = si ? 1000 : 1024
if (Math.abs(bytes) < thresh) {
return bytes + ' B'
}
var units = si
? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
var u = -1
do {
bytes /= thresh
++u
} while (Math.abs(bytes) >= thresh && u < units.length - 1)
return bytes.toFixed(1) + ' ' + units[u]
}
base.validateExtension = function(input) {
var fileName = $(input).val()
return (new RegExp('(' + VALID_EXTENSIONS.join('|').replace(/\./g, '\\.') + ')$', 'i')).test(fileName)
}
base.validateSize = function(input) {
// console.log(["INPUTFILE",input.files[0]]);
if(input.files[0] !== null ) {
if(input.files[0] !== undefined ) {
return (input.files[0].size/1024/1024 < 10);
}else{
return true;
}
}else{
return true;
}
}
base.validateFiles = function(validate, virus) {
validate = 'boolean' === typeof validate ? validate : false;
var errors = {
file_size: true,
file_number: true,
file_extension: true,
virus:'string' === typeof virus ? virus : true,
}
// Check file extensions
_.each(base.$fileUploadFields.find('input:file'), function(input) {
if (!base.validateExtension(input) && $(input).val() !== '') {
errors.file_extension = 'The indicated file must be one of the allowed file formats. Please remove attachment and submit a valid file type.';
}
if (!base.validateSize(input) && $(input).val() !== '') {
errors.file_size = 'Each attachment must be less than 10MB in size. Please remove attachment indicated and attach file(s) of valid file size.';
}
})
// using external validation test
if (validate === true) {
return errors;
}
// Only allow as many files as there are file fields (generally 4)
if (base.findUnsusedFileInput() === false) {
base.$wrapper.find('.saw-attach-file').addClass('disabled').prop('disabled', true)
} else {
base.$wrapper.find('.saw-attach-file').removeClass('disabled').prop('disabled', false)
}
var validation = {}
validation[base.$wrapper.data('question')] = errors
hf.addValidationErrors(validation)
}
// bind Attach button to opening the file fields
base.$attachButton.on('click', function() {
var fileField = base.findUnsusedFileInput()
if (fileField === false) {
var a = {}
a[base.$wrapper.data('question')] = { file_number: 'Sorry, a maxiumum of four files are allowed.' }
hf.addValidationErrors(a)
}
$(fileField).trigger('click')
})
// Update file list when a file is attached
base.$fileUploadFields.find('input:file').on('change', function() {
if ($(this).val() !== '') {
var fieldDiv = document.createElement('li')
$(fieldDiv)
.data('file-id', $(this).attr('id'))
.html('' +
_.last($(this).val().split('\\')) +
' (' + base.humanFileSize(this.files[0].size, true) +
')Remove attachment
')
base.$fileList.append($(fieldDiv))
base.$wrapper.find('.no-photos').addClass('hide')
if ($(window).width < 640) { // hack for getting sizing right consistantly on ios etc
base.$fileList.css('width', parseInt($(window).width()) - 20)
}
}
base.validateFiles()
})
// remove the attachement from the file list when the remove button is clicked
base.$wrapper.on('click', 'a.saw-file-remove', function() {
var $li = $(this).parents('li')
base.$fileUploadFields.find('input:file#' + $li.data('file-id')).val('')
$li.remove()
base.$wrapper.find('.saw-attach-file').removeClass('disabled').prop('disabled', false)
if (base.$fileList.find('li').length === 0) {
base.$wrapper.find('.no-photos').removeClass('hide')
}
base.validateFiles()
})
base.$fileUploadFields.find('input:file').trigger('change')
}
})(hydrantForm || (hydrantForm = {})));
(function(hf){
// sourced from #318342
hf.addValidationErrors = function(validations) {
var allCorrect = true;
var allErrors = [];
_.each(validations, function(validation, field) { // run through all validations returned
var question = $('#' + field).parents('.sq-form-question:first'); // grab the question
var correct = _.every(validation, function(val) { return val === true }) // all validations passed?
allCorrect = correct && allCorrect
if (correct) { // if so, remove error class and all errors
$(question)
.removeAttr('aria-describedby')
.removeClass('error')
.find('span.error-message')
.remove()
} else { // if not add error class and update all errors
$(question)
.removeAttr('aria-describedby')
.addClass('error')
.find('span.error-message')
.remove()
// add message for every validation thats failed
_.each(_.filter(validation, function(val) { return val !== true }), function(message, type) {
var $label = $(question).find('label:first');
if($label.length > 0){
$label.after('' + message + '')
}else{
var $legend = $(question).find('legend:first');
$legend.after('' + message + '')
}
allErrors.push(message)
})
$(question)
.attr('aria-describedby', $(question).find('span.error-message').attr('id'))
}
})
return allCorrect;
}
})(hydrantForm || (hydrantForm = {}));
// setup file uploads (sourced from #318344)
$('.sq-form-question-file-upload').each(function(ind, el) { new hydrantForm.fileUploads(el) });