Javascript tools (div. functions)

Date: 2018-09-26
const $ = require('jquery');

let service = {};

function getRequestRandom() {
    return Math.floor(Math.random() * (10000000000000 + 1));
}

function loadScripts(uris, whenDone) {
    let wait = [];
    if (!uris.length)
        whenDone && whenDone();
    else {
        for (let i = uris.length; i--;) {
            let tag = document.createElement('script');
            tag.type = 'text/javascript';
            tag.src = uris[i];
            if (whenDone) {
                wait.push(tag);
                tag.onload = maybeDone;
                tag.onreadystatechange = maybeDone; // For IE8-
            }
            document.head.appendChild(tag);
        }
    }

    function maybeDone() {
        if (this.readyState === undefined || this.readyState === 'complete') {
            for (let i = wait.length; i--;)
                if (wait[i] == this)
                    wait.splice(i, 1);
            if (!wait.length)
                whenDone();
        }
    }
}

service.require = function(uris, whenDone) {
    // disable cache
    let i;
    for (i = 0; i < uris.length; i += 1) {
        uris[i] = uris[i] + '?_=' + getRequestRandom();
    }

    loadScripts(uris, whenDone);
};

service.getPrototypeName = function(obj) {
    let funcNameRegex = /function (.{1,})\(/;
    let results = (funcNameRegex).exec((obj).constructor.toString());
    return (results && results.length > 1) ? results[1] : '';
};

service.isFunction = function(functionToCheck) {
    let getType = {};
    return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
};
let isFunction = service.isFunction;

service.getWindowFromElement = function(element) {
    let $e = $(element);
    let e = $e[0];
    let doc = e.ownerDocument;
    let win = doc.defaultView || doc.parentWindow;
    return win;
};

service.del = function(obj, prop) {
    if (obj && obj[prop]) {
        if (obj[prop].unload && isFunction(obj[prop].unload)) {
            obj[prop].unload();
        }
        delete obj[prop];
    }
};

service.deleteObject = function(obj) {
    for (let member in obj)
        delete obj[member];
};

service.waitFor = function(condition, callback, interval) {
    interval = interval || 100;
    let isLoaded = condition();
    if (isLoaded) {
        callback();
    } else {
        setTimeout(function() {
            service.waitFor(condition, callback, interval);
        }, interval);
    }
};

service.supportsStorage = function() {
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
        return false;
    }
};

service.setLocal = function(key, obj) {
    if (service.supportsStorage()) {
        let item = obj;
        if (obj != null) {
            item = JSON.stringify(obj);
        }
        window.localStorage.setItem(key, item);
    }
};

service.getLocal = function(key) {
    if (service.supportsStorage()) {
        let item = window.localStorage.getItem(key);
        if (item) {
            return JSON.parse(item);
        }
    }
    return null;
};

service.limitOpacity = function(opacity) {
    if (opacity < 0.001)
        return 0.001;
    if (opacity > 0.999)
        return 1;
    return opacity;
};

service.isInternetExplorer = function() {
    return window.navigator.appVersion.indexOf('MSIE') != -1;
};

service.preventEvent = function(e) {
    e.preventDefault();
    return false;
};

service.format = function(str) {
    let i;
    for (i = 1; i < arguments.length; i++) {
        str = str.replace('{' + (i - 1) + '}', arguments[i]);
    }
    return str;
};

service.pad = function(number, length) {
    let str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
};

let pad = service.pad;

service.getTimeStr = function() {
    let time = new Date();
    return service.format('{0}:{1}:{2}.{3}', pad(time.getHours(), 2), pad(time.getMinutes(), 2), pad(time.getSeconds(), 2), pad(time.getMilliseconds(), 3));
};

let seen = [];
let jsonReplacer = function(key, val) {
    if (val != null && typeof val == 'object') {
        if (seen.indexOf(val) >= 0) {
            return;
        }
        seen.push(val);
    }
    return val;
};

service.toJson = function(obj) {
    try {
        return JSON.stringify(obj, jsonReplacer);
    } catch (e) {
        service.log(obj);
        service.log(e);
    }
};

