altinn-designsystem
Version:
Altinn Design system based on Pattern Lab.
1,447 lines (1,291 loc) • 55.9 kB
JavaScript
/* globals $, Foundation */
var listenForAttachmentChanges = function(formId, errorMessageCallback) {
var maxSizeInMb = 15;
var maxSizeInBytes = maxSizeInMb * 1024 * 1024;
var allowedExtensions = [
'bmp', 'jpg', 'jpeg', 'png', 'gif', 'txt', 'log', 'csv', 'doc', 'docx', 'xls', 'xlsx', 'ppt',
'pptx', 'pdf', 'odt', 'ods', 'odp', 'rtf', 'rar', 'zip', '7z', 'gdoc', 'gsheet', 'gslide', 'htm',
'html', 'eml', 'msg'
];
var fileInput = $(formId).find('.a-js-uploadAttachment').find('#newCertificateInput');
var attachmentErrorBox = $(formId).find('.a-js-upload-error');
var attachmentBox = $(formId).find('.a-js-attachment-box');
var attachmentNameText = $(attachmentBox).find('.a-js-attachment-name');
var deleteAttachmentButton = $(attachmentBox).find('.a-btn-delete');
var selectedFile = '';
attachmentErrorBox.hide();
attachmentBox.hide();
deleteAttachmentButton.click(function() {
fileInput.val(''); // reset content
attachmentBox.hide();
attachmentErrorBox.hide();
fileInput.parent().show();
});
$(fileInput).change(function(event) {
if (event.target.files.length > 0) {
selectedFile = event.target.files[0];
}
function handleFile(file) {
var fileName = file.name;
var extension = fileName.split('.').pop();
var byteSize = file.size;
var validExtension = $.inArray(extension, allowedExtensions) > -1;
var validFileSize = maxSizeInBytes > byteSize;
if (validExtension && validFileSize) {
// success:
// set file name and show 'attachment box'
// hide 'error box'
// hide upload button
attachmentNameText.text(fileName);
attachmentBox.show();
attachmentErrorBox.hide();
fileInput.parent().hide();
} else {
// failure:
// hide 'attachment box'
// show 'error box'
// show upload button
attachmentBox.hide();
attachmentErrorBox.show();
fileInput.parent().show();
}
if (!validFileSize) {
attachmentErrorBox.find('.a-message-error').text(errorMessageCallback('size') + ': ' + maxSizeInMb + 'MB');
} else if (!validExtension) {
attachmentErrorBox.find('.a-message-error').text(errorMessageCallback('ext') + ': ' + allowedExtensions.join(', '));
}
}
if (selectedFile) {
handleFile(selectedFile);
} else {
attachmentBox.hide();
}
});
};
/* globals $ */
function setupFormValidation(formId, buttonId) {
var $submitBtn = $(buttonId);
var wasSubmitted = false;
var storedString = '';
var validDropdown = function(el) {
if (
el.attr('required') !== undefined && el.attr('required') === 'required' &&
el.attr('data-dropdowndefaultvalue') === el.find('.a-form-text').text()
) {
el.closest('.a-form-group').addClass('has-error').find('.a-message-error').css('display', 'table');
} else {
el.closest('.a-form-group').removeClass('has-error').find('.a-message-error').css('display', 'none');
}
};
var validAllDropdowns = function() {
var invalids = [];
$('.a-js-dropdownToValidate').each(function(index, el) {
if (
$(el).attr('required') !== undefined && $(el).attr('required') === 'required' &&
$(el).attr('data-dropdowndefaultvalue') === $(el).find('.a-form-text').text()
) {
invalids.push(index);
}
});
return invalids.length === 0;
};
var validAllReferancials = function() {
var invalids = [];
$('.a-js-validateThisAgainstPrev').each(function(index, el) {
if (
$(el).closest('.a-form-group').hasClass('has-error')
) {
invalids.push(index);
}
});
return invalids.length === 0;
};
var validateBackwards = function(el) {
if (el.prev().find('.a-js-dropdownToValidate').length > 0) {
validDropdown(el.prev().find('.a-js-dropdownToValidate'));
validateBackwards(el.prev());
} else if (el.prev().hasClass('form-group')) {
if (el.prev().find('input:not(.a-js-validateThisAgainstPrev)').length > 0) {
el.prev().find('input:not(.a-js-validateThisAgainstPrev)').valid();
}
if (el.prev().find('.a-js-validateThisAgainstPrev').length > 0) {
el.prev().find('.a-js-validateThisAgainstPrev').trigger('change');
}
if (el.prev().find('textarea').length > 0) {
el.prev().find('textarea').valid();
}
validateBackwards(el.prev());
}
};
var validateAgainstPrev = function() {
if ($(this).closest('.form-group').prev().find('.a-message-error')
.text() !== '') {
$(this).closest('.form-group').find('.a-message-error').text(
$(this).closest('.form-group').prev().find('.a-message-error')
.text()
);
storedString = $(this).closest('.form-group').prev().find('.a-message-error')
.text();
} else {
$(this).closest('.form-group').find('.a-message-error').text(
storedString
);
}
if ($(this).val() !==
$(this).closest('.form-group').prev().find('input')
.val() || $(this).val() === '') {
setTimeout(function() {
$(this).closest('.a-form-group').addClass('has-error').find('.a-message-error')
.css('display', 'table');
}.bind(this), 0);
} else {
$(this).closest('.a-form-group').removeClass('has-error').find('.a-message-error')
.css('display', 'none');
}
};
var validateForm = function() {
var str;
if ($(formId).validate().checkForm() && validAllDropdowns() && validAllReferancials()) {
$submitBtn.prop('disabled', false);
$submitBtn.removeClass('disabled');
} else {
$submitBtn.prop('disabled', 'disabled');
$submitBtn.addClass('disabled');
}
if (!wasSubmitted) {
$(formId).validate().submitted = {};
}
};
$(formId + ' .a-js-dropdownToValidate').each(function() {
$(this).attr('data-dropdowndefaultvalue', $(this).find('.a-form-text').text());
});
if (!buttonId) {
$submitBtn = $(formId + ' button[type="submit"]');
}
$.validator.unobtrusive.parse($(formId));
$submitBtn.addClass('disabled');
$submitBtn.prop('disabled', 'disabled');
$(formId).on('blur input change', '*', validateForm);
$(formId + ' .a-js-dropdownToValidate').next().on('click', function() {
setTimeout(function() {
validDropdown($(this).prev());
}.bind(this), 0);
validateBackwards($(this).closest('.form-group'));
});
$(formId + ' .a-js-dropdownToValidate').on('blur', function() {
validDropdown($(this));
validateBackwards($(this).closest('.form-group'));
});
$('.a-js-certificateContainer').on('focus', function() {
$('.a-js-certificateContainer').closest('label').addClass('a-custom-fileupload--focused');
});
$('.a-js-certificateContainer').on('blur', function() {
$('.a-js-certificateContainer').closest('label').removeClass('a-custom-fileupload--focused');
});
$('.a-js-validateThisAgainstPrev').each(function() {
storedString = $(this).closest('.form-group').prev().find('input')
.attr('data-val-regex');
});
$(formId + ' .form-control').not('.a-js-validateThisAgainstPrev').on('blur change', function() {
var $nextInput = $('#text-input-epost1').closest('.form-group').next().find('.a-js-validateThisAgainstPrev');
if ($nextInput.length > 0 && $nextInput.val() !== '') {
validateAgainstPrev.bind($nextInput)();
setTimeout(function() {
validateForm();
}, 0);
}
});
$('.a-js-validateThisAgainstPrev').on('keyup', function(e) {
var hasError = $(this).closest('.form-group').hasClass('has-error');
e.stopPropagation();
if (hasError) {
validateAgainstPrev.bind(this)();
}
});
$('.a-js-validateThisAgainstPrev').on('change blur', function(e) {
e.stopPropagation();
validateAgainstPrev.bind(this)();
});
}
var addListExpandHandler = function() {
$('body').on('click', '.a-list *[data-toggle="collapse"]', function() {
// This script runs before the bootstrap collapse handler, so the collapsed-class will still be
// present even though the content is about to be expanded
if ($(this).hasClass('collapsed')) {
$(this).closest('li').addClass('a-expanded');
$(this).closest('li').siblings().removeClass('a-expanded');
} else {
$(this).closest('li').removeClass('a-expanded');
}
});
};
/* globals $ */
var feedbackToggle = function() {
if ($('.a-js-feedbackToggle').length > 0) {
$('.a-js-feedbackToggle').closest('fieldset').next().hide();
$('.a-js-feedbackToggle').closest('fieldset').next().next()
.hide();
$('.a-js-feedbackToggle').closest('fieldset').next().next()
.next()
.hide();
$('.a-js-feedbackToggle').each(function() {
$(this).find('input[type=radio]').change(function() {
if ($(this).val() === 'radio1' && $(this).is(':checked')) {
$(this).closest('fieldset').next().show();
$(this).closest('fieldset').next().next()
.hide();
$(this).closest('fieldset').next().next()
.next()
.hide();
} else if ($(this).val() === 'radio2' && $(this).is(':checked')) {
$(this).closest('fieldset').next().hide();
$(this).closest('fieldset').next().next()
.show();
$(this).closest('fieldset').next().next()
.next()
.show();
}
});
$(this).closest('form').find('button').on('click', function() {
$(this).closest('fieldset').next().show();
$(this).closest('fieldset').next().next()
.hide();
$(this).closest('fieldset').next().next()
.next()
.hide();
}.bind(this));
});
}
};
var setupSelectableCheckbox = function() {
$('body').on('change', '.a-js-selectable-checkbox', function() {
if ($(this).is(':checked')) {
$(this).closest('.a-selectable').addClass('a-selected');
} else {
$(this).closest('.a-selectable').removeClass('a-selected');
}
});
$('body').on('focus', '.a-js-selectable-checkbox', function() {
$(this).closest('.a-selectable').addClass('a-focus');
});
$('body').on('blur', '.a-js-selectable-checkbox', function() {
$(this).closest('.a-selectable').removeClass('a-focus');
});
};
/* eslint vars-on-top: 0 */
/* globals AltinnDropdown */
/* globals AltinnDropdown:true */
AltinnDropdown = {
init: function() {
var that = this;
$('body').on('click', '[data-toggle="altinn-dropdown"] .a-dropdown-item', function() {
var $dropdownElement = $(this).closest('[data-toggle="altinn-dropdown"]');
if ($(this).data('value')) {
$dropdownElement.find('.a-js-altinnDropdown-value').val($(this).data('value'));
}
$dropdownElement.find('.a-dropdown-toggle').html($(this).html());
// Focus the dropdownmenu element after click on item in dropdownmenu
var id = $(this).closest('.a-dropdown-menu').attr('aria-labelledby');
$('#' + id).focus();
});
}
};
/* globals $ */
var handleFocus = function() {
// If state on input is 'focus', add class to a-input: 'a-input-focus'
$('body').on('focus', 'input.form-control', function() {
$(this).parent().addClass('a-input-focus');
});
$('body').on('blur', 'input.form-control', function() {
$(this).parent().removeClass('a-input-focus');
});
$('.a-radioButtons-stackedList').find('input[type=radio]').change(function() {
var me = $(this);
if (me.is(':checked')) {
me.parent().addClass('a-js-radioParentGray');
$('input[type=radio]').each(function() {
if ($(this).attr('id') !== me.attr('id') &&
$(this).attr('name') === me.attr('name')) {
$(this).parent().removeClass('a-js-radioParentGray');
}
});
}
});
};
var setupTruncateLines = function() {
setTimeout(function() {
// Max two lines for all screen sizes
$('.a-js-truncate-2').truncate({
lines: 2
});
// Max two lines for screen sizes less than 768
// Intit with 3 lines instead of 2 for IE11
if (!!window.MSInputMethodContext
&& !!document.documentMode
&& window.innerWidth < 768) {
$('.a-js-truncate-2-sm-down').truncate({
lines: 3
});
} else {
$('.a-js-truncate-2-sm-down').truncate({
lines: 2
});
}
}, 1);
$(window).resize(function() {
// Max two lines for all screen sizes
$('.a-js-truncate-2').truncate('collapse');
$('.a-js-truncate-2').truncate('update');
// Max two lines for screen sizes less than 768
if (window.innerWidth < 768) {
$('.a-js-truncate-2-sm-down').truncate('collapse');
$('.a-js-truncate-2-sm-down').truncate('update');
} else {
$('.a-js-truncate-2-sm-down').truncate('expand');
}
});
$('.a-collapsePanel-body').on('shown.bs.collapse', function() {
var el = $(this).siblings('.a-collapsePanel-heading').find('.a-js-truncate-2-sm-down');
if (window.innerWidth < 768) {
el.truncate('expand');
}
});
$('.a-collapsePanel-body').on('hide.bs.collapse', function() {
var el = $(this).siblings('.a-collapsePanel-heading').find('.a-js-truncate-2-sm-down');
if (window.innerWidth < 768) {
el.truncate('collapse');
}
});
};
/* globals AltinnLoader:true */
AltinnLoader = {
addLoader: function($target) {
if ($target.find('.loader-container').length === 0) {
$target.prepend('<div class="loader-container"><div class="loader loader-ellipsis"></div></div>');
}
$('button.a-modal-back').attr('disabled', true);
$('button.a-modal-close').attr('disabled', true);
},
removeLoader: function($target) {
$target.find('.loader-container').remove();
$('button.a-modal-back').attr('disabled', false);
$('button.a-modal-close').attr('disabled', false);
}
};
function showPassword(src, target) {
var pwd = $('#' + target);
if (pwd.attr('type') === 'text') {
pwd.attr('type', 'password');
$(src).children('.hide-password-text').hide();
$(src).children('.show-password-text').show();
} else {
pwd.attr('type', 'text');
$(src).children('.hide-password-text').show();
$(src).children('.show-password-text').hide();
setTimeout(function() {
pwd.attr('type', 'password');
$(src).children('.hide-password-text').hide();
$(src).children('.show-password-text').show();
}, 15000);
}
}
function setVisibility(passwordField, showPasswordId) {
var password = $(passwordField);
if (password.val().length > 0) {
$('#' + showPasswordId).removeClass('d-none');
} else {
$('#' + showPasswordId).addClass('d-none');
}
}
/* globals currentRequest, popoverLocalInit, AltinnModal */
/* globals AltinnModal:true, AltinnLoader */
AltinnModal = {
closeModal: function(settings) {
$('body').removeClass('a-modal-background-error a-displayNav');
$('body').removeClass('a-modal-background-success');
$(settings.target).modal('hide');
$('body').append($('.a-stickyHelp-container'));
},
loadModal: function(settings) {
var currentRequest = $.ajax({
url: settings.url,
beforeSend: function() {
if (typeof currentRequest !== 'undefined') {
currentRequest.abort();
}
AltinnLoader.addLoader($('body'));
},
data: settings.data
}).always(function() {
}).done(function(data) {
var modalPage = $('<div/>', {
class: 'modalPage',
html: data
});
var page = $('<div/>', {
class: 'a-page a-current-page',
data: {
pageIndex: 1,
isSuccess: settings.isSuccess,
isError: settings.isError,
showModalNav: settings.showModalNav
},
html: modalPage
});
$('body').removeClass('a-modal-background-error a-displayNav');
$('body').removeClass('a-modal-background-success');
// if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
// goToModalHeader();
// }
$(settings.target + ' .a-modal-content-target').append(page);
$(settings.target).trigger('loaded.altinn.modal');
$(settings.target).find('.a-current-page').first().data().enableDirtyPopover = settings.enableDirtyPopover;
// Initialize with backdrop: static to prevent modal from closing when clicking outside,
// and keyboard: false to prevent ESC from closing the modal
$(settings.target).modal({
backdrop: 'static',
keyboard: false
});
$(settings.target).on('hidden.bs.modal', function() {
$(settings.target + ' .a-modal-content-target').empty();
$(settings.target).attr('aria-hidden', true);
$('#altinnModal').siblings('.row').removeClass('d-none');
});
$(settings.target).on('shown.bs.modal', function() {
$(settings.target).removeAttr('aria-hidden');
$('#altinnModal').siblings('.row').addClass('d-none');
});
popoverLocalInit();
if (settings.isError) {
$('body').addClass('a-modal-background-error');
if (settings.showModalNav) {
$('body').addClass('a-displayNav');
}
} else if (settings.isSuccess) {
$('body').addClass('a-modal-background-success');
}
AltinnLoader.removeLoader($('body'));
// causes issues in IE11 (blinking quickhelp when modal is open)
// $(settings.target).on('transitionend', function() {
// $(settings.target).append($('.a-stickyHelp-container'));
// });
});
},
nextModalPageWithContent: function(settings) {
var current;
var modalPage = $('<div/>', {
class: 'modalPage',
html: settings.content
});
var existingPages;
var newPage;
var newPageIndex;
existingPages = $(settings.target + ' :data(page-index)');
if (settings.clearHistory) {
newPageIndex = 1;
} else {
newPageIndex = existingPages.length + 1;
}
if (settings.clearHistory) {
$(settings.target + ' :data(page-index)').not('.a-current-page').remove();
}
newPage = $('<div/>', {
class: 'a-page a-next-page',
data: {
pageIndex: newPageIndex,
isSuccess: settings.isSuccess,
isError: settings.isError,
showModalNav: settings.showModalNav
},
html: modalPage
});
// if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
// goToModalHeader();
// }
$(settings.target + ' .a-modal-content-target').append(newPage);
$(settings.target).trigger('loaded.altinn.modal');
$(settings.target).animate({
scrollTop: 0
}, 20);
current = $(settings.target + ' .a-current-page');
setTimeout(function() {
$('body').removeClass('a-modal-background-error a-displayNav');
$('body').removeClass('a-modal-background-success');
current.removeClass('a-current-page').addClass('a-previous-page');
newPage.removeClass('a-next-page').addClass('a-current-page');
$(newPage).data().enableDirtyPopover = settings.enableDirtyPopover;
if (settings.isError) {
$('body').addClass('a-modal-background-error');
if (settings.showModalNav) {
$('body').addClass('a-displayNav');
}
} else if (settings.isSuccess) {
$('body').addClass('a-modal-background-success');
}
}, 0);
current.on('transitionend', function() {
if (settings.clearHistory) {
$(settings.target + ' :data(page-index)').not('.a-current-page').remove();
} else {
current.hide().off();
}
});
popoverLocalInit();
},
nextModalPage: function(settings) {
var currentRequest = $.ajax({
url: settings.url,
beforeSend: function() {
if (typeof currentRequest !== 'undefined') {
currentRequest.abort();
}
AltinnLoader.addLoader($(settings.target).find('.a-current-page .a-modal-body'));
},
data: settings.data
}).always(function() {
}).done(function(data) {
var current;
var modalPage = $('<div/>', {
class: 'modalPage',
html: data
});
var existingPages;
var newPage;
var newPageIndex;
existingPages = $(settings.target + ' :data(page-index)');
if (settings.clearHistory) {
newPageIndex = 1;
} else {
newPageIndex = existingPages.length + 1;
}
if (settings.clearHistory) {
$(settings.target + ' :data(page-index)').not('.a-current-page').remove();
}
newPage = $('<div/>', {
class: 'a-page a-next-page',
data: {
pageIndex: newPageIndex,
isSuccess: settings.isSuccess,
isError: settings.isError,
showModalNav: settings.showModalNav
},
html: modalPage
});
// if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
// goToModalHeader();
// }
$(settings.target + ' .a-modal-content-target').append(newPage);
$(settings.target).trigger('loaded.altinn.modal');
$(settings.target).animate({
scrollTop: 0
}, 20);
current = $(settings.target + ' .a-current-page');
setTimeout(function() {
$('body').removeClass('a-modal-background-error a-displayNav');
$('body').removeClass('a-modal-background-success');
current.removeClass('a-current-page').addClass('a-previous-page');
newPage.removeClass('a-next-page').addClass('a-current-page');
$(newPage).data().enableDirtyPopover = settings.enableDirtyPopover;
if (settings.isError) {
$('body').addClass('a-modal-background-error');
if (settings.showModalNav) {
$('body').addClass('a-displayNav');
}
} else if (settings.isSuccess) {
$('body').addClass('a-modal-background-success');
}
}, 0);
current.on('transitionend', function() {
if (settings.clearHistory) {
$(settings.target + ' :data(page-index)').not('.a-current-page').remove();
} else {
current.hide().off();
}
AltinnLoader.removeLoader(current.find('.a-modal-body'));
});
popoverLocalInit();
});
},
previousModalPage: function(settings) {
var current;
var allPages;
var previous;
var pagesToPop;
var isError;
var showModalNav;
var isSuccess;
if (!settings.pagesToPop) {
pagesToPop = 1;
} else {
pagesToPop = settings.pagesToPop;
}
if ($(settings.target + ' .a-current-page').data('page-index') - pagesToPop <= 0) {
$(settings.target).one('hidden.bs.modal', function() {
$('body').removeClass('a-modal-background-error a-displayNav');
$('body').removeClass('a-modal-background-success');
});
$(settings.target).modal('hide');
return;
}
current = $(settings.target + ' .a-current-page');
allPages = $(settings.target + ' :data(page-index)');
previous = allPages.filter(function() {
return $(this).data('page-index') === allPages.length - 1;
});
previous.show();
isError = $(previous).data().isError;
showModalNav = $(previous).data().showModalNav;
isSuccess = $(previous).data().isSuccess;
current.addClass('a-next-page');
current.removeClass('a-current-page');
// if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
// goToModalHeader();
// }
setTimeout(function() {
$('body').removeClass('a-modal-background-error a-displayNav');
$('body').removeClass('a-modal-background-success');
previous.addClass('a-current-page').removeClass('a-previous-page');
if (isError) {
$('body').addClass('a-modal-background-error');
if (showModalNav) {
$('body').addClass('a-displayNav');
}
} else if (isSuccess) {
$('body').addClass('a-modal-background-success');
}
}, 0);
current.on('transitionend', function() {
var previousPages = allPages.filter(function() {
return $(this).data('page-index') > allPages.length - pagesToPop;
});
previousPages.remove();
});
},
setCurrentPageIsDirty: function(target, state) {
$(target).find('.a-current-page').first().data().isDirty = state;
},
init: function() {
var that = this;
$('body').on('click', '[data-toggle="altinn-modal"]', function() {
var $source = $(this);
if ($source.data().action === 'load') {
that.loadModal({
url: $source.data().url,
target: $source.data().target,
enableDirtyPopover: $source.data().enableDirtyPopover
});
} else if ($source.data().action === 'next') {
that.nextModalPage({ url: $source.data().url,
target: $source.data().target,
isSuccess: $source.data().isSuccess,
isError: $source.data().isError,
showModalNav: $source.data().showModalNav,
clearHistory: $source.data().clearHistory,
enableDirtyPopover: $source.data().enableDirtyPopover });
} else if ($source.data().action === 'back') {
that.previousModalPage({
target: $source.data().target,
pagesToPop: $source.data().pages
});
} else if ($source.data().action === 'close') {
that.closeModal({ target: $source.data().target });
}
});
$('body').on('click', '.a-modal-back', function() {
var $modal = $(this).closest('.a-modal');
if ($modal.find('.a-current-page').first().data().enableDirtyPopover
&& $modal.find('.a-current-page').first().data().isDirty) {
$(this).popover('show');
} else {
that.previousModalPage({ target: '#' + $modal[0].id });
}
});
$('body').on('click', '.a-modal-close', function() {
var $modal = $(this).closest('.a-modal');
if ($modal.find('.a-current-page').first().data().enableDirtyPopover
&& $modal.find('.a-current-page').first().data().isDirty) {
$(this).popover('show');
} else {
that.closeModal({ target: '#' + $modal[0].id });
}
});
$('body').on('click', '.a-js-modal-dirtyBackBtn', function() {
AltinnModal.previousModalPage({ target: '#' + $(this).closest('.a-modal')[0].id });
$('button[aria-describedby=' + $(this).parent().parent().attr('id') + ']').popover('hide');
});
$('body').on('click', '.a-js-modal-dirtyCancelBtn', function() {
$('button[aria-describedby=' + $(this).parent().parent().attr('id') + ']').popover('hide');
});
$('body').on('click', '.a-js-modal-dirtyCloseBtn', function() {
AltinnModal.closeModal({ target: '#' + $(this).closest('.a-modal')[0].id });
$('button[aria-describedby=' + $(this).parent().parent().attr('id') + ']').popover('hide');
});
function urlQuery(query) { // Parse current URL for query value
var _query = query.replace(/[[]/, '[').replace(/[\]]/, '\\]');
var expr = '[\\?&]' + _query + '=([^&#]*)';
var regex = new RegExp(expr);
var results = regex.exec(window.location.href);
if (results !== null) {
return results[1];
}
return false;
}
if (urlQuery('form') === '1') {
AltinnModal.loadModal({
url: '/hjelp/kontaktskjema-for-hjelp/',
target: '#modal'
});
}
}
};
/* globals $ */
var toggleFilter = function() {
$('.a-collapse-title').on('keyup', function(e) {
var key = e.which;
if (key === 13) {
e.stopImmediatePropagation(); e.stopPropagation(); e.preventDefault();
$(e.target).trigger('mouseup');
} else if (key === 9) {
if ($($(e.target).attr('data-target')).hasClass('show')) {
$($(e.target).attr('data-target')).find('.a-switch').eq(0)
.trigger('focus');
}
}
});
};
/* globals currentRequest, AltinnQuickhelp */
/* globals AltinnQuickhelp:true */
AltinnQuickhelp = {
listeners: function(target) {
var that = this;
$('.a-stickyHelp-search').find('input').on('keyup', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13 && encodeURIComponent($(this)[0].value).length > 0) {
that.nextquickhelpPage({
url: $('#a-stickyHelp').attr('data-api') +
encodeURIComponent($(this)[0].value) + '/' + $('html').attr('lang'),
target: target
});
}
});
$('.a-stickyHelp-search').find('button').on('click', function(e) {
if (encodeURIComponent($('.a-js-stickyhelpSearch')[0].value).length > 0) {
that.nextquickhelpPage({
url: $('#a-stickyHelp').attr('data-api') +
encodeURIComponent($('.a-js-stickyhelpSearch')[0].value) + '/' +
$('html').attr('lang'),
target: target
});
}
});
},
nextquickhelpPage: function(settings) {
var currentRequest = $.ajax({
url: settings.url,
beforeSend: function() {
if (typeof currentRequest !== 'undefined') {
currentRequest.abort();
}
}
}).done(function(data) {
var quickhelpPage = $('<div/>', { class: 'quickhelpPage', html: data });
var current; var existingPages; var newPage; var newPageIndex;
existingPages = $(settings.target + ' :data(page-index)');
newPageIndex = existingPages.length + 1;
newPage = $('<div/>', {
class: 'a-page a-next-page',
data: { 'page-index': newPageIndex },
html: quickhelpPage
});
$(settings.target + ' .a-stickyHelp-content-target').append(newPage);
$(settings.target).animate({ scrollTop: 0 }, 20);
current = $(settings.target + ' .a-current-page');
setTimeout(function() {
current.removeClass('a-current-page').addClass('a-previous-page');
newPage.removeClass('a-next-page').addClass('a-current-page');
$(newPage).data();
}, 0);
current.on('transitionend', function() {
if (settings.clearHistory) {
$(settings.target + ' :data(page-index)').not('.a-current-page')
.remove();
} else {
current.off();
}
});
$('#a-js-stickyHelp-back').addClass('d-block');
});
},
previousquickhelpPage: function(settings) {
var current; var allPages; var previous; var pagesToPop;
if (!settings.pagesToPop) {
pagesToPop = 1;
} else {
pagesToPop = settings.pagesToPop;
}
current = $(settings.target + ' .a-current-page');
allPages = $(settings.target + ' :data(page-index)');
previous = allPages.filter(function() {
return $(this).data('page-index') === allPages.length - 1;
});
previous.addClass('a-current-page').removeClass('a-next-page');
current.removeClass('a-current-page').addClass('a-next-page');
setTimeout(function() {
previous.addClass('a-current-page').removeClass('a-previous-page');
}, 0);
current.on('transitionend', function() {
var previousPages = allPages.filter(function() {
return $(this).data('page-index') > allPages.length - pagesToPop;
});
previousPages.remove();
});
if (allPages.length === 2) {
$('#a-js-stickyHelp-back').removeClass('d-block');
}
},
init: function() {
var that = this; that.listeners('#a-stickyHelp');
$('body').on('click', '[data-toggle="quickhelp"]', function() {
var $source = $(this);
if ($source.data().action === 'next') {
that.nextquickhelpPage({
url: $source.data().url, target: $source.data().target
});
} else if ($source.data().action === 'back') {
that.previousquickhelpPage({
target: $source.data().target, pagesToPop: $source.data().pages
});
}
});
$('.a-current-page').data({ 'page-index': 1 });
$('.a-js-stickyHelpCategory')
.html($('#a-stickyHelp').find('.a-stickyHelp-content-target')
.attr('data-category')
);
$('.a-js-stickyHelpCategoryLink').attr('data-url', $('#a-stickyHelp')
.find('.a-stickyHelp-content-target').attr('data-url')
);
$('body').on('click', '.a-stickyHelp-open', function() {
if (!$('.a-js-stickyHelpFrame').attr('src')) {
$('.a-js-stickyHelpFrame')
.attr('src', $('.a-js-stickyHelpFrame').attr('data-src'));
}
});
if ($('.quickhelpPage').find('.a-text').length !== 0) {
$('.quickhelpPage').parent('.a-page').addClass('a-page-hasArticleInside');
}
}
};
/* globals mobileNavigation */
var wasDark = $('header').hasClass('a-darkBackground');
var action = function(e) {
if ($(e.target).closest('.a-globalNav-main').length === 0 &&
$(e.target).closest('.navbar-toggler').length === 0) {
if ($('.a-globalNav-main').is(':visible')) {
$('.navbar-toggler').attr('data-jsexpanded', 'false');
$('.a-globalNav-main').hide();
$('body').css('background-color', '');
if (wasDark) {
$('header').addClass('a-darkBackground');
$('.a-globalNav-logo').find('img')
.attr('src', $('.a-globalNav-logo').find('img').attr('src').replace('blue', 'white'));
}
$('.a-page').children(':not(header)').removeClass('a-js-hidden');
}
} else if ($(e.target).closest('.navbar-toggler').length > 0) {
if ($('.a-globalNav-main').is(':visible')) {
$('.navbar-toggler').attr('data-jsexpanded', 'false');
$('.a-globalNav-main').hide();
$('body').css('background-color', '');
if (wasDark) {
$('header').addClass('a-darkBackground');
$('.a-globalNav-logo').find('img')
.attr('src', $('.a-globalNav-logo').find('img').attr('src').replace('blue', 'white'));
}
$('.a-page').children(':not(header)').removeClass('a-js-hidden');
} else {
$('.navbar-toggler').attr('data-jsexpanded', 'true');
$('.a-globalNav-main').show();
$('body').css('background-color', '#fff');
if (wasDark) {
$('header').removeClass('a-darkBackground');
$('.a-globalNav-logo').find('img')
.attr('src', $('.a-globalNav-logo').find('img').attr('src').replace('white', 'blue'));
}
$('.a-page').children(':not(header)').addClass('a-js-hidden');
}
}
};
function menuHandler() {
// enable tabbing and mouse click on mobile menu btn
if ($('body').width() < 768) {
$('body').on('click', action);
}
}
menuHandler();
$(window).on('resize', function() {
$('body').off('click', action);
menuHandler();
});
var toggleInstant = function() {
$('.a-panelAccordion').on('click', '*[data-toggle="instant"]', function() {
var $target = $(this.dataset.target);
if ($target.is(':visible')) {
$(this).attr('aria-expanded', false);
$target.hide();
$(this).removeClass('a-open');
} else {
$(this).attr('aria-expanded', true);
$target.show();
$(this).addClass('a-open');
}
});
};
/* globals $ */
var mobileNavigation = function() {
$('.a-globalNav .dropdown').on('show.bs.dropdown', function(e) {
var that = this;
setTimeout(function() {
$(that).find('.a-dropdown-languages').addClass('expand');
$(that).find('.a-dropdown-languages a').removeAttr('tabindex');
$(that).find('.a-dropdown-languages a').removeAttr('aria-hidden');
}, 0);
});
$('.a-globalNav .dropdown').on('hide.bs.dropdown', function(e) {
$(this).find('.a-dropdown-languages').removeClass('expand');
$(this).find('.a-dropdown-languages a').attr('tabindex', '-1');
$(this).find('.a-dropdown-languages a').attr('aria-hidden', 'true');
});
};
/* globals
setupExpandContent
*/
$('body').on('show.bs.collapse', '.a-collapsePanel-body', function(e) {
var that = this;
if ($(e.target).hasClass('a-collapsePanel-body')) {
setTimeout(function() {
var $collapsePanelHeader = $(that).siblings('.a-js-index-heading').first();
var $msgIconWrapper = $collapsePanelHeader.find('.a-inboxHeadingContent')
.find('.a-msgIconSecondary')
.closest('.a-msgIconWrapper');
$msgIconWrapper.find('.reg')
.hide()
.siblings('.a-msgIconSecondary')
.show();
$msgIconWrapper.find('span').attr('aria-hidden', true);
$msgIconWrapper.find('span:last-of-type').removeAttr('aria-hidden');
$('.a-collapsePanel').removeClass('expanded');
$(that).closest('.a-collapsePanel').addClass('expanded');
$('.a-js-index-heading').addClass('dim');
$('.a-collapsePanel.expanded').find('.a-js-index-heading').removeClass('dim');
setupExpandContent();
}, 0);
}
});
$('body').on('hide.bs.collapse', '.a-collapsePanel-body', function(e) {
var that = this;
if ($(e.target).hasClass('a-collapsePanel-body')) {
setTimeout(function() {
var $collapsePanelHeader = $(that).siblings('.a-js-index-heading').first();
$collapsePanelHeader.find('.a-inboxHeadingContent').removeClass('a-msgUnread');
$(that).closest('.a-collapsePanel').removeClass('expanded');
if ($('.a-collapsePanel.expanded').length === 0) {
$('.a-js-index-heading').removeClass('dim');
} else {
$collapsePanelHeader.addClass('dim');
}
}, 0);
}
});
$('.a-js-collapseInboxMessage').click(function() {
$('div.card.a-accordion-card.a-collapsePanel.expanded a[data-toggle="collapse"]').click();
});
var setupOnKeypress = function() {
$('body').on('keydown', '.a-clickable, .a-selectable', function(e) {
var key = e.which;
if ($(e.target).hasClass('a-clickable') || $(e.target).hasClass('a-selectable')) {
if (key === 13) {
$(this).click();
return false;
}
}
return true;
});
};
var compareTo = function(firstItem, secondItem) {
var first;
var second;
if (firstItem === undefined && secondItem === undefined) {
return 0;
}
if (firstItem === undefined) {
return 1;
}
if (secondItem === undefined) {
return -1;
}
first = firstItem.toString();
second = secondItem.toString();
if (first < second) {
return -1;
}
if (first > second) {
return 1;
}
return 0;
};
// Select the node that will be observed for mutations
var targetNode = document.getElementsByClassName('navbar-toggler')[0];
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };
var callback = function(mutationsList) {
mutationsList.forEach(function(mutation) {
if ($(mutation.target).attr('data-jsexpanded') === 'false') {
$('.a-login-container').css('display', '');
} else {
$('.a-login-container').css('display', 'none');
}
});
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
try {
observer.observe(targetNode, config);
} catch (e) {
//
}
$('button.a-personSwitcher').on('click', function() {
if ($('button.navbar-toggler').attr('data-jsexpanded') === 'true') {
event.preventDefault();
event.stopPropagation();
$('button.navbar-toggler').trigger('click');
}
});
$('.a-dropdown-personswitchList').on('click', 'button[data-toggle="collapse"]', function(event) {
event.preventDefault();
event.stopPropagation();
$($(this).data('target')).collapse('toggle');
});
// For setting the background-color when favorite star is hovered
$('.a-listWithSubLevels').children().hover(function() {
if (!$(this).parent().find('button.a-btn-shadow-large').is(':disabled') && ($(this).is('.a-favourite') || $(this).is('.a-btn-shadow-large'))) {
$(this).parent().find('button.a-btn-shadow-large').css('background', '#CFF0FF');
$(this).parent().find('button.a-btn-shadow-large.a-bgGreyLight').css('background', '#E2E2E2');
}
},
function() {
if (!$(this).parent().find('button.a-btn-shadow-large').is(':disabled') && ($(this).is('.a-favourite') || $(this).is('.a-btn-shadow-large'))) {
$(this).parent().find('button.a-btn-shadow-large').css('background', '#E3F7FF');
$(this).parent().find('button.a-btn-shadow-large.a-bgGreyLight').css('background', '#EFEFEF');
}
});
var setValidatorSettings = function() {
var defaultOptions = {
ignore: ':hidden, .ignoreValidation',
highlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').addClass(errorClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').removeClass(errorClass);
},
focusInvalid: false
};
$.validator.setDefaults(defaultOptions);
$.validator.unobtrusive.options = {
errorClass: 'has-error'
};
};
/* eslint vars-on-top: 0 */
/* globals $ */
var popoverLocalInit = function() {
var options = {
html: true,
sanitize: false,
placement: function(context, source) {
var position = $(source).offset();
$(context).addClass($(source).attr('data-popover-class'));
if ($(source).hasClass('a-js-popoverBig')) {
return 'bottom';
}
if (position.left < 125) {
return 'right';
}
if (position.left > ($(document).width() - $(source).width() - 125)) {
return 'left';
}
return 'bottom';
},
content: function() {
if ($(this).attr('data-popover-content')) {
return $('#' + $(this).data('popover-content')).html();
}
return false;
},
template: '<div class="popover" role="popover" tabindex="0"><div class="arrow"></div><div class="popover-body"></div></div>'
};
$('[data-toggle="popover"]').popover(options);
$('.a-js-togglePopoverIcons').each(function() {
// $(this).find('i').eq(1).hide();
$(this).find('.a-js-popoverIconExpanded').hide();
});
$('.a-js-popoverIconExpanded').on('click', function() {
$('.a-js-popoverIconExpanded').hide();
$('.a-js-popoverIconInitial').show();
// $(this).hide();
// $('.a-js-popoverIconInitial').show();
});
$('.a-js-popoverIconInitial').on('click', function() {
$(this).hide();
$(this).parent().find('.a-js-popoverIconExpanded').show();
});
};
var forceFocusTriggerElement;
var popoverGlobalInit = function() {
$('[data-toggle="dropdown"]').on('click', function(e) {
if (window.innerWidth < 992) {
$('.a-dropdown-overflow-menu-right').removeClass('dropdown-menu-right');
} else {
$('.a-dropdown-overflow-menu-right').addClass('dropdown-menu-right');
}
});
$('body').on('show.bs.popover', '[data-toggle="popover"].a-js-tabable-popover', function(e) {
var triggerElement = this;
$(triggerElement).closest('.a-modal').scrollTop(0);
});
$('body').on('shown.bs.popover', '[data-toggle="popover"].a-js-tabable-popover', function(e) {
var triggerElement = this;
setTimeout(function() {
$(triggerElement).after($($(triggerElement).data('bs.popover').tip));
$(triggerElement).closest('.a-modal').one('scroll', function() {
$('[data-toggle="popover"]').popover('hide');
});
}, 0);
});
$('body').on('shown.bs.popover', '[data-toggle="popover"].a-js-popover-forceFocus', function(e) {
$('body').append($('<button class="sr-only a-js-popoverTrick">ignoreme</button>'));
forceFocusTriggerElement = this;
/*
This is a keyboard trap code
which prevents the user from exiting the "popover" dialog with tabbing.
ESC will close the "popover" dialog.
*/
// Find popover-warning
var popoverWarning = $('.popover-warning');
// Find all focusable children
var focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]';
// var focusableElements = popover.querySelectorAll(focusableElementsString);
var focusableElements = $(popoverWarning).find(focusableElementsString);
// If there are focusable elements, make keyboardtrap
if (focusableElements.length) {
// Convert NodeList to Array
focusableElements = Array.prototype.slice.call(focusableElements);
var firstTabStop = focusableElements[0];
var lastTabStop = focusableElements[focusableElements.length - 1];
// Focus first child, and scroll to current position
var position = $(window).scrollTop();
firstTabStop.focus({ preventScroll: true });
$(window).scrollTop(position);
$(popoverWarning).keydown(function(key) {
if (key.keyCode === 9) {
// Shift + Tab
if (key.shiftKey) {
if (document.activeElement === firstTabStop) {
key.preventDefault();
lastTabStop.focus();
}
// TAB
} else {
if (document.activeElement === lastTabStop) { // eslint-disable-line
key.preventDefault();
firstTabStop.focus();
}
}
} else if (key.keyCode === 27) {
// Escape
$('[data-toggle="popover"]').popover('hide');
$(forceFocusTriggerElement).focus();
}
});
// if cancel/avbryt pressed with Enter, hide popover and focus on trigger
$(lastTabStop).keydown(function(key) {
if (key.keyCode === 13) {
// Enter
key.preventDefault();
$('[data-toggle="popover"]').popover('hide');
$(forceFocusTriggerElement).focus();
}
});
}
});
$('body').on('hidden.bs.popover', '[data-toggle="popover"].a-js-popover-forceFocus', function(e) {
$('body').find('.a-js-popoverTrick').remove();
});
// hides popover when the checkbutton is checked
$('body').on('focus', '[data-toggle="popover"].sr-only', function(e) {
if ($(this).is(':checked')) {
$(this).popover('hide');
} else {
$(this).popover('show');
}
});
// show/hide popover on checkbutton change
$('body').on('change', 'a-switch[data-toggle=popover]', function() {
if ($(this).is(':checked')) {
$(this).popover('hide');
} else {
$(this).popover('show');
}
});
// Hide all existing popovers when opening a new popover
$('body').on('click', '[data-toggle="popover"]', function(e) {
$('[data-toggle="popover"]').not(this).popover('hide');
});
// Hide all existing popovers when focusing a new element
// which is not the open popover or any of its content
$('body').on('blur', '[data-toggle="popover"], .popover *', function(e) {
setTimeout(function() {
var $focused = $(':focus');
if ((($focused.length !== 0 || forceFocusTriggerElement)
&& !$focused.hasClass('popover')
&& !$focused.parents('.popover').length >= 1) || $focused.hasClass('a-js-popoverTrick')) {
// disable blur when in modal to allow use of non-original scrollbar
if ($('.modal.show').length > 0) {
$('.popover-big[data-toggle="popover"]').popover('hide');
}
}
}, 0);
});
// Hide popovers when clicking on something else than the trigger element
// and the popover itself
$('body').on('click', function(e) {
if ($(e.target).data('toggle') !== 'popover' && $(e.target).parents('[data-toggle="popover"]').length === 0 && $(e.target).parents('.popover.show').length === 0) {
$('[data-toggle="popover"]').popover('hide');
forceFocusTriggerElement = false;
$(this).parent().find('.a-js-popoverIconInitial').show();
$(this).parent().find('.a-js-popoverIconExpanded').hide();
}
});
function resetTranslate() {
$('.popover-big').attr('style', $('.popover-big').attr('style').replace(/translateX\(.*?\)/, 'translateX(0px)'));
}
function adjustBig() {
var modalHeight;
var padding;
if ($('.popover-big').length > 0) {
if ($('.modal.show').length > 0) {
// Add padding to make sure modal is big enough to contain popover
modalHeight = $('.modal-dialog').height() + $('.modalPage:visible').height();
padding = ($('.popover').offset().top + $('.modal').scrollTop() + $('.popover').height() + 5) - modalHeight;
$('.modalPage:visible').css('padding-bottom', padding + 'px');
// tranlate is somehow added by Bootstrap later when in modal??
setTimeout(resetTranslate, 0);
} else {
resetTranslate();
}
}
}
$('body').on('shown.bs.popover', '.a-js-persistPopover', function() {
$('.arrow').html('<style>.popover-big:after { left: ' + ($(this).offset().left + 10.5) + 'px !important; }</style>');
$('html, body').animate({
scrollTop: $('.a-js-persistPopover').of