Files
Saxonite/SaxoniteCoreWebOnline/wwwroot/js/sax-main.js
T
2021-07-10 14:23:14 +01:00

519 lines
16 KiB
JavaScript

/*
* Main scripts.
*/
(function (win, doc, undef)
{
"use strict";
win.sax = win.sax || {};
//--------------------------------------------------------------
// Utilities.
sax.isDef = function (obj)
{
return obj === null || typeof obj == "undefined" ? false : true;
}
sax.isFn = function (fn)
{
return fn != null && typeof fn == typeof Function;
}
sax.isNumeric = function (n)
{
return !isNaN(parseFloat(n)) && isFinite(n);
}
sax.zeroPad = function (num, count)
{
var val = num + '';
while (val.length < count) val = "0" + val;
return val;
}
sax.toInt = function (value, defaultValue)
{
return sax.isNumeric(value) ? parseInt(value, 10) : defaultValue || 0;
}
if ("function" != typeof "".format)
String.prototype.format = (function ()
{
var rx1 = /\{(\d|\d\d)\}/g, rx2 = /\d+/;
return function ()
{
var args = arguments;
return this.replace(rx1, function ($0)
{
var idx = 1 * $0.match(rx2)[0];
return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : $0);
});
}
}());
sax.getFileType = function (file)
{
if (!file) return "";
if (file.type) return file.type;
if (file.filename) return filename.split('.').pop();
return "";
}
sax.formatFileSize = function (size)
{
if (size / 10 ** 9 > 1) return Math.floor(size / 10 ** 9) + 'Gb';
if (size / 10 ** 6 > 1) return Math.floor(size / 10 ** 6) + 'Mb';
if (size / 10 ** 3 > 1) return Math.floor(size / 10 ** 3) + 'Kb';
return size + 'bytes';
}
sax.escapeRegExp = function (val)
{
return (val || '').replace(/[[{}()*+?^$|\]\.\\]/g, "\\$&");
}
sax.haltEvent = function (evt)
{
evt.preventDefault();
evt.stopPropagation();
}
sax.debug = sax.debugMode ? win.console.log.bind(win.console) : function () { };
//--------------------------------------------------------------
sax.setOddDataRowClass = function (rowSel, cName)
{
$(rowSel).addClass(function (index, currentClasses)
{
return index % 2 == 1 ? (cName || "other") : "";
});
}
sax.populateSelectCodeDesc = function ($sel, values)
{
$sel = $($sel).empty();
for (const value of values)
$sel.append($('<option>').prop('value', value.code).text(value.desc));
}
sax.checkTextAreaMaxLength = function (ctrl, len)
{
if (ctrl == null || ctrl.value == null) return;
if (ctrl.value.length > len) ctrl.value = ctrl.value.substring(0, len);
}
sax.setAvailableCharsLabel = function ($if, max, $lbl)
{
var avail = Math.max(0, max - $if.val().length);
$lbl.text(avail == 1 ? sax.lbl.availableCharacter : sax.lbl.availableCharacters.replace(/\{0\}/g, avail));
}
sax.setCharsAvailableLabel = function ($if, max)
{
var avail = Math.max(0, max - $if.val().length);
$('.sax-select-chars-available', $if.closest('.sax-form-control')).text(avail == 1 ? sax.lbl.availableCharacter : sax.lbl.availableCharacters.replace(/\{0\}/g, avail));
}
sax.setItemsSelectedLabel = function ($sel)
{
var sel = $(':selected', $sel).length;
$('.sax-select-items-selected', $sel.closest('.sax-form-control')).text(sel == 0 ? sax.lbl.noneSelected : sax.lbl.numberSelected.replace(/\{0\}/g, sel));
}
sax.initCalendars = function (sel)
{
return $(sel).datepicker();
}
sax.refreshPaging = function (response, context, refreshFn)
{
if (sax.resultsPaging.fn.refreshPaging)
sax.resultsPaging.fn.refreshPaging(response.paging, context, refreshFn);
}
//--------------------------------------------------------------
// Page navigation.
sax.navigateTo = function (action)
{
sax.doPleaseWait();
$('#frmNavigate').prop('action', sax.url.base + action).submit();
}
sax.goToPage = function (action)
{
sax.doPleaseWait();
location = sax.url.base + action;
}
// Account action.
sax.onAccountAction = function (select)
{
var action = $(select).val();
$(select).val("");
if (action == "Profile")
sax.navigateTo("Profile");
else if (action == "Organisations")
sax.navigateTo("Organisations");
}
// Security.
sax.redirectHome = function ()
{
sax.goToPage('');
}
sax.redirectHomeExp = function ()
{
sax.doPleaseWait();
document.location = sax.url.sesionExpired;
}
sax.onSignOut = function ()
{
sax.doConfirm(sax.dlg.title.signOut, sax.msg.signOutConfirm, sax.doSignOut);
}
sax.doSignOut = function ()
{
sax.doAjaxRequest({ url: sax.url.base + 'Security/Ajax/SignOut', formId: 'frmNavigate' }, 50);
}
//--------------------------------------------------------------
// Dialogs.
sax.openDialog = function ($dlg, width, height)
{
let $win = $(win);
$dlg.dialog(
{
minWidth: null, maxWidth: null, width: Math.min(width || 400, $win.width() * .90),
minHeight: null, maxHeight: null, height: Math.min(height || 320, $win.innerHeight() * .96)
}).dialog('open');
return $dlg;
}
sax.dlgOpts = function ()
{
return { autoOpen: false, modal: true, show: 'clip', hide: 'clip', minWidth: 320, maxWidth: 480, width: 'auto', resizable: false, draggable: false, closeOnEscape: false, dialogClass: "dialog-no-close", buttons: {} };
}
sax.dlgOptsClose = function ()
{
var opts = sax.dlgOpts();
opts.buttons[sax.dlg.btn.close] = function () { $(this).dialog('close'); };
return opts;
}
sax.doAlert = function (title, msg, onOk)
{
if (!msg)
{
msg = title;
title = null;
}
if (!sax.isDef(sax.$dlg.alert))
{
var opt = sax.dlgOpts();
opt.buttons[sax.dlg.btn.ok] = function () { $(this).dialog('close'); if (onOk) onOk(); };
sax.$dlg.alert = $('<div id="dlgAlert"><div id="dlgAlertMsg"></div></div>').dialog(opt);
}
$('#dlgAlertMsg', sax.$dlg.alert).html(msg);
sax.$dlg.alert.dialog('option', { title: title || sax.dlg.title.alert });
sax.openDialog(sax.$dlg.alert);
}
sax.doConfirm = function (title, msg, onOk, onCancel)
{
if (!msg)
{
msg = title;
title = null;
}
if (!sax.isDef(sax.$dlg.confirm))
{
var opt = sax.dlgOpts();
sax.$dlg.confirm = $('<div id="dlgConfirm"><div class="spacer2"></div><div id="dlgConfirmMsg"></div></div>').dialog(opt);
}
var buttons = sax.$dlg.confirm.dialog('option', 'buttons');
buttons[sax.dlg.btn.yes] = function () { $(this).dialog('close'); if (onOk) onOk(); };
buttons[sax.dlg.btn.no] = function () { $(this).dialog('close'); if (onCancel) onCancel(); };
sax.$dlg.confirm.dialog('option', { title: title || sax.dlg.title.confirm, 'buttons': buttons });
$('#dlgConfirmMsg').html(msg);
sax.openDialog(sax.$dlg.confirm);
}
sax.confirmItemRemove = function (fn)
{
sax.doConfirm('', sax.msg.itemRemoveConfirm, fn);
}
sax.doProgress = function (title, msg, delay)
{
if (!msg)
{
msg = title;
title = null;
}
clearTimeout(sax.toShowProgress);
if (!sax.isDef(sax.$dlg.progress))
{
var opt = sax.dlgOpts();
opt.show = { effect: 'fade', duration: 200 };
opt.hide = { effect: 'fade', duration: 200 };
sax.$dlg.progress = $('<div id="dlgProgress"><div id="dlgProgressMsg"></div></div>').dialog(opt);
}
$('#dlgProgressMsg').html(msg);
sax.$dlg.progress.dialog('option', { title: title || sax.dlg.title.progress });
if (delay > 0) sax.toShowProgress = setTimeout(function () { sax.$dlg.progress.dialog('open'); }, delay);
else sax.$dlg.progress.dialog('open');
}
sax.hideProgress = function ()
{
clearTimeout(sax.toShowProgress);
sax.$dlg.progress.dialog('close');
}
//--------------------------------------------------------------
// Notifications.
sax.showNotification = function (title, msg)
{
win.clearTimeout(sax.toNotification);
var $win = $(win);
var $not = $('#sax-notification').hide();
if (!$not.length)
{
$not = $('<div id="sax-notification"><div class="content"><div class="heading"><div class="close" onclick="sax.hideNotification()">&#10006;</div><div class="title"></div></div><div class="message"></div></div></div>');
$('body').append($not);
}
var $hdr = $('.heading', $not).css({ 'background-color': 'rgba(247,217,0,0.7)' });
$('.title', $not).html(title);
$('.message', $not).html(msg);
var $bdy = $('#sax-page-body');
//sax.debug(sax.topMargin($bdy));
var fbr = $bdy[0].getBoundingClientRect();
var fn = function () { $hdr.delay(2000).animate({ backgroundColor: '#f0f0f0' }, 1000); };
$not.css({ 'top': Math.max(0, fbr.top - sax.topMargin($bdy)), 'right': $win.width() - fbr.right }).slideDown(500, fn);
sax.toNotification = setTimeout(sax.hideNotification, 6000);
}
sax.hideNotification = function ()
{
win.clearTimeout(sax.toNotification);
$('#sax-notification').slideUp(500);
}
sax.doPleaseWait = function ()
{
sax.$pleaseWait = sax.$pleaseWait || $('#sax-please-wait');
sax.$pleaseWait.stop(true, false).animate({ "null": 1 }, 200).fadeTo(200, 1);
}
sax.hidePleaseWait = function ()
{
if (sax.$pleaseWait) sax.$pleaseWait.stop(true, false).fadeOut(200);
}
//--------------------------------------------------------------
// Ajax.
sax.doAjaxRequest = function (ajax, delay)
{
win.clearTimeout(ajax.timeout);
if (!ajax.noWaitIcon) sax.doPleaseWait();
ajax.timeout = setTimeout(function () { sax.execAjaxRequest(ajax); }, Math.max(50, parseInt(delay || 0, 10)));
}
sax.execAjaxRequest = function (ajax)
{
win.clearTimeout(ajax.timeout);
if (ajax.request) ajax.request.abort();
var cfgAjax =
{
url: ajax.url,
type: 'POST',
cache: false,
//enctype: 'multipart/form-data',
data: ajax.formData || $("#" + ajax.formId).serialize(),
dataType: 'json',
success: function (response, status, jqXHR)
{
if (!ajax.noWaitIcon) sax.hidePleaseWait();
ajax.status = status;
if (response.notification)
sax.showNotification(response.notification.title, response.notification.message);
if (response.message)
{
var fnCloseAlert = function ()
{
if (response.sessionExpired) return sax.redirectHomeExp();
if (response.goHome) return sax.redirectHome();
if (ajax.callbackFn) ajax.callbackFn(response);
}
sax.doAlert(response.message.title, response.message.text, function () { fnCloseAlert(); });
}
else if (response.sessionExpired)
return sax.redirectHomeExp();
else if (response.goHome)
return sax.redirectHome();
else if (response.error && ajax.errFn) ajax.errFn(response);
else if (ajax.callbackFn) ajax.callbackFn(response);
},
error: function (jqXHR, status, errorThrown)
{
if (!ajax.noWaitIcon) sax.hidePleaseWait();
ajax.status = status;
if (status == "abort") return;
sax.doAlert(sax.dlg.title.alert, sax.msg.somethingGoneWrong, sax.redirectHome);
},
complete: function (jqXHR, textStatus)
{
if (!ajax.noWaitIcon) sax.hidePleaseWait();
ajax.formData = null;
ajax.complete = true;
}
}
if (ajax.formData)
{
//for (var pair of ajax.formData.entries()) sax.debug(pair[0] + ': ' + pair[1]);
cfgAjax.processData = false;
cfgAjax.contentType = false;
}
ajax.request = $.ajax(cfgAjax);
}
//--------------------------------------------------------------
// Session.
sax.configureKeepLoggedIn = function ()
{
//sax.debug('KeepLoggedIn Configuring');
setTimeout(sax.doKeepLoggedIn, Math.max(30000, sax.keepLoggedInDelay || 300000));
}
sax.doKeepLoggedIn = function ()
{
//sax.debug('KeepLoggedIn Calling');
var onKeepLoggedIn = function (response)
{
//sax.debug('KeepLoggedIn Responded', response);
sax.configureKeepLoggedIn();
}
sax.doAjaxRequest({ url: sax.url.base + 'Security/Ajax/KeepLoggedIn', formId: 'frmNavigate', noWaitIcon: true, callbackFn: onKeepLoggedIn }, 1000)
}
sax.configureSessionRefresh = function ()
{
//sax.debug('SessionRefresh Configuring');
$(document).on('mousedown mousemove touchstart scroll keydown', sax.triggeRefreshSession);
}
sax.triggeRefreshSession = function ()
{
sax.session = sax.session || { refresh: {} };
let ssr = sax.session.refresh;
win.clearTimeout(ssr.timeout);
ssr.timeout = setTimeout(function () { sax.refreshSession(); }, 150000);
}
sax.refreshSession = function ()
{
//sax.debug('sax.refreshSession');
sax.doKeepLoggedIn();
}
//--------------------------------------------------------------
// Data entry.
sax.clearControlErrors = function (context)
{
var $ctrls = $('.sax-form-control', $(context)).removeClass('sax-error');
$('.sax-message', $ctrls).empty();
}
sax.clearControlError = function (sel)
{
var $ctrl = $(sel).closest('.sax-form-control').removeClass('sax-error');
$('.sax-message', $ctrl).empty();
}
sax.setControlError = function (sel, error)
{
var $ctrl = $(sel).closest('.sax-form-control').toggleClass('sax-error', !!error.length);
$('.sax-message', $ctrl).text(error);
}
sax.refreshControlValues = function (controlValues, context)
{
var $frmCtrls = $('.sax-form-control', $(context)).removeClass('sax-error');
sax.clearControlErrors();
var values = (controlValues || []);
var valuesLen = values.length;
for (var valIdx = 0; valIdx < valuesLen; valIdx++)
{
let ctrlValue = values[valIdx];
$frmCtrls.each(function (idx, frmCtrl)
{
var $frmCtrl = $(frmCtrl);
if (!$frmCtrl.hasClass(ctrlValue.controlName)) return;
var $ctrl = $('input,textarea,select', $frmCtrl);
if ($ctrl.length && $ctrl.prop('name') == ctrlValue.controlName && ctrlValue.value)
$ctrl.val(ctrlValue.value);
if (ctrlValue.error)
$frmCtrl.addClass('sax-error').find('.sax-message').text(ctrlValue.error);
});
}
}
//--------------------------------------------------------------
// Elements.
sax.objBtm = function (sel)
{
var $obj = $(sel);
return Math.floor($obj.offset().top + $obj.outerHeight(true));
}
sax.innerBtm = function (sel)
{
var $obj = $(sel);
return Math.floor($obj.offset().top + $obj.outerHeight() - sax.bottomSurround($obj));
}
sax.innerTop = function (sel)
{
var $obj = $(sel);
return Math.floor($obj.offset().top + sax.topSurround($obj));
}
sax.topMargin = function (sel)
{
var $obj = $(sel);
return parseInt($obj.css('margin-top'), 10);
}
sax.topSurround = function (sel)
{
var $obj = $(sel);
return parseInt($obj.css('margin-top'), 10) + parseInt($obj.css('border-top-width'), 10) + parseInt($obj.css('padding-top'), 10);
}
sax.bottomSurround = function (sel)
{
var $obj = $(sel);
return parseInt($obj.css('margin-bottom'), 10) + parseInt($obj.css('border-bottom-width'), 10) + parseInt($obj.css('padding-bottom'), 10);
}
sax.marginHeight = function (sel)
{
var $obj = $(sel);
return parseInt($obj.css('margin-top'), 10) + parseInt($obj.css('margin-bottom'), 10);
}
sax.borderHeight = function (sel)
{
var $obj = $(sel);
return parseInt($obj.css('border-top-width'), 10) + parseInt($obj.css('border-bottom-width'), 10);
}
//--------------------------------------------------------------
// Viewport - Desktop or Mobile.
sax.isMob = function () { return $('body.mob').length > 0; };
sax.onChangeViewport = function (viewport)
{
var $body = $('body');
$body.removeClass('mob dsk');
if (viewport.is('xs')) $body.addClass('mob');
else if (viewport.current() != 'unrecognized') $body.addClass('dsk');
}
sax.isAutoHeight = function () { return ($(win).width() < 360 || $(win).height() < 560 || sax.isMob()); }
sax.onWinResizePage = function () { };
sax.onWinResize = function ()
{
var winH = $(win).height();
var $pageBody = $('#sax-page-body');
var $hdr = $('#sax-page-header');
var $ftr = $('#sax-page-footer');
if (sax.isAutoHeight())
$pageBody.height('auto');
else
$pageBody.innerHeight(Math.min(1200, winH - $hdr.outerHeight() - $ftr.outerHeight(true)));
$ftr.css('visibility', 'visible');
sax.onWinResizePage();
}
//--------------------------------------------------------------
$(function ()
{
$('.sax-button-cta,.sax-button-action,.sax-action-link,.sax-social-icon.sax-action').prop('tabindex', 0);
if (sax.keepLoggedIn)
sax.configureKeepLoggedIn();
else if (!sax.awaitingLogin)
sax.configureSessionRefresh();
$.datepicker.setDefaults({
showOn: 'both',
buttonImageOnly: true,
buttonImage: '../img/action/calendar32.png',
buttonText: sax.lbl.calendar,
dateFormat: sax.form.calendarDateFormat,
changeMonth: true,
changeYear: false,
yearRange: '-14:+01',
firstDay: 1,
//defaultDate: 0,
});
});
}(window, window.document));
/* The End */