let debug = false;
if (window && window.location && window.location.href && window.location.href.indexOf('debug=1') >= 0) {
    debug = true;
}
service.log = function() {
    if (!debug) return;
    let args = [].slice.call(arguments);
    let error = null;
    let i;
    for (i = 0; i < args.length; i += 1) {
        if (typeof args[i] === 'object') {
            try {
                if (args[i] instanceof Error) {
                    error = args[i];
                    console.warn(error.stack);
                } else {
                    args[i] = JSON.stringify(args[i]);
                }
            } catch (e) {
                // Could not convert to JSON
                args[i] = args[i].toString();
            }
        }
    }
    args.unshift(service.getTimeStr());
    console.info(args);
};

/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in
 * obj1
 *
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
service.mergeOptions = function(a, b) {
    let c = {},
        at;
    for (at in a) {
        c[at] = a[at];
    }
    for (at in b) {
        c[at] = b[at];
    }
    return c;
};

/*
 * function globalErrorHandler(message, url, lineNumber) { // save error and
 * send to server for example.
 *
 * if (!scriptDbg) { console.info('deactivate the global error handler to
 * see errors'); return true; }
 *
 * return false; }; window.addEventListener('error' //window.onerror =
 * globalErrorHandler;
 */

service.trimr = function(str, ch) {
    for (let i = str.length - 1; i >= 0; i--) {
        if (ch != str.charAt(i)) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
};

service.guid = function() {
    let d = new Date().getTime();
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        let r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
};

module.exports = service;

let service = {};
let tools = require('./tools');

service.sendTo = function(contentWindow, data) {
    setTimeout(() => {
        contentWindow.postMessage(tools.toJson(data), '*');
    }, 0);
};

service.sendToFrame = function(frame, data) {
    setTimeout(() => {
        frame.contentWindow.postMessage(tools.toJson(data), '*');
    }, 0);
};

service.sendToParent = function(data) {
    setTimeout(() => {
        window.parent.postMessage(tools.toJson(data), '*');
    }, 0);
};

service.receiveMessage = function(event, handler) {
    // event.origin, event.data, event.source
    let data = JSON.parse(event.data);
    handler(data, event, handler);
};

service.registerHandler = function(handler) {
    window.addEventListener('message', function(event) {
        service.receiveMessage(event, handler);
    }, false);
};

module.exports = service;

const $ = require('jquery');

let service = {};

// Helper functie die een nieuw html element aanmaakt en deze als jQuery
// object terug geeft
service.$new = function(type, parent, attributes, classNames) {
    let k, i;
    let el = document.createElement(type);
    if (attributes && attributes['type']) {
        el.type = attributes['type'];
    }

    $(parent).append(el);
    let jqEl = $(el);

    if (attributes) {
        for (k in attributes) {
            if (k !== 'type') {
                jqEl.attr(k, attributes[k]);
            }
        }
    }

    if (classNames && classNames instanceof Array) {
        for (i = 0; i < classNames.length; i += 1) {
            jqEl.addClass(classNames[i]);
        }
    }

    return jqEl;
};

service.$newCss = function(file, $head) {
    let $h = $('head');

    if ($head) {
        $h = $head;
    }

    let $e = service.$new('link', $h, {
        'rel': 'stylesheet',
        'type': 'text/css',
        'href': file
    });
    return $e;
};

service.$newJs = function(file, $head) {
    let $h = $('head');

    if ($head) {
        $h = $head;
    }

    let $e = service.$new('script', $h, {
        'type': 'text/javascript',
        'src': file
    });
    return $e;
};

service.$redraw = function($e) {
    return $e.hide(0, function() {
        $e.show(0);
    });
};

module.exports = service;

const tools = require('./tools');

let service = {};
let format = tools.format;
let pad = tools.pad;

service.parseDate = function(dateStr) {
	let dateRegex = /([0-9]*)-([0-9]*)-([0-9]*)T(.*)/gi;
	let match = dateRegex.exec(dateStr);
	if (match) {
		return new Date(parseInt(match[1]), parseInt(match[2]) -1, parseInt(match[3]));
	}
	return null;
};

service.getBirthdays = function(dateArr, dateProp) {
	let now = new Date();
	let nowYear = now.getFullYear();
	let nowDate = now.getDate();
	let nowMonth = now.getMonth();

	let result = [];

	dateArr.forEach(function(item) {
		let itemDate = item[dateProp];
		let date = itemDate.getDate();
		let month = itemDate.getMonth();
		let year = itemDate.getFullYear();

		let birthDay = null;
		let birthDayYear = null;

		if (month < nowMonth || (month == nowMonth && date < nowDate)) {
			birthDayYear = nowYear+1;
		} else {
			birthDayYear = nowYear;
		}
		birthDay = new Date(birthDayYear, month, date);

		let row = {};
		row.birthDay = birthDay;
		row.birthDayAge = birthDayYear - year;
		row.timeToBirthDay = birthDay.valueOf() - now.valueOf();
		row.data = item;
		result.push(row);
	});

	result.sort(function(a, b) {
		return a.timeToBirthDay - b.timeToBirthDay;
	});

	return result;
};

service.formatDate = function(date, format) {
	let dstr = format;
	dstr = dstr.replace('yyyy', date.getFullYear());
	dstr = dstr.replace('yy', pad(date.getYear(), 2));
	dstr = dstr.replace('y', date.getYear());

	dstr = dstr.replace('MM', pad(date.getMonth(), 2));
	dstr = dstr.replace('M', date.getMonth());

	dstr = dstr.replace('dd', pad(date.getDate(), 2));
	dstr.replace('d', date.getDate());

	dstr = dstr.replace('HH', pad(date.getHours(), 2));
	dstr = dstr.replace('H', date.getHours());

	dstr = dstr.replace('hh', pad(date.getHours() % 12, 2));
	dstr = dstr.replace('h', date.getHours() % 12);

	dstr = dstr.replace('mm', pad(date.getMinutes(), 2));
	dstr = dstr.replace('m', date.getMinutes());

	dstr = dstr.replace('ss', pad(date.getSeconds(), 2));
	dstr = dstr.replace('s', date.getSeconds());

	dstr = dstr.replace('fff', pad(date.getMilliseconds(), 3));
	return dstr;
};

service.datesEqual = function(a, b) {
	return a.getDate() === b.getDate() && a.getMonth() === b.getMonth() && a.getFullYear() === b.getFullYear();
};

service.isToday = function(date) {
	if (date && date.getFullYear) {
		return service.datesEqual(new Date(), date);
	}
	return false;
};

service.minToHour = function(min) {
	return min * (100 / 60) / 100;
};

service.hourToMin = function(hour) {
	return (hour / (100 / 60)) * 100;
};

let to_min = (100 / 60) / 100;
let to_sec = (100 / 60) / 10000;
service.getTimeNumber = function(date) {
	if (date && date.getHours) {
		return date.getHours() + (date.getMinutes() * to_min) + (date.getSeconds() * to_sec);
	}
	return 0;
};

service.dateToStr = function(time) {
	return format('{0}-{1}-{2} {3}:{4}', pad(time.getFullYear(), 4), pad(time.getMonth(), 2), pad(time.getDate(), 2), time.getHours(), pad(time
			.getMinutes(), 2));
};

service.getWeek = function(date) {
	let onejan = new Date(date.getFullYear(), 0, 1);
	return Math.ceil((((date - onejan) / 86400000) + onejan.getDay() + 1) / 7);
};

service.dayNames = [ 'zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag' ];
service.monthNamesFull = [ 'januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december' ];
service.monthNames = [ 'jan', 'feb', 'mrt', 'april', 'mei', 'juni', 'juli', 'aug', 'sept', 'okt', 'nov', 'dec' ];
let monthNames = service.monthNames;

service.shortDateStr = function(date) {
	if (date && date.getFullYear) {
		return format('{1}  {0}', monthNames[date.getMonth()], pad(date.getDate(), 2));
	}
};

service.dateToString = function(date) {
	if (date && date.getFullYear) {
		return format('{0}-{1}-{2}  {3}:{4}:{5}', pad(date.getFullYear(), 4), pad(date.getMonth() + 1, 2), pad(date.getDate(), 2), pad(date.getHours(), 2),
				pad(date.getMinutes(), 2), pad(date.getSeconds(), 2));
	}
	return '';
};

service.addDays = function(date, days) {
	let result = new Date(date);
	result.setDate(date.getDate() + days);
	return result;
};
let addDays = service.addDays;

service.isWorkingDay = function(date) {
	let weekDay = date.getDay();
	return !(weekDay == 0 || weekDay == 6);
};
let isWorkingDay = service.isWorkingDay;

service.addWorkingDays = function(date, days) {
	let result = new Date(date);
	let step = 1;
	if (days < 0)
		step = -1;

	let cnt = Math.abs(days);
	while (cnt > 0) {
		result = addDays(result, step);
		if (isWorkingDay(result)) {
			cnt--;
		}
	}
	return result;
};

service.getTimeAsSeconds = function getTimeAsSeconds(date) {
	if (date && date.getHours) {
		return (date.getHours() * 3600) + (date.getMinutes() * 60) + date.getSeconds();
	}
	return null;
};

module.exports = service;


let service = {};
let tools = require('./tools');

service.sendTo = function(contentWindow, data) {
    setTimeout(() => {
        contentWindow.postMessage(tools.toJson(data), '*');
    }, 0);
};

service.sendToFrame = function(frame, data) {
    setTimeout(() => {
        frame.contentWindow.postMessage(tools.toJson(data), '*');
    }, 0);
};

service.sendToParent = function(data) {
    setTimeout(() => {
        window.parent.postMessage(tools.toJson(data), '*');
    }, 0);
};

service.receiveMessage = function(event, handler) {
    // event.origin, event.data, event.source
    let data = JSON.parse(event.data);
    handler(data, event, handler);
};

service.registerHandler = function(handler) {
    window.addEventListener('message', function(event) {
        service.receiveMessage(event, handler);
    }, false);
};

module.exports = service;
const $ = require('jquery');

let service = {};

// Helper functie die een nieuw html element aanmaakt en deze als jQuery
// object terug geeft
service.$new = function(type, parent, attributes, classNames) {
    let k, i;
    let el = document.createElement(type);
    if (attributes && attributes['type']) {
        el.type = attributes['type'];
    }

    $(parent).append(el);
    let jqEl = $(el);

    if (attributes) {
        for (k in attributes) {
            if (k !== 'type') {
                jqEl.attr(k, attributes[k]);
            }
        }
    }

    if (classNames && classNames instanceof Array) {
        for (i = 0; i < classNames.length; i += 1) {
            jqEl.addClass(classNames[i]);
        }
    }

    return jqEl;
};

service.$newCss = function(file, $head) {
    let $h = $('head');

    if ($head) {
        $h = $head;
    }

    let $e = service.$new('link', $h, {
        'rel': 'stylesheet',
        'type': 'text/css',
        'href': file
    });
    return $e;
};

service.$newJs = function(file, $head) {
    let $h = $('head');

    if ($head) {
        $h = $head;
    }

    let $e = service.$new('script', $h, {
        'type': 'text/javascript',
        'src': file
    });
    return $e;
};

service.$redraw = function($e) {
    return $e.hide(0, function() {
        $e.show(0);
    });
};

module.exports = service;
const tools = require('./tools');

let service = {};
let format = tools.format;
let pad = tools.pad;

service.parseDate = function(dateStr) {
	let dateRegex = /([0-9]*)-([0-9]*)-([0-9]*)T(.*)/gi;
	let match = dateRegex.exec(dateStr);
	if (match) {
		return new Date(parseInt(match[1]), parseInt(match[2]) -1, parseInt(match[3]));
	}
	return null;
};

service.getBirthdays = function(dateArr, dateProp) {
	let now = new Date();
	let nowYear = now.getFullYear();
	let nowDate = now.getDate();
	let nowMonth = now.getMonth();

	let result = [];

	dateArr.forEach(function(item) {
		let itemDate = item[dateProp];
		let date = itemDate.getDate();
		let month = itemDate.getMonth();
		let year = itemDate.getFullYear();

		let birthDay = null;
		let birthDayYear = null;

		if (month < nowMonth || (month == nowMonth && date < nowDate)) {
			birthDayYear = nowYear+1;
		} else {
			birthDayYear = nowYear;
		}
		birthDay = new Date(birthDayYear, month, date);

		let row = {};
		row.birthDay = birthDay;
		row.birthDayAge = birthDayYear - year;
		row.timeToBirthDay = birthDay.valueOf() - now.valueOf();
		row.data = item;
		result.push(row);
	});

	result.sort(function(a, b) {
		return a.timeToBirthDay - b.timeToBirthDay;
	});

	return result;
};

service.formatDate = function(date, format) {
	let dstr = format;
	dstr = dstr.replace('yyyy', date.getFullYear());
	dstr = dstr.replace('yy', pad(date.getYear(), 2));
	dstr = dstr.replace('y', date.getYear());

	dstr = dstr.replace('MM', pad(date.getMonth(), 2));
	dstr = dstr.replace('M', date.getMonth());

	dstr = dstr.replace('dd', pad(date.getDate(), 2));
	dstr.replace('d', date.getDate());

	dstr = dstr.replace('HH', pad(date.getHours(), 2));
	dstr = dstr.replace('H', date.getHours());

	dstr = dstr.replace('hh', pad(date.getHours() % 12, 2));
	dstr = dstr.replace('h', date.getHours() % 12);

	dstr = dstr.replace('mm', pad(date.getMinutes(), 2));
	dstr = dstr.replace('m', date.getMinutes());

	dstr = dstr.replace('ss', pad(date.getSeconds(), 2));
	dstr = dstr.replace('s', date.getSeconds());

	dstr = dstr.replace('fff', pad(date.getMilliseconds(), 3));
	return dstr;
};

service.datesEqual = function(a, b) {
	return a.getDate() === b.getDate() && a.getMonth() === b.getMonth() && a.getFullYear() === b.getFullYear();
};

service.isToday = function(date) {
	if (date && date.getFullYear) {
		return service.datesEqual(new Date(), date);
	}
	return false;
};

service.minToHour = function(min) {
	return min * (100 / 60) / 100;
};

service.hourToMin = function(hour) {
	return (hour / (100 / 60)) * 100;
};

let to_min = (100 / 60) / 100;
let to_sec = (100 / 60) / 10000;
service.getTimeNumber = function(date) {
	if (date && date.getHours) {
		return date.getHours() + (date.getMinutes() * to_min) + (date.getSeconds() * to_sec);
	}
	return 0;
};

service.dateToStr = function(time) {
	return format('{0}-{1}-{2} {3}:{4}', pad(time.getFullYear(), 4), pad(time.getMonth(), 2), pad(time.getDate(), 2), time.getHours(), pad(time
			.getMinutes(), 2));
};

service.getWeek = function(date) {
	let onejan = new Date(date.getFullYear(), 0, 1);
	return Math.ceil((((date - onejan) / 86400000) + onejan.getDay() + 1) / 7);
};

service.dayNames = [ 'zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag' ];
service.monthNamesFull = [ 'januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december' ];
service.monthNames = [ 'jan', 'feb', 'mrt', 'april', 'mei', 'juni', 'juli', 'aug', 'sept', 'okt', 'nov', 'dec' ];
let monthNames = service.monthNames;

service.shortDateStr = function(date) {
	if (date && date.getFullYear) {
		return format('{1}  {0}', monthNames[date.getMonth()], pad(date.getDate(), 2));
	}
};

service.dateToString = function(date) {
	if (date && date.getFullYear) {
		return format('{0}-{1}-{2}  {3}:{4}:{5}', pad(date.getFullYear(), 4), pad(date.getMonth() + 1, 2), pad(date.getDate(), 2), pad(date.getHours(), 2),
				pad(date.getMinutes(), 2), pad(date.getSeconds(), 2));
	}
	return '';
};

service.addDays = function(date, days) {
	let result = new Date(date);
	result.setDate(date.getDate() + days);
	return result;
};
let addDays = service.addDays;

service.isWorkingDay = function(date) {
	let weekDay = date.getDay();
	return !(weekDay == 0 || weekDay == 6);
};
let isWorkingDay = service.isWorkingDay;

service.addWorkingDays = function(date, days) {
	let result = new Date(date);
	let step = 1;
	if (days < 0)
		step = -1;

	let cnt = Math.abs(days);
	while (cnt > 0) {
		result = addDays(result, step);
		if (isWorkingDay(result)) {
			cnt--;
		}
	}
	return result;
};

service.getTimeAsSeconds = function getTimeAsSeconds(date) {
	if (date && date.getHours) {
		return (date.getHours() * 3600) + (date.getMinutes() * 60) + date.getSeconds();
	}
	return null;
};

module.exports = service;
14040cookie-checkJavascript tools (div. functions)