var delayTimer;
/* ### FILTER AND VIEW FUNCTIONS ### */
// Search
function doSearch(text, templateId, mainTemplateId) {
clearTimeout(delayTimer);
delayTimer = setTimeout(function() {
updateFilter("search", encodeURIComponent(String(text)), templateId, mainTemplateId);
}, 500);
}
function toggleSelection(button) {
$("#categoryFilters > a").removeClass("active");
$("#zipFilters > a").removeClass("active");
$(button).addClass("active");
}
/* ### END FILTER AND VIEW ACTIONS ### */
/* ### DYNAMIC LOADING ### */
// Update filter in queries
function updateFilter(filterName, filterValue, templateId, mainTemplateId, contentDiv) {
// Get current queries from URL
var urlQueries = window.location.search;
let path = window.location.pathname;
if (!(contentDiv || typeof contentDiv === "string")) {
contentDiv = "contentSub";
}
// Update or insert filter
urlQueries = updateQueryValue(filterName, filterValue, urlQueries);
if (mainTemplateId && mainTemplateId > 0) {
urlQueries = updateQueryValue("MainTemplateId", mainTemplateId, urlQueries);
}
// Update content
updateContent(templateId, urlQueries.substring(1) + `&Path=${path}&ContentDiv=${contentDiv}`);
}
// Update div content
function updateContent(templateId, queries, scroll) {
if (typeof templateId !== "number") {
console.log("Template id not defined, unable to update content. Exiting!");
return false;
}
// Check for filter update and remove it from queries
var filterUpdate = (getQueryValue("FilterUpdate", queries) === "true");
queries = removeQuery("FilterUpdate", queries);
// Check which content div to update
var contentDiv = getQueryValue("ContentDiv", queries);
queries = removeQuery("ContentDiv", queries);
if (typeof contentDiv !== "string" || contentDiv === "") {
contentDiv = "contentMain";
}
// Check if history is to be updated
var noHistory = filterUpdate || (getQueryValue("History", queries) === "false");
queries = removeQuery("History", queries);
if (!noHistory) {
// Get path from queries
var path = getQueryValue("Path", queries);
queries = removeQuery("Path", queries);
} else {
path = window.location.pathname;
}
// Save current page scroll before ajax load
try {
window.history.state.scrollTop = $(window).scrollTop();
window.history.replaceState(window.history.state, "", window.location.pathname);
} catch (e) {
console.log("Error saving history - " + e);
};
// Get dialog html from template
$.ajax({
type: "POST",
url: "/servlet/wisweb.ViewData",
data: "TemplateId=" + String(templateId) + "&" + String(queries) + "&PortalId=" + String(jsPortalId) + "&DesignAreaId=" + jsDesignAreaId
}).done(function(html) {
if ($(html).find(`#${contentDiv}`).length > 0) {
$("#" + contentDiv).html($(html).find(`#${contentDiv}`).html());
} else {
$("#" + contentDiv).html(html);
}
// Initialize and localize Bootstrap-Select
if ($('.selectpicker').length) {
$('.selectpicker').selectpicker({noneResultsText: "Ingen treff for {0}"});
$('.selectpicker').selectpicker({noneSelectedText: "Alle målgrupper"});
$('.selectpicker').selectpicker({countSelectedText: "{0} valgt"});
$('.selectpicker').selectpicker({selectedTextFormat: "count > 1"});
}
if (scroll && scroll > 0) {
$(window).scrollTop(scroll);
} else {
$(".menu-container")[0].scrollIntoView();
}
queries = removeQuery("secret-code", queries);
if (hasQuery("MainTemplateId", queries)) {
updateURL(getQueryValue("MainTemplateId", queries), path, removeQuery("MainTemplateId", queries), noHistory);
} else {
updateURL(templateId, path, queries, noHistory);
}
initImageGalleries(contentDiv);
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
}).fail(function(html) {
console.log("Error retrieving template. Exiting!");
console.log(html);
});
}
// Update the URL
function updateURL(templateId, path, queries, noHistory) {
if (queries.startsWith("?") || queries.startsWith("&")) {
queries = queries.slice(1);
}
let stateObj;
if (typeof queries === "string" && queries !== "") {
if (queries.indexOf("?") !== 0) {
path = path + "?" + queries;
} else {
path = path + queries;
}
stateObj = { templateId: parseInt(templateId), queries: queries };
} else {
stateObj = { templateId: parseInt(templateId), queries: "" };
}
// Check that path starts with /
if (path.indexOf("/") !== 0) path = "/" + path;
if (typeof noHistory === "boolean" && noHistory === true) {
window.history.replaceState(stateObj, "", path);
} else {
window.history.pushState(stateObj, "", path);
}
}
function initImageGalleries(contentId) {
let selector = ".image-gallery";
if (contentId) {
selector = "#" + contentId + " .image-gallery";
}
if ($(selector).length && $.fn.magnificPopup) {
$(selector).magnificPopup({
delegate: 'a',
type: 'image',
gallery: {
enabled: true,
preload: [0,2]
}
});
}
}
function initEditor(editorId) {
if (editorId) {
new FroalaEditor("#" + String(editorId), {
key: '1CC3kB5D7A4C4D4A3bHIMFF1EWBXIJb1BZLZFh1i1MXQLjE4C3F3H3B4A5A4E3A3H3',
toolbarInline: false,
language: 'nb',
useClasses: true,
heightMin: 100,
imageUploadParam: 'ww_File',
imageUploadURL: '',
imageUploadParams: {source: 'froala-editor'},
imageUploadMethod: 'POST',
imageResizeWithPercent: true,
imageRoundPercent: true,
imageDefaultAlign: 'left',
imageDefaultWidth: 100,
attribution: false,
toolbarSticky: false,
entities: '',
imageEditButtons: ['imageAlign', 'imageCaption', 'imageRemove', '|', 'imageLink', 'linkOpen', 'linkEdit', 'linkRemove', '-', 'imageDisplay', 'imageStyle', 'imageAlt', 'imageSize'],
toolbarButtons: ['fullscreen', '|', 'undo', 'redo', '|', 'paragraphFormat', 'formatOL', 'formatUL', '|', 'outdent', 'indent', 'align', 'quote', '|', 'bold', 'italic', 'underline', 'clearFormatting', '|', 'fontFamily', 'fontSize', 'color', '|', 'html', '-', 'insertLink', 'insertImage', 'insertFile', 'insertTable', 'insertVideo', 'insertHR', 'customInsertSection'],
toolbarButtonsXS: ['fullscreen', '|', 'paragraphFormat', 'formatOL', 'formatUL', '|', 'bold', 'italic', '-', 'insertLink', 'insertImage', 'insertVideo', 'insertFile', 'insertTable', 'insertHR']
})
} else {
new FroalaEditor('.froala-editor', {
key: '1CC3kB5D7A4C4D4A3bHIMFF1EWBXIJb1BZLZFh1i1MXQLjE4C3F3H3B4A5A4E3A3H3',
toolbarInline: false,
language: 'nb',
useClasses: true,
heightMin: 100,
imageUploadParam: 'ww_File',
imageUploadURL: '',
imageUploadParams: {source: 'froala-editor'},
imageUploadMethod: 'POST',
imageResizeWithPercent: true,
imageRoundPercent: true,
imageDefaultAlign: 'left',
imageDefaultWidth: 100,
attribution: false,
toolbarSticky: false,
entities: '',
imageEditButtons: ['imageAlign', 'imageCaption', 'imageRemove', '|', 'imageLink', 'linkOpen', 'linkEdit', 'linkRemove', '-', 'imageDisplay', 'imageStyle', 'imageAlt', 'imageSize'],
toolbarButtons: ['fullscreen', '|', 'undo', 'redo', '|', 'paragraphFormat', 'formatOL', 'formatUL', '|', 'outdent', 'indent', 'align', 'quote', '|', 'bold', 'italic', 'underline', 'clearFormatting', '|', 'fontFamily', 'fontSize', 'color', '|', 'html', '-', 'insertLink', 'insertImage', 'insertFile', 'insertTable', 'insertVideo', 'insertHR', 'customInsertSection'],
toolbarButtonsXS: ['fullscreen', '|', 'paragraphFormat', 'formatOL', 'formatUL', '|', 'bold', 'italic', '-', 'insertLink', 'insertImage', 'insertVideo', 'insertFile', 'insertTable', 'insertHR']
})
}
}
function showDialog(type, params, stacked) {
let dialogDiv = "dialog";
if (type === "img") {
data = "TemplateId=36855";
dialogDiv = "imageDialog";
} else if (type === "event") {
data = "TemplateId=36827"
} else if (type === "reg") {
data = "TemplateId=36877"
} else {
return false
}
$.ajax({
type: "POST",
url: "/servlet/wisweb.ViewData",
data: data + "&" + String(params)
}).done(function(html) {
$("#" + dialogDiv).html(html);
initEditor();
$("#" + dialogDiv).modal("show");
}).fail(function(resp) {
console.log("Error retrieving template.");
console.log(resp);
})
}
/* ### END DYNAMIC LOADING ### */
/* ### URL QUERY FUNCTIONS ### */
function hasQuery(queryItemName, queries) {
// Remove preceeding questionmark
if (queries.indexOf("?") === 0) {
var queries = queries.substring(1).split("&");
} else {
var queries = queries.split("&");
}
if (typeof queries === "object" && queries.toString() !== "") {
var queryItems = {};
for (var i = 0; i < queries.length; i++) {
var split = queries[i].split('=');
queryItems[split[0].trim()] = (typeof split[1] !== "undefined") ? split[1].trim() : "";
}
if (queryItemName in queryItems) {
return true;
} else {
return false;
}
}
return false;
}
function updateQueryValue(queryName, queryValue, queries) {
var regQueryName = new RegExp("([?&])" + queryName + "=.*?(&|#|$)", "i");
if (queryValue === undefined || queryValue === "") {
if (queries.match(regQueryName)) {
return removeQuery(queryName, queries);
} else {
return queries;
}
} else {
if (queries.match(regQueryName)) {
return queries.replace(regQueryName, '$1' + queryName + "=" + queryValue + '$2');
} else {
var hash = '';
if (queries.indexOf('#') !== -1) {
hash = queries.replace(/.*#/, '#');
queries = queries.replace(/#.*/, '');
}
var separator = queries.indexOf('?') !== -1 ? "&" : "?";
return queries + separator + queryName + "=" + queryValue + hash;
}
}
}
function removeQuery(queryName, queries) {
var rtn = queries.split("?")[0],
param,
params_arr = [],
queryString = (queries.indexOf("?") !== -1) ? queries.split("?")[1] : queries;
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === queryName) {
params_arr.splice(i, 1);
}
}
rtn = (queries.indexOf("?") !== -1) ? rtn + "?" + params_arr.join("&") : params_arr.join("&");
}
return rtn;
}
function getQueryValue(queryName, queries) {
var queries = queries.substring(1).split("&");
var queryItems = {};
for (var i = 0; i < queries.length; i++) {
var split = queries[i].split('=');
if (typeof split[1] !== "undefined") {
queryItems[split[0].trim()] = split[1].trim();
} else {
queryItems[queries[i]] = queries[i];
}
}
if (queryName in queryItems) {
return queryItems[queryName];
} else {
return "";
}
}
/* ### END URL QUERY ### */
/* ### EVENTS ### */
window.onpopstate = function(event) {
try {
updateContent(event.state.templateId, event.state.queries + "&History=false", event.state.scrollTop);
$(".menu-container .item-active").removeClass("item-active");
$("#menuItem-" + event.state.templateId).addClass("item-active");
} catch (e) {
$(".menu-container")[0].scrollIntoView();
console.log(e);
//window.location.reload(true);
}
};
/* ### END EVENTS ### */
function MonthLength(intMonth, intYear)
{
// Sjekk måneder med 30 dager
if ( (intMonth == 4) || (intMonth == 6) || (intMonth == 9) || (intMonth == 11) )
return 30;
// Sjekk om februar har et skuddår - alle år delbar på 4, bortsett fra de delelig på 100 (men IKKE 400)
if (intMonth == 2)
{
var leapyear = false;
if ( (Math.floor(intYear/4) == (intYear/4)) && ((Math.floor(intYear/100) != (intYear/100)) || (Math.floor(intYear/400) == (intYear/400))) ) {
return 29;
}
return 28;
}
return 31;
}
function checkDate(elDate) {
if (!elDate) elDate = this;
var strInput = new String(elDate.value);
if (strInput == "") return true;
// Gjør om alle kjente typer separatorer
strInput = strInput.replace(new RegExp(",", "g"), ".");
strInput = strInput.replace(new RegExp(";", "g"), ".");
strInput = strInput.replace(new RegExp(":", "g"), ".");
strInput = strInput.replace(new RegExp(" ", "g"), ".");
strInput = strInput.replace(new RegExp("-", "g"), ".");
strInput = strInput.replace(new RegExp("_", "g"), ".");
strInput = strInput.replace(new RegExp("/", "g"), ".");
strInput = strInput.replace(new RegExp("\\\\", "g"), ".");
// Splitt teksten på separatorer
var arParts = strInput.split(".");
// Dato på formen ddmm
if (arParts.length == 1 && strInput.length == 4)
{
arParts[0] = strInput.substring(0, 2);
arParts[1] = strInput.substring(2, 4);
arParts[2] = "";
}
// Dato på formen ddmmåå
if (arParts.length == 1 && strInput.length == 6)
{
arParts[0] = strInput.substring(0, 2);
arParts[1] = strInput.substring(2, 4);
arParts[2] = strInput.substring(4, 6);
}
// Dato på formen ddmmåååå
if (arParts.length == 1 && strInput.length == 8)
{
arParts[0] = strInput.substring(0, 2);
arParts[1] = strInput.substring(2, 4);
arParts[2] = strInput.substring(4, 8);
}
// Finn gjeldende dato
var today = new Date();
var dateNow = today.getDate();
var monthNow = today.getMonth() + 1;
var yearNow = today.getFullYear();
yearNow = new String(yearNow);
// Gjør om dag til tall
var date = parseInt(arParts[0], 10);
if (isNaN(date)) date = dateNow;
// Gjør om måned til tall
var month = parseInt(arParts[1], 10);
if (isNaN(month)) month = monthNow;
// Gjør om år til tall
var year = parseInt(arParts[2], 10);
if (isNaN(year)) year = yearNow;
if (date < 1) date = 1;
if (date > 31) date = 31;
if (month < 1) month = 1;
if (month > 12) month = 12;
if (year < 0) year = today.getFullYear();
// Tar hensyn til ulik lengde på månedene (f.eks 30.02.2006 -> 28.02.2006)
var monthlen = MonthLength(month, year);
if (date > monthlen) date = monthlen;
// Gjør om alle tall til tekster
date = new String(date);
month = new String(month);
year = new String(year);
// Korriger lengde på tall (foranstilte nuller)
while (date.length < 2) date = "0" + date;
while (month.length < 2) month = "0" + month;
if (year.length < 4) year = yearNow.substring(0, 4 - year.length) + year;
// Erstatt original verdi
elDate.value = date + "." + month + "." + year;
return true;
}
function checkTime(elTime) {
var strInput = new String(elTime.value);
if (strInput == "") return true;
// Gjør om alle kjente typer separatorer
strInput = strInput.replace(new RegExp(",", "g"), ".");
strInput = strInput.replace(new RegExp(";", "g"), ".");
strInput = strInput.replace(new RegExp(":", "g"), ".");
strInput = strInput.replace(new RegExp(" ", "g"), ".");
strInput = strInput.replace(new RegExp("-", "g"), ".");
strInput = strInput.replace(new RegExp("_", "g"), ".");
strInput = strInput.replace(new RegExp("/", "g"), ".");
strInput = strInput.replace(new RegExp("\\\\", "g"), ".");
// Splitt teksten på separatorer
var arParts = strInput.split(".");
// Tid på formen t/tt
if (arParts.length == 1 && strInput.length < 3 && strInput.length > 0)
{
arParts[0] = strInput;
arParts[1] = "";
}
// Tid på formen tmm
if (arParts.length == 1 && strInput.length == 3)
{
arParts[0] = strInput.substring(0, 1);
arParts[1] = strInput.substring(1, 3);
}
// Tid på formen ttmm
if (arParts.length == 1 && strInput.length == 4)
{
arParts[0] = strInput.substring(0, 2);
arParts[1] = strInput.substring(2, 4);
}
// Gjør om time til tall
var hour = parseInt(arParts[0], 10);
if (isNaN(hour)) hour = 0;
// Gjør om minutt til tall
var minute = parseInt(arParts[1], 10);
if (isNaN(minute)) minute = 0;
// Korrigere time
if (hour < 0) hour = 0;
if (hour > 23) hour = 23;
// Korrigere minutt
if (minute < 0) minute = 0;
if (minute > 59) minute = 59;
// Gjør om alle tall til tekster
hour = new String(hour);
minute = new String(minute);
// Korriger lengde på tall
while (hour.length < 2) hour = "0" + hour;
while (minute.length < 2) minute = "0" + minute;
// Erstatt original verdi
elTime.value = hour + ":" + minute;
return true;
}