function addRequiredFieldValidator(elementId){ try{ var a = document.createElement('span'); a.style.display = "none"; a.id = "RequiredFieldValidator" + elementId; a.display = "Dynamic"; a.controltovalidate = elementId; a.evaluationfunction = RequiredFieldValidatorEvaluateIsValid; a.initialvalue = ""; // Find out the label text of the field var labelText = ""; var labelElement = $(`label[for="${elementId}"]`); if (labelElement && labelElement.length) { labelText = labelElement.text() } else { labelText = "Okänt fält (systemet lyckades inte hitta det)"; } a.errormessage = `${labelText} är ett obligatoriskt fält.`; a.dispose = () => { Array.remove(Page_Validators, document.getElementById("RequiredFieldValidator" + elementId)); }; a.isvalid = true; Page_Validators.push(a); }catch(error){ console.log(error); } } /* Accessibility function for reading out messages to screen readers */ function screenReaderMessage(message) { console.log('Screen reader message:', message); const speaker = document.getElementById("a11y-speaker"); speaker.innerHTML = message; // Reset speaker setTimeout(() => { speaker.innerHTML = "" }, 500); } function updateLaguageModal(languageModal) { const langHeading = 'Sök och välj språk'; const langDescription = 'Välj språk i listan.'; const searchButtonText = 'Sök språk'; // Heading languageModal.querySelectorAll('h1.modal-title').forEach( (title) => { title.innerHTML = langHeading; title.ariaLabel = langHeading; title.title = langHeading; }); // Description languageModal.querySelectorAll('.view-grid > span').forEach( (span) => { let p = document.createElement('p'); let text = document.createTextNode(langDescription); p.appendChild(text); span.replaceWith(p); }); // Close button } document.addEventListener('DOMContentLoaded', function() { if(window.MTM?.libraryName){ const libraryElements = document.getElementsByClassName('js-mtm-library'); for (let i = 0; i < libraryElements.length; i++) { libraryElements[i].innerHTML = window.MTM.libraryName; } } }); function hideISBNInput(hide){ if(hide){ $("#ne_isbninput").val(""); $("#ne_isbninput").parent().parent().hide(); $("#ISBNInfoTitle").html(""); $("#ISBNInfoAuthor").html(""); }else{ $("#ne_isbninput").parent().parent().show(); } $("#NextButton").prop("disabled", !hide); } function isbnSearchProcess(){ let isbnInput = $("#ne_isbninput").val().replace(/-|\s+/g, ""); if (isValidISBN(isbnInput)) { $("#ne_isbninput").prop("readonly", true); $("#ISBNInfoDisplayField").slideDown(300, function () { $("#ISBNInfoDisplayField").show(); }); getISBN(isbnInput); $("#ne_isbninput").prop("readonly", false); } else { $("#ISBNInfoDisplayField").show(); $("#ISBNInfoDisplayField").addClass("APICallError"); $("#ISBNInfoDisplayField").html("
ISBN är felaktig angivet.
"); $("#ne_isbninput_btn").prop('disabled', false); } } function isValidISBN(isbn) { // Check for ISBN-10 if (/^\d{9}[\dX]$/.test(isbn)) { let sum = 0; for (let i = 0; i < 9; i++) { sum += (i + 1) * parseInt(isbn[i]); } sum += isbn[9] === "X" ? 10 : parseInt(isbn[9]); return sum % 11 === 0; } // Check for ISBN-13 if (/^\d{13}$/.test(isbn)) { let sum = 0; for (let i = 0; i < 12; i++) { sum += (i % 2 === 0 ? 1 : 3) * parseInt(isbn[i]); } let checkDigit = (10 - (sum % 10)) % 10; return checkDigit === parseInt(isbn[12]); } return false; } function validatePersonalId(id) { // sätta regexp och testa angivet pnr mot det. const regexpPattern = /\b(19|20)(\d{6})(\d{3})(\d{1})\b/g; //Dela upp pnr i ett object för att köra de olika kontrollerna. const array = [...id.matchAll(regexpPattern)]; let pnr = Object(); if (array.length){ pnr.century = array[0][1]; pnr.birthdate = array[0][2]; pnr.year = pnr.birthdate.split(/(\d{2})(\d{2})(\d{2})/g).filter(Boolean)[0] pnr.month = pnr.birthdate.split(/(\d{2})(\d{2})(\d{2})/g).filter(Boolean)[1] pnr.day = pnr.birthdate.split(/(\d{2})(\d{2})(\d{2})/g).filter(Boolean)[2] pnr.lastFour = array[0][3] + array[0][4]; pnr.birthNumber = array[0][3]; pnr.checksum = array[0][4]; pnr.raw = id; if (validateChecksum(pnr)) { return pnr; } else { return false //{errorMessage: 'Personnumret är felaktigt angivet.'}; } }else{ return false; } /* //om century inte är angivet, lägg till 19 eller 20 beroende på födelsedata. if (!pnr.century) { let birthYear = pnr.birthdate.split(/(\d{2})(\d{2})(\d{2})/g).filter(Boolean)[0]; let thisYear = new Date().getUTCFullYear().toString().split(/(\d{2})(\d{2})/g).filter(Boolean)[1]; pnr.century = birthYear > thisYear ? '19' : '20'; } */ //Kolla att födelsedatum är ett faktiskt datum. Används inte för tillfället då det skulle strula med samordningsnr. function isActualDate(pnr) { let ISODate = pnr.century + [pnr.year, pnr.month, pnr.day].join('-') date = new Date(ISODate); return !isNaN(date) && date.toISOString().substring(0, 10) === ISODate; } // Implementera Luhn-algoritmen function validateChecksum(pnr) { let ssn = pnr.birthdate + pnr.lastFour; var sum = ssn.split("").reverse() // convert to number .map(function (n) { return Number(n); }) // perform arithmetic and return sum .reduce(function (previous, current, index) { // multiply every other number with two if (index % 2) current *= 2; // if larger than 10 get sum of individual digits (also n-9) if (current > 9) current -= 9; // sum it up return previous + current; }); // sum must be divisible by 10 return 0 === sum % 10; } if (validateChecksum(pnr)) { return pnr; } else { return false //{errorMessage: 'Personnumret är felaktigt angivet.'}; } } function validateAlternateID(id){ const LMAKort = /^\d{2}-\d{6}/g; const MTMId = /^(19|20)\d{6}-MTM[1-8]/g; const Massflyktsdirektivet = /^(19|20)\d{6}-\d{3}U/g; if (LMAKort.test(id) || MTMId.test(id) || Massflyktsdirektivet.test(id)){ return true; } return false; } function clearContactInputField(){ $("#ne_contact_entityname").val(""); $("#ne_contact_name").val(""); $("#ne_contact").val(""); $("#ne_pnrinput").val(""); $("#ContactInfoDisplayField").hide(); } function setInputFieldsReadOnly(){ $("#ne_isbninput").prop("readonly", true); $("#mtm_title").prop("readonly", true); $("#mtm_author").prop("readonly", true); $("#ne_utgivningsar").prop("readonly", true); $("#mtm_edition").prop("readonly", true); $("#mtm_classificationcode").prop("readonly", true); $("#mtm_totalpages").prop("readonly", true); $(".launchentitylookup").hide(); } function clearISBNFormInputField(){ $("#ISBNInfoTitle").html(""); $("#ISBNInfoAuthor").html(""); $("#ne_isbn_name").val(""); $("#ne_isbn_entityname").val(""); $("#ne_isbn").val(""); $("#NextButton").prop("disabled", true); } function personalIdSearchProcess(){ $("#ne_pnrinput_btn").prop('disabled', true); var input = $("#ne_pnrinput").val(); pnr = validatePersonalId(input); if (pnr){ $("#ContactInfoDisplayField").slideDown(300, function(){ $("#ContactInfoDisplayField").show(); getContact(pnr.century+pnr.birthdate+pnr.lastFour); }); }else if (validateAlternateID(input)){ $("#ContactInfoDisplayField").slideDown(300, function(){ $("#ContactInfoDisplayField").show(); //getContact(input); getContactByAlternateId(input); }); } else{ $("#ContactInfoDisplayField").show(); $("#ContactInfoDisplayField").addClass("APICallError"); $("#ContactInfoDisplayField").html("Personnumret är felaktigt angivet.
"); screenReaderMessage('Personnumret är felaktigt angivet.'); } $("#ne_pnrinput_btn").prop('disabled', false); } async function createFilialPicker() { var mainLibraryName = $("#ne_filial_name").val(); var mainLibraryId = $("#ne_filial").val(); var libraryNameList = []; var libraryIdList = []; var jsonObject; try { jsonObject = await fetchLibraries(); } catch (error) { console.error("Error in fetching libraries:", error); return; } var results = jsonObject.results; libraryNameList.push(mainLibraryName); libraryIdList.push(mainLibraryId); results.forEach(function(item) { if (item.name !== mainLibraryName) { libraryNameList.push(item.name); libraryIdList.push(item.accountid); } }); createLibraryDropDown(libraryNameList, libraryIdList); } async function fetchLibraries() { var newUrl = "/fetch-libraries"; // Ensure the correct relative URL return new Promise((resolve, reject) => { $.ajax({ type: "GET", url: newUrl, dataType: 'json' // jQuery will handle the JSON parsing }).done(function(res) { if (res.results && res.results.length) { resolve(res); } else { reject("No results found"); } }).fail(function(jqXHR, textStatus, errorThrown) { console.error("Error fetching libraries:", textStatus, errorThrown); reject(errorThrown); }); }); } function createLibraryDropDown(libraryNameList, libraryIdList){ if(libraryNameList.length > 1){ $("").appendTo($("#ne_filial_label").closest(".cell")); var dropDown = $("").appendTo($("#libraryDiv")); for(var i = 0; i < libraryNameList.length; i++){ var option = $("").text(libraryNameList[i]).val(i); dropDown.append(option); } $("#libraryDropDownList").on('change', function() { var selectedIndex = $(this).val(); var libraryCode = libraryIdList[selectedIndex]; $("#ne_filial").val(libraryCode); $("#ne_filial_name").val(libraryNameList[selectedIndex]); }); $("#ne_filial_name").hide(); } } async function getISBN(ISBNNo){ validISBN = false; if(step == 1){ if ($("#ISBNInfoDisplayField").hasClass("APICallError")) { $("#ISBNInfoDisplayField").removeClass("APICallError") } if ($("#ISBNInfoDisplayField").hasClass("APICallSuccess")) { $("#ISBNInfoDisplayField").removeClass("APICallSuccess") $(".isbn").slideUp(400, function() { $(".isbn").hide(); }); } $("#ISBNInfoDisplayField").html("Söker efter boken, vänligen vänta
"); screenReaderMessage('Söker efter boken, vänligen vänta'); } try{ var flowUrl = MTM.getISBNFlow; var input = JSON.stringify({ isbn: ISBNNo}) const options = { method: 'POST', headers: { 'Content-Type': 'application/json'}, body: input }; const response = await fetch(flowUrl, options); console.log(response) if (response.status !== 200){ console.log('Status Code:', response.status); if(response.status == 404){ $("#ISBNInfoDisplayField").addClass("APICallError"); $("#ISBNInfoDisplayField").html("Boken hittades inte.
"); screenReaderMessage('Boken hittades inte'); }else if (response.status == 502){ $("#ISBNInfoDisplayField").addClass("APICallError"); $("#ISBNInfoDisplayField").html("Information om boken kunde inte hämtas i rätt format. Vänligen fyll i uppgifterna manuellt.
"); screenReaderMessage('Information om boken kunde inte hämtas i rätt format. Vänligen fyll i uppgifterna manuellt'); }else{ $("#ISBNInfoDisplayField").addClass("APICallError"); $("#ISBNInfoDisplayField").html("Ett fel har uppstått. Vänligen fyll i uppgifterna manuellt eller försök igen senare.
"); screenReaderMessage('Ett fel har uppstått. Vänligen fyll i uppgifterna manuellt eller försök igen senare.'); } }else{ const data = await response.json(); //Steg 2 if(step == 2){ $("#mtm_title").val(data.Title); $("#mtm_title").prop("readonly", (data.Title && data.Title.trim() !== "")); $("#mtm_author").val(data.Author); $("#mtm_author").prop("readonly", (data.Author && data.Author.trim() !== "")); $("#ne_utgivningsar").val(data.PublicationYear); console.log(data.PublicationYear && data.PublicationYear.trim() !== ""); $("#ne_utgivningsar").prop("readonly", (data.PublicationYear && data.PublicationYear.trim() !== "")); $("#ne_utgivningsar").prop("type", "number"); $("#ne_utgivningsar").prop("placeholder", "ÅÅÅÅ"); addRequiredFieldValidator("ne_utgivningsar"); $("#mtm_edition").val(data.Editions); $("#mtm_edition").prop("readonly", (data.Editions && data.Editions.trim() !== "")); $("#mtm_totalpages").val(data.TotalPages); $("#mtm_classificationcode").val(data.ClassificationCode); $("#mtm_classificationcode").prop("readonly", (data.ClassificationCode && data.ClassificationCode.trim() !== "")); validISBN = true; if (data.Language) { $.ajax({ type: "GET", dataType: 'json', url: "~/fetch-language?languageId=" + encodeURIComponent(data.Language) }).done(function (res) { if (res.results && res.results.length) { const resultObj = res.results[0]; $('#ne_sprak_2').attr('readonly', false); $("#ne_sprak_2_name").val(resultObj.languageName); $("#ne_sprak_2").val(resultObj.languageGuid); $("#ne_sprak_2_entityname").val("ne_language"); $('#ne_sprak_2').attr('readonly', true); } }); } }else if (step == 1){ //Steg 1 if(response == ""){ $("#NextButton").prop("disabled", true); clearISBNFormInputField(); $("#ISBNInfoDisplayField").addClass("APICallError"); $("#ISBNInfoDisplayField").html("Boken hittades inte.
"); screenReaderMessage('Boken hittades inte'); }else{ $("#ne_isbn_name").val(ISBNNo); $("#ne_isbn_entityname").val("ne_isbn"); $("#ne_isbn").val(data.ne_isbnid); $("#NextButton").prop("disabled", false); $("#ISBNInfoDisplayField").addClass("APICallSuccess"); $("#ISBNInfoDisplayField").fadeIn(300).html("Boken hittades.
"); $(".isbn").html("Titel
" + data.Title +"
Författare
" + data.Author +"
"); screenReaderMessage('Boken hittades. Titel: ' + data.Title + ' Författare: ' + data.Author); $(".isbn").slideDown(400, function() { $(".isbn").show(); }); validISBN = true; enableDisableSubmitButton(); } } } }catch (err) { (err); } } function setVisible(hideManualInputFields){ if(hideManualInputFields){ $("#mtm_title").parent().parent().hide(); $("#mtm_title").val($("#ne_title").val()); $("#mtm_author").parent().parent().hide(); $("#ne_utgivningsar").parent().parent().hide(); $("#mtm_edition").parent().parent().hide(); $("#mtm_totalpages").parent().parent().hide(); $("#mtm_language_lookupmodal").parent().parent().hide(); $("#ne_isbninput").prop("disabled", true); }else{ $("#ne_isbninput").parent().parent().hide(); $("#QuickviewControl1709567306154").hide(); } $("#mtm_noisbn").parent().parent().hide(); } const UserMessage = (() => { // Private function: Get configuration for type of message function getTypeConfig(type) { const typeMap = { wait: {cssClass: "", icon: "lds-dual-ring"}, error: { cssClass: "APICallError", icon: "bi bi-x-circle" }, success: { cssClass: "APICallSuccess", icon: "bi bi-check2-circle" } }; return typeMap[type] || null; } // Public function: Create a new user message (returns the HTML) function createMessage(id, type, message) { if (!id || !type) { console.warn("CreateUserMessage missing id or type"); return ""; } const typeConfig = getTypeConfig(type); if (!typeConfig) { console.warn("Invalid message type. Use 'error' or 'success'."); return ""; } // Build and return the HTML content return `