/**
* Global functions
**/
function inherit(Child, Parent) {
// inherit PageBase
Child.prototype = Object.create(Parent.prototype);
// correct the constructor pointer because it points to PageBase
Child.prototype.constructor = Child;
}
function hasRole(role)
{
return false;
// var userRoles = App.tokenProfile.role.split(',');
// return $.inArray(role, userRoles) > -1;
}
function formKeyHandler(e)
{
var charCode = e.charCode || e.keyCode;
if (e.ctrlKey && charCode == 13) {
e.preventDefault();
$("#fmSave").trigger("click");
}
if (charCode == 27) {
$("#fmCancel").trigger("click");
}
}
function yesBlank(value)
{
if (value == '0' || !value || value == false)
return '';
else
return 'Ja';
}
function ymd2dmy(date)
{
if ($.trim(date) == '')
return '';
var y = date.substr(0, 4);
var mPos = date.lastIndexOf('-');
var m = date.substr(5, -5 + mPos);
var d = date.substr(mPos + 1);
return d + '.' + m + '.' + y;
}
function ymdts2dmyts(ts)
{
if ($.trim(ts) == '')
return 'Tillsvidare';
var y = ts.substr(0, 4);
var mPos = ts.lastIndexOf('-');
var m = ts.substr(5, -5 + mPos);
var hPos = ts.indexOf(' ');
var d = ts.substr(mPos + 1, hPos-mPos-1);
var mmPos = ts.indexOf(':');
var sPos = ts.lastIndexOf(':');
var h = ts.substr(hPos + 1, mmPos-hPos-1);
var mm = ts.substr(mmPos + 1, sPos-mmPos-1);
var s = ts.substr(sPos + 1);
return d + '.' + m + '.' + y + ' ' + h + ':' + mm;
}
function displayLoading(target) {
var element = $(target);
kendo.ui.progress(element, true);
}
function hideLoading(target) {
var element = $(target);
kendo.ui.progress(element, false);
}
function calculateSsnCheckDigit(ssn)
{
checkDigits = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','H','J','K','L','M','N','P','R','S','T','U','V','W','X','Y');
var digit = ssn % 31;
return checkDigits[digit];
}
function validateSsn(ssn)
{
var ssnWithoutCheckDigit;
var checkDigit;
/**
* Must be 11 characters
*/
if (ssn.length != 11)
return false;
/**
* Position 7 has to be '+' (1800-), '-' (1900-) or 'A' (2000-)
*
* We have to accept a space att position 7 to be able to validate constructed social security numbers.
*/
if (ssn.charAt(6) != '+' && ssn.charAt(6) != '-' && ssn.charAt(6) != 'A' && ssn.charAt(6) != ' ')
return false;
/**
* Calculate the checksum and compare
*/
ssnWithoutCheckDigit = ssn.substr(0, 6) + ssn.substr(7, 3);
checkDigit = ssn.charAt(10);
testDigit = calculateSsnCheckDigit(ssnWithoutCheckDigit);
if (testDigit == checkDigit)
result = true;
else
result = false;
return result;
}
function formatFoNumber(fo)
{
if (fo.indexOf('-') > 0)
return fo;
var foWithoutCheckDigit = fo.substr(0, fo.length-1);
var checkDigit = fo.charAt(fo.length-1);
return foWithoutCheckDigit + '-' + checkDigit;
}
function calculateFoNumberCheckDigit(fo)
{
var digit;
var multiplier1 = 2;
var multiplier2 = 4;
var multiplier3 = 8;
var multiplier4 = 5;
var multiplier5 = 10;
var multiplier6 = 9;
var multiplier7 = 7;
var len = fo.length;
var total = 0;
var lastDigit;
var ctr=0;
for (var i = len-1; i>=0; i--)
{
digit = parseInt(fo.charAt(i));
ctr++;
switch (ctr)
{
case 1:
sum = digit * multiplier1;
break;
case 2:
sum = digit * multiplier2;
break;
case 3:
sum = digit * multiplier3;
break;
case 4:
sum = digit * multiplier4;
break;
case 5:
sum = digit * multiplier5;
break;
case 6:
sum = digit * multiplier6;
break;
case 7:
sum = digit * multiplier7;
break;
}
total += sum;
}
total /= 11;
var rest = total - parseInt(total);
if (rest == 0)
result = 0;
else
{
result = 11 - Math.round(11 * rest);
}
return result;
}
function validateFoNumber(fo)
{
var foWithoutCheckDigit;
var checkDigit;
if (fo.length < 4 || fo.length > 11)
return false;
fo = fo.replace('-', '');
foWithoutCheckDigit = fo.substr(0, fo.length-1);
checkDigit = fo.charAt(fo.length-1);
testDigit = calculateFoNumberCheckDigit(foWithoutCheckDigit);
if (testDigit == checkDigit)
result = true;
else
result = false;
return result;
}
function dataGridOddBackground(e) {
var items = this._data;
var tableRows = $(this.table).find("tr");
tableRows.each(function(index) {
var row = $(this);
var rowItem = items[index];
if (index % 2 === 0) {
row.addClass("kendo-primary-row");
} else {
row.addClass("kendo-secondary-row");
}
});
}
function getCurrentDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if(dd < 10) {
dd = '0' + dd
}
if(mm < 10) {
mm = '0' + mm
}
today = yyyy + '-' + mm + '-' + dd;
return today;
}
function isDate(date) {
return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}
/**
* Download or open file response from XML HTTP request
*
* Open file if PDF, else download file.
*/
function XHROnloadDocument(xhr, filename) {
filename = filename ? filename : "";
if (xhr.readyState === 4 && xhr.status === 200) {
// var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([xhr.response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007:
// One or more blob URLs were revoked by closing the blob for which they were created.
// These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (type.includes("application/pdf")) {
window.open(downloadUrl, filename);
}
else {
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}
else {
$("#popupNotification").kendoNotification({autoHideAfter:0}).data("kendoNotification")
.show('Hoppsan, något gick fel. Det gick inte att hämta dokumentet.', "error");
// notification.error("Ursäkta, något gick fel. Det gick inte att hämta dokumentet.");
}
}
/**
* Use image data to insert image into HTML
*
* @param string image - base 64 image string
* @param jQuery container - where the image will be inserted
*/
function insertImage(image, container)
{
// create an image
var outputImg = document.createElement('img');
outputImg.src = 'data:image/image;base64,' + image;
// append it to your page
$(container).append(outputImg);
}
function clearErrors()
{
$('.error-message').html('');
}
function displayErrors(response)
{
var popupId = -1;
for (var i in response.responseJSON.messages) {
if (response.responseJSON.messages[i].field)
$("#" + response.responseJSON.messages[i].field.replace(/_/g, '-') + "-error").html('Ogiltigt värde');
else
popupId = i;
}
if (popupId != -1)
displayErrorMessage(response, popupId);
}
function displayErrorMessage(response, id)
{
var result = response.responseJSON;
kendo.alert(result.messages[id].text + ' (' + result.messages[id].code + ')');
}
function hash(string) {
var hash = 0;
if (string.length === 0) return hash;
for (i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
/**
* Copy text to clipboard
*
* source:
* https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript
*
* @return boolean indicating if text was successfully copied
*/
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea");
var textWasCopied = false;
//
// *** This styling is an extra step which is likely not required. ***
//
// Why is it here? To ensure:
// 1. the element is able to have focus and selection.
// 2. if element was to flash render it has minimal visual impact.
// 3. less flakyness with selection and copying which **might** occur if
// the textarea element is not visible.
//
// The likelihood is the element won't even render, not even a flash,
// so some of these are just precautions. However in IE the element
// is visible whilst the popup box asking the user for permission for
// the web page to copy to the clipboard.
//
// Place in top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textArea.style.width = '2em';
textArea.style.height = '2em';
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;
// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
// Avoid flash of white box if rendered for any reason.
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
textWasCopied = document.execCommand('copy');
} catch (err) {}
document.body.removeChild(textArea);
return textWasCopied;
}
function getAuthSsn(aut_id) {
var _result;
$.ajax({
url: App.apiUrl + 'authorization/'+aut_id,
type: "GET",
dataType: "json",
success: function(result) {
_result = result;//console.log(result);
},
error: function(result) {
console.log(result);
}
});
return _result;
}
function getAuthPerson(id) {
var _result;
$.ajax({
url: App.apiUrl + 'employee/'+id+'/id',
type: "GET",
success: function(result) {
_result = result;
App.person = result.data;
},
error: function(result) {
console.log(result);
}
});
return _result;
}
function parseDate(input) {
var parts = input.match(/(\d+)/g);
// note parts[1]-1
return new Date(parts[2], parts[1]-1, parts[0]);
}
/**
* IE11 support function, returns a Date object equal to new Date() (which in IE11 rejected the input format)
* @param {[string]} dateStr "2019-03-01 09:15" - returned from db
* @return {[Date]} Date object
*/
function parseDateIE(dateStr) {
var a=dateStr.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);
return date;
}
/**
* Safely get key value from object
*
* Checks if it's an object and that the key exists. If it does not exist, an empty string is returned.
*/
function value(object, key, emptyValue) {
emptyValue = emptyValue !== undefined ? emptyValue : '';
var isObject = object !== null && typeof object === 'object';
var value = isObject && (key in object) ? object[key] : emptyValue;
return value;
}
function getCategoryName(category) {
var categoryName = 'Okänd';
switch(category) {
case "0":
categoryName = 'Motion';
break;
case "1":
categoryName = 'Kultur';
break;
case "2":
categoryName = 'Massage';
break;
}
return categoryName;
}
function showAddToHomeScreen() {
if(isEmployee()) {
if(App.user.auth.auth_mode == 'employee') {
var item = '
';
}
};
function User()
{
this.init($.cookie('ahs_token'));
}
User.prototype.init = function(token)
{
this.token = token;
App.token = this.token;
if (this.token) {
this.auth = jwt_decode(this.token);
App.tokenProfile = this.auth;
}
}
User.prototype.isLoggedIn = function()
{
var loggedIn = false;
if ( this.token ) {
var now = Date.now()/1000;
if (this.auth.exp > now) {
loggedIn = true;
}
}
return loggedIn;
};
User.prototype.isProvider = function()
{
return this.authMode() == 'provider';
}
User.prototype.isEmployee = function()
{
return this.authMode() == 'employee';
}
User.prototype.isOtp = function()
{
return this.authMode() == 'otp';
}
User.prototype.authMode = function()
{
if ( this.isLoggedIn() ) {
return this.auth.auth_mode;
}
return null;
};
User.prototype.logout = function() {
$.removeCookie('ahs_token');
App.loggedIn=false;
if(this.auth) {
if(this.isProvider()) window.location.hash = "provider-login";
else if (this.isEmployee() || this.isOtp()) window.location.hash = "login";
else window.location.href = "logout-identification.php";
}
else {
if(App.portalActive) window.location.href = "#login";
else window.location.href = "#error";
}
};
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version v4.2.6+9869a4bc
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ES6Promise = factory());
}(this, (function () { 'use strict';
function objectOrFunction(x) {
var type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = void 0;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
}
var isArray = _isArray;
var len = 0;
var vertxNext = void 0;
var customSchedulerFn = void 0;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var vertx = Function('return this')().require('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = void 0;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
var callback = arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$1(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(2);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var TRY_CATCH_ERROR = { error: null };
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
TRY_CATCH_ERROR.error = error;
return TRY_CATCH_ERROR;
}
}
function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
try {
then$$1.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then$$1) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then$$1, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return resolve(promise, value);
}, function (reason) {
return reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$1) {
if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$1 === TRY_CATCH_ERROR) {
reject(promise, TRY_CATCH_ERROR.error);
TRY_CATCH_ERROR.error = null;
} else if (then$$1 === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$1)) {
handleForeignThenable(promise, maybeThenable, then$$1);
} else {
fulfill(promise, maybeThenable);
}
}
}
function resolve(promise, value) {
if (promise === value) {
reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = void 0,
callback = void 0,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = void 0,
error = void 0,
succeeded = void 0,
failed = void 0;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value.error = null;
} else {
succeeded = true;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
resolve(promise, value);
}, function rejectPromise(reason) {
reject(promise, reason);
});
} catch (e) {
reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function validationError() {
return new Error('Array Methods must be provided an Array');
}
var Enumerator = function () {
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
Enumerator.prototype._enumerate = function _enumerate(input) {
for (var i = 0; this._state === PENDING && i < input.length; i++) {
this._eachEntry(input[i], i);
}
};
Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
var c = this._instanceConstructor;
var resolve$$1 = c.resolve;
if (resolve$$1 === resolve$1) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise$2) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$1) {
return resolve$$1(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$1(entry), i);
}
};
Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
return Enumerator;
}();
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries) {
return new Enumerator(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {Function} resolver
Useful for tooling.
@constructor
*/
var Promise$2 = function () {
function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
Promise.prototype.catch = function _catch(onRejection) {
return this.then(null, onRejection);
};
/**
`finally` will be invoked regardless of the promise's fate just as native
try/catch/finally behaves
Synchronous example:
```js
findAuthor() {
if (Math.random() > 0.5) {
throw new Error();
}
return new Author();
}
try {
return findAuthor(); // succeed or fail
} catch(error) {
return findOtherAuther();
} finally {
// always runs
// doesn't affect the return value
}
```
Asynchronous example:
```js
findAuthor().catch(function(reason){
return findOtherAuther();
}).finally(function(){
// author was either found, or not
});
```
@method finally
@param {Function} callback
@return {Promise}
*/
Promise.prototype.finally = function _finally(callback) {
var promise = this;
var constructor = promise.constructor;
if (isFunction(callback)) {
return promise.then(function (value) {
return constructor.resolve(callback()).then(function () {
return value;
});
}, function (reason) {
return constructor.resolve(callback()).then(function () {
throw reason;
});
});
}
return promise.then(callback, callback);
};
return Promise;
}();
Promise$2.prototype.then = then;
Promise$2.all = all;
Promise$2.race = race;
Promise$2.resolve = resolve$1;
Promise$2.reject = reject$1;
Promise$2._setScheduler = setScheduler;
Promise$2._setAsap = setAsap;
Promise$2._asap = asap;
/*global self*/
function polyfill() {
var local = void 0;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise$2;
}
// Strange compat..
Promise$2.polyfill = polyfill;
Promise$2.Promise = Promise$2;
Promise$2.polyfill();
return Promise$2;
})));
//# sourceMappingURL=es6-promise.auto.map
function Help()
{
}
Help.prototype.init = function()
{
App.helpOverlay = new Overlay('#help');
$("#btn-help").on('click', function(e) {
$('#btn-help').addClass("toggle-overlay");
App.help.loadTemplateHelp();
App.helpOverlay.open();
$(".headbar-button").css('background-color', "");
// $("#btn-help").css('background-color', "#f4f4f4");
});
};
Help.prototype.loadTemplateHelp = function()
{
$( "#help-template" ).load( "resources/views/help-template.html", function() {
var template = kendo.template($("#overlayHelpTemplate").html());
var result = template({}); //Execute the template
$("#help-content").html(result); //Append the result
$.ajax({
url: App.helpUrl + "?l=sv&q="+App.helpQuery,
dataType:'html',
success: function(e) {
$("#help-container").html(e);
}
});
});
};
function kendoValidatorSettings() {
return {
messages: {
required: "Obligatorisk",
},
errorTemplate: '#=message#'
};
}
/**
* Get selected Kendo grid data item id
*/
function kendoGridGetSelectedId(grid)
{
var selected = grid.dataItem(grid.select());
var id = selected ? selected.id : null;
return id;
}
/**
* Select Kendo grid row with data item id
*/
function kendoGridSelect(grid, id)
{
var dataItem = grid.dataSource.get(id);
if (dataItem) grid.select("tr[data-uid=" + dataItem.uid + "]");
}
/**
* Get localization object for Kendo Upload
*
* Language Swedish
*/
function getKendoUploadLocalization()
{
return {
select: 'Välj...',
headerStatusUploading: "Laddar upp...",
headerStatusUploaded: "",
invalidFileExtension: "Filtypen tillåts inte",
invalidMaxFileSize: "Filen är för stor",
invalidMinFileSize: 'För liten filstorlek',
invalidFiles: 'Ogiltig fil',
dropFilesHere: 'Dra filer hit',
cancel: 'Avbryt',
remove: 'Ta bort',
retry: 'Försök igen',
statusFailed: 'Uppladdning misslyckades',
statusUploaded: 'Slutförd',
statusUploading: 'Laddar upp',
clearSelectedFiles: 'Rensa',
uploadSelectedFiles: 'Ladda upp',
};
}
var KendoHelper = {
createValidator: function(formSelector) {
var form = $(formSelector);
var validator = form.kendoValidator({
messages: {
required: "Obligatorisk.",
ssn: "Vänligen ange ett giltigt personnummer.",
checkbox_group: "Välj minst en",
email: "Vänligen ange en giltig e-postaddress.",
min: function(input) {
return "Minsta tillåtna värde är " + input[0].min + ".";
}
},
rules: {
ssn: function(input) {
valid = true;
if (input.data("validation") === "ssn") {
var required = input.prop('required');
var empty = (input.val() === "");
if (required || !empty) {
valid = validateSsn(input.val());
}
}
return valid;
},
sms: function(input) {
if (input.filter("[name=mobile]").length) {
var format = /^([+][0-9]{7,15}|)$/;
return format.test(input.val());
}
return true;
},
checkbox_group: function(input) {
valid = true;
if (input.data("validation") === "checkbox_group") {
var selected = [];
var form = $(input).closest('form');
var chks = $(form).find('div .checkbox_group').find(':checkbox');
$(chks).each(function() {
if ($(this).is(":checked")) {
selected.push($(this).attr('name'));
}
});
valid = selected.length > 0;
}
return valid;
},
},
errorTemplate: '
#=message#
',
validateInput: function(e) {
if (e.valid) e.input.removeClass("is-invalid");
else e.input.addClass("is-invalid");
}
}).data("kendoValidator");
return validator;
}
};
var Overlay = function(selector) {
// VARIABLES
var thisOverlay = $(selector);
var me = this;
var events = {
beforeOpen: [],
afterOpen: [],
beforeClose: [],
afterClose: [],
beforeToggle: [],
afterToggle: [],
};
var animationSpeed = 200;
var DEBUG = false;
// INIT
thisOverlay
.hide()
.addClass("overlay")
.prepend('');
// close overlay when clicking outside
/*$("body:not(.overlay-bound)")
.on("click", closeIfOutside)
.addClass("overlay-bound");
*/
thisOverlay.find("button.close-overlay").on("click", function () {
me.close();
});
// PUBLIC FUNCTIONS
/**
* Open overlay
*/
this.open = function() {
// hide all visible overlays but this one
close($(".overlay.visible").not(selector));
open(thisOverlay);
};
/**
* Close overlay
*/
this.close = function() {
return close(thisOverlay);
};
/**
* Toggle overlay
*/
this.toggle = function() {
if (!thisOverlay.is(":hidden")) return me.close();
else return me.open();
};
/**
* Add event
*
* @param string type
* Type of event. Can be before or after open/close/toggle. Written in the format "beforeOpen".
*
* @param function event
* The event function.
*/
this.addEvent = function(type, event) {
events[type].push(event);
$.data(thisOverlay[0], "events", events);
};
/**
* Add a button that controls the overlay
*
* @param string selector
* CSS selector for the button.
*
* @param string type
* Type of control: in what way the button should control the overlay. Can be open/close/toggle.
*/
this.addButton = function(selector, type) {
if (!type) type = "toggle";
var functions = {
open: me.open,
close: me.close,
toggle: me.toggle
};
var buttonFunc = functions[type];
$(selector)
.addClass("toggle-overlay")
.on("click", function() {
buttonFunc();
});
};
/**
* Check if overlay is open
*
* @return boolean
*/
this.isOpen = function() {
return (!thisOverlay.is(':hidden'));
};
// PRIVATE FUNCTIONS
function closeIfOutside(event) {
if ($(".overlay.visible").length) {
var target = $(event.target);
var overlayParent = target.closest('.overlay, .toggle-overlay').length;
var kendoOverlayParent = target.closest('.k-popup, .k-overlay, .k-dialog').length;
// it's "outside" if all of these apply:
// - it's not in an overlay or a button for toggling an overlay
// - it's not a kendo popup or overlay of some kind
// - it's in the dom
if ( !overlayParent && !kendoOverlayParent &&
$.contains(document.documentElement, event.target))
{
close($(".overlay.visible"));
}
}
}
function open(element) {
if (element.length) {
triggerEvent(element, "beforeToggle");
triggerEvent(element, "beforeOpen");
element.promise().done(function() {
if (element.is(':hidden')) {
if (DEBUG) console.log("open", element);
element
.addClass("visible")
.animate({width: 'toggle'}, animationSpeed)
.promise()
.done(function() {
triggerEvent(element, "afterOpen");
triggerEvent(element, "afterToggle");
});
}
});
}
return element.promise();
}
function close(element) {
if (element.length) {
triggerEvent(element, "beforeToggle");
triggerEvent(element, "beforeClose");
element.promise().done(function() {
if (!element.is(':hidden')) {
if (DEBUG) console.log("close", element);
element
.removeClass("visible")
.animate({width: 'toggle'}, animationSpeed)
.promise()
.done(function() {
triggerEvent(element, "afterClose");
triggerEvent(element, "afterToggle");
});
}
});
}
return element.promise();
}
function triggerEvent(element, type) {
var eventContainer = $.data(element[0], "events");
if (eventContainer) {
var eventList = eventContainer[type];
if (DEBUG && eventList.length) console.log(type, eventList);
for (var i = eventList.length - 1; i >= 0; i--) {
eventList[i]();
}
}
}
};
function Profile(email, role, language)
{
this.email = email;
this.role = role;
this.language = language;
this.i18nLang = "sv_FI";
this.messageLang = "sv-SE";
this.cultureLang = "se-FI";
console.log(role);
// Define different language parameters, since they differ from each other
if (language == "sv_FI") {
this.i18nLang = "sv_FI";
this.messageLang = "sv-SE";
this.cultureLang = "se-FI";
} else {
this.i18nLang = "fi_FI";
this.messageLang = "fi-FI";
this.cultureLang = "fi-FI";
}
}
Profile.prototype.init = function()
{
// Concatenate the path based on the defined language parameter
$.cachedScript( "resources/i18n/" + this.i18nLang + ".json" ).done(function( script, textStatus ) {
App.debug( this.i18nLang );
});
$.cachedScript( "https://webassets.consilia.fi/kendo/kendoui2018.3.911/js/messages/kendo.messages." + this.messageLang + ".min.js" ).done(function( script, textStatus ) {
App.debug( this.messageLang );
});
$.cachedScript( "https://webassets.consilia.fi/kendo/kendoui2018.3.911/js/cultures/kendo.culture." + this.cultureLang + ".min.js" ).done(function( script, textStatus ) {
App.debug( this.cultureLang );
});
kendo.culture(this.cultureLang);
App.debug("Profile: culture = " + kendo.getCulture().name);
var email = this.email;
$("#btn-profile").html(email);
App.profileOverlay = new Overlay('#profile');
$("#btn-profile").on('click', function(e) {
$('#btn-profile').addClass("toggle-overlay");
App.profile.loadTemplateProfile();
App.profileOverlay.open();
$(".headbar-button").css('background-color', "");
});
};
Profile.prototype.loadTemplateProfile = function()
{
var _profiledata = this;
$( "#profile-template" ).load( "resources/views/profile-template.html", function() {
var template = kendo.template($("#overlayProfileTemplate").html());
var result = template(_profiledata); //Execute the template
$("#profile-content").html(result); //Append the result
$("#btn-logout").on('click', _profiledata.logout);
});
};
Profile.prototype.logout = function() {
App.storage.clear();
$.removeCookie('ahs_token');
location.reload();
};
var Router = function() {
var Router = this;
this.router = new kendo.Router({
change: function(e) {
App.debug("route change: " + e.url);
$("body").html('');
},
routeMissing: function(e) {
App.debug("Route missing");
App.debug(e);
load('not-found', function(e){
App.Page = new Page();
});
}
});
this.navigate = function(routename) {
this.router.navigate(routename);
};
// ROUTES
// default page
this.router.route("/", function() {
// If auth, re-route to respective login page
if(typeof App !== "undefined" && typeof App.tokenProfile !== "undefined" && typeof App.tokenProfile.auth_mode !== "undefined") {
switch(App.tokenProfile.auth_mode) {
case 'otp':
case 'employee':
window.location.href = "#login";
break;
case 'transaction-create':
window.location.href = "#provider-login";
break;
// If unknown auth_mode, redir default
default:
window.location.href = "#login";
break;
}
}
// If not set auth_mode, redir default
else {
window.location.href = "#login";
}
});
this.router.route("login", function() {
if ( isEmployee() ) {
Router.router.replace('#employee');
}
else if ( isProvider() ) {
App.user.logout();
load('login');
}
else {
load('login');
}
});
this.router.route("error", function() {
load('error');
});
this.router.route("provider-login", function() {
if (isProvider()) {
Router.router.replace('#transaction-create');
}
else if( isEmployee()) {
App.user.logout();
load('provider-login');
}
else {
load('provider-login');
}
});
this.router.route("provider-application", function() {
load('provider-application');
});
this.router.route("transaction-create", function() {
if(isProvider()) {
load('transaction-create');
}
else if(isEmployee()) {
App.user.logout();
Router.router.replace('#provider-login');
}
else {
Router.router.replace('#provider-login');
}
});
this.router.route("provider-report", function() {
if(isProvider()) {
load('provider-report');
}
else if(isEmployee()) {
App.user.logout();
Router.router.replace('#provider-login');
}
else {
Router.router.replace('#provider-login');
}
});
this.router.route("transaction-correct", function() {
if(isProvider()) {
load('transaction-correct');
}
else if(isEmployee()) {
App.user.logout();
Router.router.replace('#provider-login');
}
else {
Router.router.replace('#provider-login');
}
});
this.router.route("transaction-create", function() {
if(isProvider()) {
load('transaction-create');
}
else if(isEmployee()) {
App.user.logout();
Router.router.replace('#provider-login');
}
else {
Router.router.replace('#provider-login');
}
});
this.router.route("me", function() {
if(isEmployee()) {
load('me');
}
else if(isProvider()) {
App.user.logout();
Router.router.replace('#login');
}
else {
Router.router.replace('#login');
}
});
this.router.route("profile", function() {
if(isProvider()) {
load('profile');
}
else if(isEmployee()) {
App.user.logout();
Router.router.replace('#provider-login');
}
else {
Router.router.replace('#provider-login');
}
});
this.router.route("error", function() {
load('error');
});
this.router.route("employee", function() {
if(isEmployee()) {
load('employee');
}
else if(isProvider()) {
App.user.logout();
Router.router.replace('#login');
}
else {
Router.router.replace('#login');
}
});
this.router.route("employee-transactions(/:category)", function(category) {
if(isEmployee()) {
if(typeof category !== null) {
App.selectedCategory = category;
}
load('employee-transactions');
}
else if(isProvider()) {
App.user.logout();
Router.router.replace('#login');
}
else {
Router.router.replace('#login');
}
});
this.router.route("employee-providers", function() {
if(isEmployee()) {
load('employee-providers');
}
else if(isProvider()) {
App.user.logout();
Router.router.replace('#login');
}
else {
Router.router.replace('#login');
}
});
this.router.start();
// PRIVATE FUNCTIONS
function load(filename, callback) {
filename = filename.replace("#", "");
var templatePromise = $.ajax({
url: App.rootUrl + "resources/template/page/" + filename + ".html",
type: "GET",
dataType: "html",
});
var scriptPromise = $.cachedScript("resources/js/page/" + filename + ".js");
$.when(templatePromise, scriptPromise)
.done(function(templateResults) {
App.Page = new Page(templateResults[0]);
})
.fail(function() {
$("body").html('error');
});
}
};
Router.prototype.loadRoutes = function() {
};