(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
        typeof define === 'function' && define.amd ? define(['exports'], factory) :
            (global = global || self, factory(global.IF = {}));
}(this, (function (exports) { 'use strict';

    // Orig: https://github.com/ElliotNB/observable-slim
    // Fork: https://github.com/aheadware/observable-slim

    /*
	 * 	Observable Slim
	 *	Version 0.1.5
	 * 	https://github.com/elliotnb/observable-slim
	 *
	 * 	Licensed under the MIT license:
	 * 	http://www.opensource.org/licenses/MIT
	 *
	 *	Observable Slim is a singleton that allows you to observe changes made to an object and any nested
	 *	children of that object. It is intended to assist with one-way data binding, that is, in MVC parlance,
	 *	reflecting changes in the model to the view. Observable Slim aspires to be as lightweight and easily
	 *	understood as possible. Minifies down to roughly 3000 characters.
	 */
    const ObservableSlim = (function() {
        // An array that stores all of the observables created through the public create() method below.
        var observables = [];
        // An array of all the objects that we have assigned Proxies to
        var targets = [];

        // An array of arrays containing the Proxies created for each target object. targetsProxy is index-matched with
        // 'targets' -- together, the pair offer a Hash table where the key is not a string nor number, but the actual target object
        var targetsProxy = [];

        // this variable tracks duplicate proxies assigned to the same target.
        // the 'set' handler below will trigger the same change on all other Proxies tracking the same target.
        // however, in order to avoid an infinite loop of Proxies triggering and re-triggering one another, we use dupProxy
        // to track that a given Proxy was modified from the 'set' handler
        var dupProxy = null;

        var _getProperty = function(obj, path) {
            return path.split('.').reduce(function(prev, curr) {
                return prev ? prev[curr] : undefined
            }, obj || self)
        };

        /*	Function: _create
	                Private internal function that is invoked to create a new ES6 Proxy whose changes we can observe through
	                the Observerable.observe() method.

	            Parameters:
	                target 				- required, plain JavaScript object that we want to observe for changes.
	                domDelay 			- batch up changes on a 10ms delay so a series of changes can be processed in one DOM update.
	                originalObservable 	- object, the original observable created by the user, exists for recursion purposes,
	                                      allows one observable to observe change on any nested/child objects.
	                originalPath 		- array of objects, each object having the properties 'target' and 'property' -- target referring to the observed object itself
	                                      and property referring to the name of that object in the nested structure. the path of the property in relation to the target
	                                      on the original observable, exists for recursion purposes, allows one observable to observe change on any nested/child objects.

	            Returns:
	                An ES6 Proxy object.
	    */
        var _create = function(target, domDelay, originalObservable, originalPath) {

            var observable = originalObservable || null;

            // record the nested path taken to access this object -- if there was no path then we provide the first empty entry
            var path = originalPath || [{"target":target,"property":""}];

            // in order to accurately report the "previous value" of the "length" property on an Array
            // we must use a helper property because intercepting a length change is not always possible as of 8/13/2018 in
            // Chrome -- the new `length` value is already set by the time the `set` handler is invoked
            if (target instanceof Array) target.__length = target.length;

            var changes = [];

            /*	Function: _getPath
	                Returns a string of the nested path (in relation to the top-level observed object)
	                of the property being modified or deleted.
	            Parameters:
	                target - the object whose property is being modified or deleted.
	                property - the string name of the property
	                jsonPointer - optional, set to true if the string path should be formatted as a JSON pointer.

	            Returns:
	                String of the nested path (e.g., hello.testing.1.bar or, if JSON pointer, /hello/testing/1/bar
	        */
            var _getPath = function(target, property, jsonPointer) {

                var fullPath = "";
                var lastTarget = null;

                // loop over each item in the path and append it to full path
                for (var i = 0; i < path.length; i++) {

                    // if the current object was a member of an array, it's possible that the array was at one point
                    // mutated and would cause the position of the current object in that array to change. we perform an indexOf
                    // lookup here to determine the current position of that object in the array before we add it to fullPath
                    if (lastTarget instanceof Array && !isNaN(path[i].property)) {
                        path[i].property = lastTarget.indexOf(path[i].target);
                    }

                    fullPath = fullPath + "." + path[i].property;
                    lastTarget = path[i].target;
                }

                // add the current property
                fullPath = fullPath + "." + property;

                // remove the beginning two dots -- ..foo.bar becomes foo.bar (the first item in the nested chain doesn't have a property name)
                fullPath = fullPath.substring(2);

                if (jsonPointer === true) fullPath = "/" + fullPath.replace(/\./g, "/");

                return fullPath;
            };

            var _notifyObservers = function(numChanges) {

                // if the observable is paused, then we don't want to execute any of the observer functions
                if (observable.paused === true) return;

                // execute observer functions on a 10ms settimeout, this prevents the observer functions from being executed
                // separately on every change -- this is necessary because the observer functions will often trigger UI updates
                if (domDelay === true) {
                    setTimeout(function() {
                        if (numChanges === changes.length) {

                            // we create a copy of changes before passing it to the observer functions because even if the observer function
                            // throws an error, we still need to ensure that changes is reset to an empty array so that old changes don't persist
                            var changesCopy = changes.slice(0);
                            changes = [];

                            // invoke any functions that are observing changes
                            for (var i = 0; i < observable.observers.length; i++) observable.observers[i](changesCopy);

                        }
                    },10);
                } else {

                    // we create a copy of changes before passing it to the observer functions because even if the observer function
                    // throws an error, we still need to ensure that changes is reset to an empty array so that old changes don't persist
                    var changesCopy = changes.slice(0);
                    changes = [];

                    // invoke any functions that are observing changes
                    for (var i = 0; i < observable.observers.length; i++) observable.observers[i](changesCopy);

                }
            };

            var handler = {
                get: function(target, property) {

                    // implement a simple check for whether or not the object is a proxy, this helps the .create() method avoid
                    // creating Proxies of Proxies.
                    if (property === "__getTarget") {
                        return target;
                    } else if (property === "__isProxy") {
                        return true;
                        // from the perspective of a given observable on a parent object, return the parent object of the given nested object
                    } else if (property === "__getParent") {
                        return function(i) {
                            if (typeof i === "undefined") var i = 1;
                            var parentPath = _getPath(target, "__getParent").split(".");
                            parentPath.splice(-(i+1),(i+1));
                            return _getProperty(observable.parentProxy, parentPath.join("."));
                        }
                        // return the full path of the current object relative to the parent observable
                    } else if (property === "__getPath") {
                        // strip off the 12 characters for ".__getParent"
                        var parentPath = _getPath(target, "__getParent");
                        return parentPath.slice(0, -12);
                        // added unique id to target
                    } else if (property === "__uid" ) {
                        return target.__uid;
                    }

                    // for performance improvements, we assign this to a variable so we do not have to lookup the property value again
                    var targetProp = target[property];
                    if (target instanceof Date && targetProp instanceof Function && targetProp !== null) {
                        return targetProp.bind(target);
                    }

                    // if we are traversing into a new object, then we want to record path to that object and return a new observable.
                    // recursively returning a new observable allows us a single Observable.observe() to monitor all changes on
                    // the target object and any objects nested within.
                    if (targetProp instanceof Object && targetProp !== null && target.hasOwnProperty(property)) {

                        // if we've found a proxy nested on the object, then we want to retrieve the original object behind that proxy
                        if (targetProp.__isProxy === true) targetProp = targetProp.__getTarget;

                        // if the object accessed by the user (targetProp) already has a __targetPosition AND the object
                        // stored at target[targetProp.__targetPosition] is not null, then that means we are already observing this object
                        // we might be able to return a proxy that we've already created for the object
                        if (targetProp.__targetPosition > -1 && targets[targetProp.__targetPosition] !== null) {

                            // loop over the proxies that we've created for this object
                            var ttp = targetsProxy[targetProp.__targetPosition];
                            for (var i = 0, l = ttp.length; i < l; i++) {

                                // if we find a proxy that was setup for this particular observable, then return that proxy
                                if (observable === ttp[i].observable) {
                                    return ttp[i].proxy;
                                }
                            }
                        }

                        // if we're arrived here, then that means there is no proxy for the object the user just accessed, so we
                        // have to create a new proxy for it

                        // create a shallow copy of the path array -- if we didn't create a shallow copy then all nested objects would share the same path array and the path wouldn't be accurate
                        var newPath = path.slice(0);
                        newPath.push({"target":targetProp,"property":property});
                        return _create(targetProp, domDelay, observable, newPath);
                    } else {
                        return targetProp;
                    }
                },
                deleteProperty: function(target, property) {

                    // was this change an original change or was it a change that was re-triggered below
                    var originalChange = true;
                    if (dupProxy === proxy) {
                        originalChange = false;
                        dupProxy = null;
                    }

                    // in order to report what the previous value was, we must make a copy of it before it is deleted
                    var previousValue = Object.assign({}, target);

                    // record the deletion that just took place
                    changes.push({
                        "type":"delete"
                        ,"target":target
                        ,"property":property
                        ,"newValue":null
                        ,"previousValue":previousValue[property]
                        ,"currentPath":_getPath(target, property)
                        ,"jsonPointer":_getPath(target, property, true)
                        ,"proxy":proxy
                    });

                    if (originalChange === true) {

                        // perform the delete that we've trapped if changes are not paused for this observable
                        if (!observable.changesPaused) delete target[property];

                        for (var a = 0, l = targets.length; a < l; a++) if (target === targets[a]) break;

                        // loop over each proxy and see if the target for this change has any other proxies
                        var currentTargetProxy = targetsProxy[a] || [];

                        var b = currentTargetProxy.length;
                        while (b--) {
                            // if the same target has a different proxy
                            if (currentTargetProxy[b].proxy !== proxy) {
                                // !!IMPORTANT!! store the proxy as a duplicate proxy (dupProxy) -- this will adjust the behavior above appropriately (that is,
                                // prevent a change on dupProxy from re-triggering the same change on other proxies)
                                dupProxy = currentTargetProxy[b].proxy;

                                // make the same delete on the different proxy for the same target object. it is important that we make this change *after* we invoke the same change
                                // on any other proxies so that the previousValue can show up correct for the other proxies
                                delete currentTargetProxy[b].proxy[property];
                            }
                        }

                    }

                    _notifyObservers(changes.length);

                    return true;

                },
                set: function(target, property, value, receiver) {

                    // if the value we're assigning is an object, then we want to ensure
                    // that we're assigning the original object, not the proxy, in order to avoid mixing
                    // the actual targets and proxies -- creates issues with path logging if we don't do this
                    if (value && value.__isProxy) value = value.__getTarget;

                    // was this change an original change or was it a change that was re-triggered below
                    var originalChange = true;
                    if (dupProxy === proxy) {
                        originalChange = false;
                        dupProxy = null;
                    }

                    // improve performance by saving direct references to the property
                    var targetProp = target[property];

                    // Only record this change if:
                    // 	1. the new value differs from the old one
                    //	2. OR if this proxy was not the original proxy to receive the change
                    // 	3. OR the modified target is an array and the modified property is "length" and our helper property __length indicates that the array length has changed
                    //
                    // Regarding #3 above: mutations of arrays via .push or .splice actually modify the .length before the set handler is invoked
                    // so in order to accurately report the correct previousValue for the .length, we have to use a helper property.
                    if (targetProp !== value || originalChange === false || (property === "length" && target instanceof Array && target.__length !== value)) {

                        var foundObservable = true;

                        var typeOfTargetProp = (typeof targetProp);

                        // determine if we're adding something new or modifying somethat that already existed
                        var type = "update";
                        if (typeOfTargetProp === "undefined") type = "add";

                        // store the change that just occurred. it is important that we store the change before invoking the other proxies so that the previousValue is correct
                        changes.push({
                            "type":type
                            ,"target":target
                            ,"property":property
                            ,"newValue":value
                            ,"previousValue":receiver[property]
                            ,"currentPath":_getPath(target, property)
                            ,"jsonPointer":_getPath(target, property, true)
                            ,"proxy":proxy
                        });

                        // mutations of arrays via .push or .splice actually modify the .length before the set handler is invoked
                        // so in order to accurately report the correct previousValue for the .length, we have to use a helper property.
                        if (property === "length" && target instanceof Array && target.__length !== value) {
                            changes[changes.length-1].previousValue = target.__length;
                            target.__length = value;
                        }

                        // !!IMPORTANT!! if this proxy was the first proxy to receive the change, then we need to go check and see
                        // if there are other proxies for the same project. if there are, then we will modify those proxies as well so the other
                        // observers can be modified of the change that has occurred.
                        if (originalChange === true) {

                            // because the value actually differs than the previous value
                            // we need to store the new value on the original target object,
                            // but only as long as changes have not been paused
                            if (!observable.changesPaused) target[property] = value;


                            foundObservable = false;

                            var targetPosition = target.__targetPosition;
                            var z = targetsProxy[targetPosition].length;

                            // find the parent target for this observable -- if the target for that observable has not been removed
                            // from the targets array, then that means the observable is still active and we should notify the observers of this change
                            while (z--) {
                                if (observable === targetsProxy[targetPosition][z].observable) {
                                    if (targets[targetsProxy[targetPosition][z].observable.parentTarget.__targetPosition] !== null) {
                                        foundObservable = true;
                                        break;
                                    }
                                }
                            }

                            // if we didn't find an observable for this proxy, then that means .remove(proxy) was likely invoked
                            // so we no longer need to notify any observer function about the changes, but we still need to update the
                            // value of the underlying original objectm see below: target[property] = value;
                            if (foundObservable) {

                                // loop over each proxy and see if the target for this change has any other proxies
                                var currentTargetProxy = targetsProxy[targetPosition];
                                for (var b = 0, l = currentTargetProxy.length; b < l; b++) {
                                    // if the same target has a different proxy
                                    if (currentTargetProxy[b].proxy !== proxy) {

                                        // !!IMPORTANT!! store the proxy as a duplicate proxy (dupProxy) -- this will adjust the behavior above appropriately (that is,
                                        // prevent a change on dupProxy from re-triggering the same change on other proxies)
                                        dupProxy = currentTargetProxy[b].proxy;

                                        // invoke the same change on the different proxy for the same target object. it is important that we make this change *after* we invoke the same change
                                        // on any other proxies so that the previousValue can show up correct for the other proxies
                                        currentTargetProxy[b].proxy[property] = value;

                                    }
                                }

                                // if the property being overwritten is an object, then that means this observable
                                // will need to stop monitoring this object and any nested objects underneath the overwritten object else they'll become
                                // orphaned and grow memory usage. we excute this on a setTimeout so that the clean-up process does not block
                                // the UI rendering -- there's no need to execute the clean up immediately
                                setTimeout(function() {

                                    if (typeOfTargetProp === "object" && targetProp !== null) {

                                        // check if the to-be-overwritten target property still exists on the target object
                                        // if it does still exist on the object, then we don't want to stop observing it. this resolves
                                        // an issue where array .sort() triggers objects to be overwritten, but instead of being overwritten
                                        // and discarded, they are shuffled to a new position in the array
                                        var keys = Object.keys(target);
                                        for (var i = 0, l = keys.length; i < l; i++) {
                                            if (target[keys[i]] === targetProp) return;
                                        }

                                        var stillExists = false;

                                        // now we perform the more expensive search recursively through the target object.
                                        // if we find the targetProp (that was just overwritten) still exists somewhere else
                                        // further down in the object, then we still need to observe the targetProp on this observable.
                                        (function iterate(target) {
                                            var keys = Object.keys(target);
                                            for (var i = 0, l = keys.length; i < l; i++) {

                                                var property = keys[i];
                                                var nestedTarget = target[property];

                                                if (nestedTarget instanceof Object && nestedTarget !== null) iterate(nestedTarget);
                                                if (nestedTarget === targetProp) {
                                                    stillExists = true;
                                                    return;
                                                }
                                            }                                    })(target);

                                        // even though targetProp was overwritten, if it still exists somewhere else on the object,
                                        // then we don't want to remove the observable for that object (targetProp)
                                        if (stillExists === true) return;

                                        // loop over each property and recursively invoke the `iterate` function for any
                                        // objects nested on targetProp
                                        (function iterate(obj) {

                                            var keys = Object.keys(obj);
                                            for (var i = 0, l = keys.length; i < l; i++) {
                                                var objProp = obj[keys[i]];
                                                if (objProp instanceof Object && objProp !== null) iterate(objProp);
                                            }

                                            // if there are any existing target objects (objects that we're already observing)...
                                            var c = -1;
                                            for (var i = 0, l = targets.length; i < l; i++) {
                                                if (obj === targets[i]) {
                                                    c = i;
                                                    break;
                                                }
                                            }
                                            if (c > -1) {

                                                // ...then we want to determine if the observables for that object match our current observable
                                                var currentTargetProxy = targetsProxy[c];
                                                var d = currentTargetProxy.length;

                                                while (d--) {
                                                    // if we do have an observable monitoring the object thats about to be overwritten
                                                    // then we can remove that observable from the target object
                                                    if (observable === currentTargetProxy[d].observable) {
                                                        currentTargetProxy.splice(d,1);
                                                        break;
                                                    }
                                                }

                                                // if there are no more observables assigned to the target object, then we can remove
                                                // the target object altogether. this is necessary to prevent growing memory consumption particularly with large data sets
                                                if (currentTargetProxy.length == 0) {
                                                    // targetsProxy.splice(c,1);
                                                    targets[c] = null;
                                                }
                                            }

                                        })(targetProp);
                                    }
                                },10000);
                            }

                            // TO DO: the next block of app resolves test case #29, but it results in poor IE11 performance with very large objects.
                            // UPDATE: need to re-evaluate IE11 performance due to major performance overhaul from 12/23/2018.
                            //
                            // if the value we've just set is an object, then we'll need to iterate over it in order to initialize the
                            // observers/proxies on all nested children of the object
                            /* if (value instanceof Object && value !== null) {
	                            (function iterate(proxy) {
	                                var target = proxy.__getTarget;
	                                var keys = Object.keys(target);
	                                for (var i = 0, l = keys.length; i < l; i++) {
	                                    var property = keys[i];
	                                    if (target[property] instanceof Object && target[property] !== null) iterate(proxy[property]);
	                                };
	                            })(proxy[property]);
	                        }; */

                        }
                        if (foundObservable) {
                            // notify the observer functions that the target has been modified
                            _notifyObservers(changes.length);
                        }

                    }
                    return true;
                }
            };

            var __targetPosition = target.__targetPosition;
            if (!(__targetPosition > -1)) {
                Object.defineProperty(target, "__targetPosition", {
                    value: targets.length
                    ,writable: false
                    ,enumerable: false
                    ,configurable: false
                });
            }

            // create the proxy that we'll use to observe any changes
            var proxy = new Proxy(target, handler);

            // we don't want to create a new observable if this function was invoked recursively
            if (observable === null) {
                observable = {"parentTarget":target, "domDelay":domDelay, "parentProxy":proxy, "observers":[],"paused":false,"path":path,"changesPaused":false};
                observables.push(observable);
            }

            // store the proxy we've created so it isn't re-created unnecessairly via get handler
            var proxyItem = {"target":target,"proxy":proxy,"observable":observable};

            // if we have already created a Proxy for this target object then we add it to the corresponding array
            // on targetsProxy (targets and targetsProxy work together as a Hash table indexed by the actual target object).
            if (__targetPosition > -1) {

                // the targets array is set to null for the position of this particular object, then we know that
                // the observable was removed some point in time for this object -- so we need to set the reference again
                if (targets[__targetPosition] === null) {
                    targets[__targetPosition] = target;
                }

                targetsProxy[__targetPosition].push(proxyItem);

                // else this is a target object that we had not yet created a Proxy for, so we must add it to targets,
                // and push a new array on to targetsProxy containing the new Proxy
            } else {
                targets.push(target);
                targetsProxy.push([proxyItem]);
            }

            return proxy;
        };

        return {
            /*	Method:
	                Public method that is invoked to create a new ES6 Proxy whose changes we can observe
	                through the Observerable.observe() method.

	            Parameters
	                target - Object, required, plain JavaScript object that we want to observe for changes.
	                domDelay - Boolean, required, if true, then batch up changes on a 10ms delay so a series of changes can be processed in one DOM update.
	                observer - Function, optional, will be invoked when a change is made to the proxy.
	                uuuid - String, Unique ID (optional)

	            Returns:
	                An ES6 Proxy object.
	        */
            create: function(target, domDelay, observer, uuid) {

                // test if the target is a Proxy, if it is then we need to retrieve the original object behind the Proxy.
                // we do not allow creating proxies of proxies because -- given the recursive design of ObservableSlim -- it would lead to sharp increases in memory usage
                if (target.__isProxy === true) {
                    var target = target.__getTarget;
                    //if it is, then we should throw an error. we do not allow creating proxies of proxies
                    // because -- given the recursive design of ObservableSlim -- it would lead to sharp increases in memory usage
                    //throw new Error("ObservableSlim.create() cannot create a Proxy for a target object that is also a Proxy.");
                }

                if ( uuid ) {
                    target.__uid = uuid;
                }

                // fire off the _create() method -- it will create a new observable and proxy and return the proxy
                var proxy = _create(target, domDelay);

                // assign the observer function
                if (typeof observer === "function") this.observe(proxy, observer);

                // recursively loop over all nested objects on the proxy we've just created
                // this will allow the top observable to observe any changes that occur on a nested object
                (function iterate(proxy) {
                    var target = proxy.__getTarget;
                    var keys  = Object.keys(target);
                    for (var i = 0, l = keys.length; i < l; i++) {
                        var property = keys[i];
                        if (target[property] instanceof Object && target[property] !== null) iterate(proxy[property]);
                    }
                })(proxy);

                return proxy;

            },

            /*	Method: observe
	                This method is used to add a new observer function to an existing proxy.

	            Parameters:
	                proxy 	- the ES6 Proxy returned by the create() method. We want to observe changes made to this object.
	                observer 	- this function will be invoked when a change is made to the observable (not to be confused with the
	                              observer defined in the create() method).

	            Returns:
	                Nothing.
	        */
            observe: function(proxy, observer) {
                // loop over all the observables created by the _create() function
                var i = observables.length;
                while (i--) {
                    if (observables[i].parentProxy === proxy) {
                        observables[i].observers.push(observer);
                        break;
                    }
                }        },

            /*	Method: pause
	                This method will prevent any observer functions from being invoked when a change occurs to a proxy.

	            Parameters:
	                proxy 	- the ES6 Proxy returned by the create() method.
	        */
            pause: function(proxy) {
                var i = observables.length;
                var foundMatch = false;
                while (i--) {
                    if (observables[i].parentProxy === proxy) {
                        observables[i].paused = true;
                        foundMatch = true;
                        break;
                    }
                }
                if (foundMatch == false) throw new Error("ObseravableSlim could not pause observable -- matching proxy not found.");
            },

            /*	Method: resume
	                This method will resume execution of any observer functions when a change is made to a proxy.

	            Parameters:
	                proxy 	- the ES6 Proxy returned by the create() method.
	        */
            resume: function(proxy) {
                var i = observables.length;
                var foundMatch = false;
                while (i--) {
                    if (observables[i].parentProxy === proxy) {
                        observables[i].paused = false;
                        foundMatch = true;
                        break;
                    }
                }
                if (foundMatch == false) throw new Error("ObseravableSlim could not resume observable -- matching proxy not found.");
            },

            /*	Method: pauseChanges
	                This method will prevent any changes (i.e., set, and deleteProperty) from being written to the target
	                object.  However, the observer functions will still be invoked to let you know what changes WOULD have
	                been made.  This can be useful if the changes need to be approved by an external source before the
	                changes take effect.

	            Parameters:
	                proxy	- the ES6 Proxy returned by the create() method.
	         */
            pauseChanges: function(proxy){
                var i = observables.length;
                var foundMatch = false;
                while (i--) {
                    if (observables[i].parentProxy === proxy) {
                        observables[i].changesPaused = true;
                        foundMatch = true;
                        break;
                    }
                }
                if (foundMatch == false) throw new Error("ObseravableSlim could not pause changes on observable -- matching proxy not found.");
            },

            /*	Method: resumeChanges
	                This method will resume the changes that were taking place prior to the call to pauseChanges().

	            Parameters:
	                proxy	- the ES6 Proxy returned by the create() method.
	         */
            resumeChanges: function(proxy){
                var i = observables.length;
                var foundMatch = false;
                while (i--) {
                    if (observables[i].parentProxy === proxy) {
                        observables[i].changesPaused = false;
                        foundMatch = true;
                        break;
                    }
                }
                if (foundMatch == false) throw new Error("ObseravableSlim could not resume changes on observable -- matching proxy not found.");
            },

            /*	Method: remove
	                This method will remove the observable and proxy thereby preventing any further callback observers for
	                changes occuring to the target object.

	            Parameters:
	                proxy 	- the ES6 Proxy returned by the create() method.
	        */
            remove: function(proxy) {

                var matchedObservable = null;
                var foundMatch = false;

                var c = observables.length;
                while (c--) {
                    if (observables[c].parentProxy === proxy) {
                        matchedObservable = observables[c];
                        foundMatch = true;
                        break;
                    }
                }
                var a = targetsProxy.length;
                while (a--) {
                    var b = targetsProxy[a].length;
                    while (b--) {
                        if (targetsProxy[a][b].observable === matchedObservable) {
                            targetsProxy[a].splice(b,1);

                            // if there are no more proxies for this target object
                            // then we null out the position for this object on the targets array
                            // since we are essentially no longer observing this object.
                            // we do not splice it off the targets array, because if we re-observe the same
                            // object at a later time, the property __targetPosition cannot be redefined.
                            if (targetsProxy[a].length === 0) {
                                targets[a] = null;
                            }                    }
                    }            }
                if (foundMatch === true) {
                    observables.splice(c,1);
                }
            }
        };
    })();

    // Export in a try catch to prevent this from erroring out on older browsers
    try { module.exports = ObservableSlim; } catch (err) {}

    function ED() {}

    Object.assign( ED.prototype, {

        addEventListener: function ( type, listener ) {

            if ( this._listeners === undefined ) this._listeners = {};

            var listeners = this._listeners;

            if ( listeners[ type ] === undefined ) {

                listeners[ type ] = [];

            }

            if ( listeners[ type ].indexOf( listener ) === - 1 ) {

                listeners[ type ].push( listener );

            }

        },

        hasEventListener: function ( type, listener ) {

            if ( this._listeners === undefined ) return false;

            var listeners = this._listeners;

            return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;

        },

        removeEventListener: function ( type, listener ) {

            if ( this._listeners === undefined ) return;

            var listeners = this._listeners;
            var listenerArray = listeners[ type ];

            if ( listenerArray !== undefined ) {

                var index = listenerArray.indexOf( listener );

                if ( index !== - 1 ) {

                    listenerArray.splice( index, 1 );

                }

            }

        },

        removeAllEventListener : function( type ) {

            if ( this._listeners === undefined ) return;

            var listeners = this._listeners;
            if ( listeners[ type ] !== undefined )
            {
                listeners[ type ] = [];
            }

        },


        dispatchEvent: function ( event ) {

            if ( this._listeners === undefined ) return;

            var listeners = this._listeners;
            var listenerArray = listeners[ event.type ];

            if ( listenerArray !== undefined ) {

                event.target = this;

                var array = listenerArray.slice( 0 );

                for ( var i = 0, l = array.length; i < l; i ++ ) {

                    array[ i ].call( this, event );

                }

            }

        }

    } );

    const GlobalEventDispatcher = new ED();

    function Xhr( props = {} )
    {
        const defaultConfig = {
            headers : [],
            withCredentials : false,
            responseType : 'text',
            defaultErrorHandler : null
        };

        this.config = Object.assign( defaultConfig, props );
    }

    // Inheritance
    // none

    // Proto properties
    Xhr.prototype.get = function( url, onResult, async = true )
    {
        this.call( url, {}, onResult, async, 'GET' );
    };

    Xhr.prototype.post = function( url, data = {}, onResult, async = true )
    {
        this.call( url, data, onResult, async, 'POST' );
    };

    Xhr.prototype.call = function( url, data = null, onResult, async = true, method = 'GET' )
    {
        let request = new XMLHttpRequest();


        request.onload = function()
        {
            let response = null;
            if ( request.status >= 200 && request.status < 400 )
            {
                if ( !request.responseType || request.responseType === 'text' )
                {
                    response = request.responseText;
                }
                else if ( request.responseType === "document" )
                {
                    response = request.responseXML;
                }
                else
                {
                    response = request.response;
                }

                onResult && onResult( null, response );
            }
            else
            {
                this.handleError( onResult );
            }

        }.bind( this );

        request.onabort = function()
        {
            this.handleError( 500, onResult );
        }.bind( this );

        request.onerror = function()
        {
            this.handleError( 500, onResult );
        }.bind( this );

        request.open( method.toUpperCase(), url, async );

        // Configure request
        for( var hi = 0; hi < this.config.headers.length; hi++ )
        {
            request.setRequestHeader( this.config.headers[ hi ].key, this.config.headers[ hi ].value );
        }
        request.withCredentials = this.config.withCredentials;
        request.responseType = this.config.responseType;

        request.send( data );

        return request;
    };

    Xhr.prototype.addHeader = function( key, value )
    {
        this.config.headers.push(
            { key : key, value : value }
        );
    };

    Xhr.prototype.handleError = function( onResult, cbError = null )
    {
        if ( onResult )
        {
            onResult( 500 );
        }
        else if ( this.config.defaultErorrHandler )
        {
            this.config.defaultErorrHandler( 500 );
        }
        else
        {
            //
            console.log( "XHR Error: " + 500 );
        }
    };

    function Params(params  = {} )
    {
        this.__params = params;
    }

    Params.prototype.has = function(key )
    {
        return ( this.__params.hasOwnProperty( key ) );
    };

    Params.prototype.get = function(key, defaultValue = null )
    {
        if ( this.has( key ) )
        {
            return this.__params[ key ];
        }
        else
        {
            return defaultValue;
        }
    };

    Params.prototype.getAll = function()
    {
        return this.__params;
    };

    function ItbRpcResponse( err, res = {} )
    {
        this.error = err ? 'http_error' : null;
        this.result = res.hasOwnProperty( 'result' ) ? new Params( res.result ) : new Params( {} );
        this.code = 200;

        if ( null === this.error && res.hasOwnProperty( 'code' ) && res.code !== 200 )
        {
            this.code = res.code;
            this.error = ( res.hasOwnProperty( 'error' ) && res.error !== null ) ? res.error : 'unknown_error';
        }
    }

    ItbRpcResponse.prototype.hasError = function()
    {
        return ( null !== this.error );
    };

    ItbRpcResponse.prototype.getError = function()
    {
        return this.error;
    };

    ItbRpcResponse.prototype.get = function( paramName )
    {
        return this.result.get( paramName );
    };

    function ItbRpcClient(config = {} )
    {
        const defaultConfig = {
            endpoint : '/rpc',
            itbToken : null
        };
        this.config = Object.assign( defaultConfig, config );

        this.headers = [
            { key : "Content-Type" , value : "application/json" },
            { key : "itb-token", value : this.config.itbToken }
        ];
    }

    ItbRpcClient.prototype.setToken = function(token )
    {
        this.itbToken = token;
        for ( let hi = 0; hi < this.headers.length; hi++ )
        {
            if ( 'itb-token' === this.headers[ hi ].key )
            {
                this.headers[ hi ].value = this.itbToken;
                break;
            }
        }
    };

    ItbRpcClient.prototype.call = function(name, params = {}, onResult, additionalHeaders = null )
    {

        const headers = JSON.parse( JSON.stringify( this.headers ) );

        if ( additionalHeaders )
        {
            let newHeaderKey;
            for ( let hk in additionalHeaders )
            {
                newHeaderKey = false;
                for ( let hi = 0; hi < headers.length; hi++ )
                {
                    if ( headers[ hi ].key === hk )
                    {
                        headers[ hi ].value = additionalHeaders[ hk ];
                        newHeaderKey = true;
                        break;
                    }
                }
                if ( false === newHeaderKey )
                {
                    headers.push(
                        {
                            key : hk,
                            value : additionalHeaders[ hk ]
                        }
                    );
                }
            }
        }

        const xhr = new Xhr( { headers : headers } ),
            cbOnResult = onResult,
            body = {};

        body.rpcName = name;
        body.rpcParams = params;

        xhr.post(
            this.config.endpoint,
            JSON.stringify( body ),
            function( err, result )
            {
                try
                {
                    result = JSON.parse( result );
                }
                catch( e )  { }

                let itbRpcRes = new ItbRpcResponse( err, result );
                cbOnResult( itbRpcRes );
            }
        );
    };

    /**
     * https://github.com/cho45/micro-template.js
     * (c) cho45 http://cho45.github.com/mit-license
     */
    function template (id, data) {
        var me = template;
        if (!me.cache[id]) me.cache[id] = (function () {
            var name = id, string = /^[\w\-]+$/.test(id) ? me.get(id): (name = 'template(string)', id); // no warnings
            var line = 1, body = (
                "try { " +
                (me.variable ?  "var " + me.variable + " = this.stash;" : "with (this.stash) { ") +
                "this.ret += '"  +
                string.
                replace(/<%/g, '\x11').replace(/%>/g, '\x13'). // if you want other tag, just edit this line
                    replace(/'(?![^\x11\x13]+?\x13)/g, '\\x27').
                replace(/^\s*|\s*$/g, '').
                replace(/\n|\r\n/g, function () { return "';\nthis.line = " + (++line) + "; this.ret += '\\n" }).
                replace(/\x11=raw(.+?)\x13/g, "' + ($1) + '").
                replace(/\x11=nl2br(.+?)\x13/g, "' + this.nl2br($1) + '").
                replace(/\x11=(.+?)\x13/g, "' + this.escapeHTML($1) + '").
                replace(/\x11(.+?)\x13/g, "'; $1; this.ret += '") +
                "'; " + (me.variable ? "" : "}") + "return this.ret;" +
                "} catch (e) { throw 'TemplateError: ' + e + ' (on " + name + "' + ' line ' + this.line + ')'; } " +
                "//@ sourceURL=" + name + "\n" // source map
            ).replace(/this\.ret \+= '';/g, '');
            var func = new Function(body);
            var map  = { '&' : '&amp;', '<' : '&lt;', '>' : '&gt;', '\x22' : '&#x22;', '\x27' : '&#x27;' };
            var escapeHTML = function (string) { return (''+string).replace(/[&<>\'\"]/g, function (_) { return map[_] }) };
            var nl2br = function(string) { return escapeHTML(string).replace(/(?:\ r\n|\r|\n)/g, '<br>')};
            return function (stash) { return func.call(me.context = { escapeHTML: escapeHTML, nl2br : nl2br, line: 1, ret : '', stash: stash }) };
        })();
        return data ? me.cache[id](data) : me.cache[id];
    }
    template.cache = {};
    template.get = function (id) { return document.querySelector( '[data-if-tmpl-id="' + id + '"]' ).innerHTML };

    /**
     * Extended template function:
     *   requires: basic template() function
     *   provides:
     *     include(id)
     *     wrapper(id, function () {})
     */
    function extended (id, data) {
        var fun = function (data) {
            data.include = function (name, args) {
                var stash = {};
                for (var key in template.context.stash) if (template.context.stash.hasOwnProperty(key)) {
                    stash[key] = template.context.stash[key];
                }
                if (args) for (var key in args) if (args.hasOwnProperty(key)) {
                    stash[key] = args[key];
                }
                var context = template.context;
                context.ret += template(name, stash);
                template.context = context;
            };

            data.wrapper = function (name, fun) {
                var current = template.context.ret;
                template.context.ret = '';
                fun.apply(template.context);
                var content = template.context.ret;
                var orig_content = template.context.stash.content;
                template.context.stash.content = content;
                template.context.ret = current + template(name, template.context.stash);
                template.context.stash.content = orig_content;
            };

            return template(id, data);
        };

        return data ? fun(data) : fun;
    }

    template.get = function (id) {
        var fun = extended.get;
        return fun ? fun(id) : document.querySelector( '[data-if-tmpl-id="' + id + '"]' ).innerHTML;
    };

    var tg = template;

    function applyBodyToObject( coreObj, body )
    {
        if ( "object" !== typeof coreObj )
        {
            throw new Error( 'CoreObj is not of type object.' );
        }

        if ( body && "object" === typeof body )
        {
            for ( let k in body )
            {
                if ( "function" === typeof body[ k ] )
                {
                    //coreObj[ k ] = body[ k ].bind( coreObj );
                    coreObj[ k ] = body[ k ];
                }
                else
                {
                    coreObj[ k ] = JSON.parse( JSON.stringify( body[ k ] ) );
                }
            }
        }

        return coreObj;
    }

    var DOCUMENT_NODE_TYPE = 9;

    /**
     * A polyfill for Element.matches()
     */
    if (typeof Element !== 'undefined' && !Element.prototype.matches) {
        var proto = Element.prototype;

        proto.matches = proto.matchesSelector ||
            proto.mozMatchesSelector ||
            proto.msMatchesSelector ||
            proto.oMatchesSelector ||
            proto.webkitMatchesSelector;
    }

    /**
     * Finds the closest parent that matches a selector.
     *
     * @param {Element} element
     * @param {String} selector
     * @return {Function}
     */
    function closest (element, selector) {
        while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {
            if (typeof element.matches === 'function' &&
                element.matches(selector)) {
                return element;
            }
            element = element.parentNode;
        }
    }

    /**
     * Delegates event to a selector.
     *
     * @param {Element} element
     * @param {String} selector
     * @param {String} type
     * @param {Function} callback
     * @param {Boolean} useCapture
     * @return {Object}
     */
    function _delegate(element, selector, type, callback, useCapture) {
        var listenerFn = listener.apply(this, arguments);

        element.addEventListener(type, listenerFn, useCapture);

        return {
            destroy: function() {
                element.removeEventListener(type, listenerFn, useCapture);
            }
        }
    }

    /**
     * Delegates event to a selector.
     *
     * @param {Element|String|Array} [elements]
     * @param {String} selector
     * @param {String} type
     * @param {Function} callback
     * @param {Boolean} useCapture
     * @return {Object}
     */
    function delegate(elements, selector, type, callback, useCapture) {
        // Handle the regular Element usage
        if (typeof elements.addEventListener === 'function') {
            return _delegate.apply(null, arguments);
        }

        // Handle Element-less usage, it defaults to global delegation
        if (typeof type === 'function') {
            // Use `document` as the first parameter, then apply arguments
            // This is a short way to .unshift `arguments` without running into deoptimizations
            return _delegate.bind(null, document).apply(null, arguments);
        }

        // Handle Selector-based usage
        if (typeof elements === 'string') {
            elements = document.querySelectorAll(elements);
        }

        // Handle Array-like based usage
        return Array.prototype.map.call(elements, function (element) {
            return _delegate(element, selector, type, callback, useCapture);
        });
    }

    /**
     * Finds closest match and invokes callback.
     *
     * @param {Element} element
     * @param {String} selector
     * @param {String} type
     * @param {Function} callback
     * @return {Function}
     */
    function listener(element, selector, type, callback) {
        return function(e) {
            e.delegateTarget = closest(e.target, selector);

            if (e.delegateTarget) {
                callback.call(element, e);
            }
        }
    }

    const trim = (function ()
    {

        function escapeRegex(string)
        {
            return string.replace(/[\[\](){}?*+\^$\\.|\-]/g, "\\$&");
        }

        return function trim(str, characters, flags)
        {
            characters = characters || " ";
            flags = flags || "g";
            if (typeof str !== "string" || typeof characters !== "string" || typeof flags !== "string")
            {
                throw new TypeError("argument must be string");
            }

            if (!/^[gi]*$/.test(flags))
            {
                throw new TypeError("Invalid flags supplied '" + flags.match(new RegExp("[^gi]*")) + "'");
            }

            characters = escapeRegex(characters);

            return str.replace(new RegExp("^[" + characters + "]+|[" + characters + "]+$", flags), '');
        };
    }());

    function nf( number, precision = 2, locale = null )
    {
        let loc = ( locale === null ) ? window.navigator.language : locale;
        return new Intl.NumberFormat(
            loc,
            {
                useGrouping : true,
                minimumFractionDigits : precision,
                maximumFractionDigits : precision
            }
        ).format( number );
    }

    var template$1 = tg;

    function createParams( obj = {} )
    {
        return new Params( obj );
    }

    // Generated by CoffeeScript 1.10.0

    function UP() {
        var slice = [].slice;
        var P, UrlPattern, astNodeContainsSegmentsForProvidedParams, astNodeToNames, astNodeToRegexString, baseAstNodeToRegexString, concatMap, defaultOptions, escapeForRegex, getParam, keysAndValuesToObject, newParser, regexGroupCount, stringConcatMap, stringify;
        escapeForRegex = function(string) {
            return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
        };
        concatMap = function(array, f) {
            var i, length, results;
            results = [];
            i = -1;
            length = array.length;
            while (++i < length) {
                results = results.concat(f(array[i]));
            }
            return results;
        };
        stringConcatMap = function(array, f) {
            var i, length, result;
            result = '';
            i = -1;
            length = array.length;
            while (++i < length) {
                result += f(array[i]);
            }
            return result;
        };
        regexGroupCount = function(regex) {
            return (new RegExp(regex.toString() + '|')).exec('').length - 1;
        };
        keysAndValuesToObject = function(keys, values) {
            var i, key, length, object, value;
            object = {};
            i = -1;
            length = keys.length;
            while (++i < length) {
                key = keys[i];
                value = values[i];
                if (value == null) {
                    continue;
                }
                if (object[key] != null) {
                    if (!Array.isArray(object[key])) {
                        object[key] = [object[key]];
                    }
                    object[key].push(value);
                } else {
                    object[key] = value;
                }
            }
            return object;
        };
        P = {};
        P.Result = function(value, rest) {
            this.value = value;
            this.rest = rest;
        };
        P.Tagged = function(tag, value) {
            this.tag = tag;
            this.value = value;
        };
        P.tag = function(tag, parser) {
            return function(input) {
                var result, tagged;
                result = parser(input);
                if (result == null) {
                    return;
                }
                tagged = new P.Tagged(tag, result.value);
                return new P.Result(tagged, result.rest);
            };
        };
        P.regex = function(regex) {
            return function(input) {
                var matches, result;
                matches = regex.exec(input);
                if (matches == null) {
                    return;
                }
                result = matches[0];
                return new P.Result(result, input.slice(result.length));
            };
        };
        P.sequence = function() {
            var parsers;
            parsers = 1 <= arguments.length ? slice.call(arguments, 0) : [];
            return function(input) {
                var i, length, parser, rest, result, values;
                i = -1;
                length = parsers.length;
                values = [];
                rest = input;
                while (++i < length) {
                    parser = parsers[i];
                    result = parser(rest);
                    if (result == null) {
                        return;
                    }
                    values.push(result.value);
                    rest = result.rest;
                }
                return new P.Result(values, rest);
            };
        };
        P.pick = function() {
            var indexes, parsers;
            indexes = arguments[0], parsers = 2 <= arguments.length ? slice.call(arguments, 1) : [];
            return function(input) {
                var array, result;
                result = P.sequence.apply(P, parsers)(input);
                if (result == null) {
                    return;
                }
                array = result.value;
                result.value = array[indexes];
                return result;
            };
        };
        P.string = function(string) {
            var length;
            length = string.length;
            return function(input) {
                if (input.slice(0, length) === string) {
                    return new P.Result(string, input.slice(length));
                }
            };
        };
        P.lazy = function(fn) {
            var cached;
            cached = null;
            return function(input) {
                if (cached == null) {
                    cached = fn();
                }
                return cached(input);
            };
        };
        P.baseMany = function(parser, end, stringResult, atLeastOneResultRequired, input) {
            var endResult, parserResult, rest, results;
            rest = input;
            results = stringResult ? '' : [];
            while (true) {
                if (end != null) {
                    endResult = end(rest);
                    if (endResult != null) {
                        break;
                    }
                }
                parserResult = parser(rest);
                if (parserResult == null) {
                    break;
                }
                if (stringResult) {
                    results += parserResult.value;
                } else {
                    results.push(parserResult.value);
                }
                rest = parserResult.rest;
            }
            if (atLeastOneResultRequired && results.length === 0) {
                return;
            }
            return new P.Result(results, rest);
        };
        P.many1 = function(parser) {
            return function(input) {
                return P.baseMany(parser, null, false, true, input);
            };
        };
        P.concatMany1Till = function(parser, end) {
            return function(input) {
                return P.baseMany(parser, end, true, true, input);
            };
        };
        P.firstChoice = function() {
            var parsers;
            parsers = 1 <= arguments.length ? slice.call(arguments, 0) : [];
            return function(input) {
                var i, length, parser, result;
                i = -1;
                length = parsers.length;
                while (++i < length) {
                    parser = parsers[i];
                    result = parser(input);
                    if (result != null) {
                        return result;
                    }
                }
            };
        };
        newParser = function(options) {
            var U;
            U = {};
            U.wildcard = P.tag('wildcard', P.string(options.wildcardChar));
            U.optional = P.tag('optional', P.pick(1, P.string(options.optionalSegmentStartChar), P.lazy(function() {
                return U.pattern;
            }), P.string(options.optionalSegmentEndChar)));
            U.name = P.regex(new RegExp("^[" + options.segmentNameCharset + "]+"));
            U.named = P.tag('named', P.pick(1, P.string(options.segmentNameStartChar), P.lazy(function() {
                return U.name;
            })));
            U.escapedChar = P.pick(1, P.string(options.escapeChar), P.regex(/^./));
            U["static"] = P.tag('static', P.concatMany1Till(P.firstChoice(P.lazy(function() {
                return U.escapedChar;
            }), P.regex(/^./)), P.firstChoice(P.string(options.segmentNameStartChar), P.string(options.optionalSegmentStartChar), P.string(options.optionalSegmentEndChar), U.wildcard)));
            U.token = P.lazy(function() {
                return P.firstChoice(U.wildcard, U.optional, U.named, U["static"]);
            });
            U.pattern = P.many1(P.lazy(function() {
                return U.token;
            }));
            return U;
        };
        defaultOptions = {
            escapeChar: '\\',
            segmentNameStartChar: ':',
            segmentValueCharset: 'a-zA-Z0-9-_~ %',
            segmentNameCharset: 'a-zA-Z0-9',
            optionalSegmentStartChar: '(',
            optionalSegmentEndChar: ')',
            wildcardChar: '*'
        };
        baseAstNodeToRegexString = function(astNode, segmentValueCharset) {
            if (Array.isArray(astNode)) {
                return stringConcatMap(astNode, function(node) {
                    return baseAstNodeToRegexString(node, segmentValueCharset);
                });
            }
            switch (astNode.tag) {
                case 'wildcard':
                    return '(.*?)';
                case 'named':
                    return "([" + segmentValueCharset + "]+)";
                case 'static':
                    return escapeForRegex(astNode.value);
                case 'optional':
                    return '(?:' + baseAstNodeToRegexString(astNode.value, segmentValueCharset) + ')?';
            }
        };
        astNodeToRegexString = function(astNode, segmentValueCharset) {
            if (segmentValueCharset == null) {
                segmentValueCharset = defaultOptions.segmentValueCharset;
            }
            return '^' + baseAstNodeToRegexString(astNode, segmentValueCharset) + '$';
        };
        astNodeToNames = function(astNode) {
            if (Array.isArray(astNode)) {
                return concatMap(astNode, astNodeToNames);
            }
            switch (astNode.tag) {
                case 'wildcard':
                    return ['_'];
                case 'named':
                    return [astNode.value];
                case 'static':
                    return [];
                case 'optional':
                    return astNodeToNames(astNode.value);
            }
        };
        getParam = function(params, key, nextIndexes, sideEffects) {
            var index, maxIndex, result, value;
            if (sideEffects == null) {
                sideEffects = false;
            }
            value = params[key];
            if (value == null) {
                if (sideEffects) {
                    throw new Error("no values provided for key `" + key + "`");
                } else {
                    return;
                }
            }
            index = nextIndexes[key] || 0;
            maxIndex = Array.isArray(value) ? value.length - 1 : 0;
            if (index > maxIndex) {
                if (sideEffects) {
                    throw new Error("too few values provided for key `" + key + "`");
                } else {
                    return;
                }
            }
            result = Array.isArray(value) ? value[index] : value;
            if (sideEffects) {
                nextIndexes[key] = index + 1;
            }
            return result;
        };
        astNodeContainsSegmentsForProvidedParams = function(astNode, params, nextIndexes) {
            var i, length;
            if (Array.isArray(astNode)) {
                i = -1;
                length = astNode.length;
                while (++i < length) {
                    if (astNodeContainsSegmentsForProvidedParams(astNode[i], params, nextIndexes)) {
                        return true;
                    }
                }
                return false;
            }
            switch (astNode.tag) {
                case 'wildcard':
                    return getParam(params, '_', nextIndexes, false) != null;
                case 'named':
                    return getParam(params, astNode.value, nextIndexes, false) != null;
                case 'static':
                    return false;
                case 'optional':
                    return astNodeContainsSegmentsForProvidedParams(astNode.value, params, nextIndexes);
            }
        };
        stringify = function(astNode, params, nextIndexes) {
            if (Array.isArray(astNode)) {
                return stringConcatMap(astNode, function(node) {
                    return stringify(node, params, nextIndexes);
                });
            }
            switch (astNode.tag) {
                case 'wildcard':
                    return getParam(params, '_', nextIndexes, true);
                case 'named':
                    return getParam(params, astNode.value, nextIndexes, true);
                case 'static':
                    return astNode.value;
                case 'optional':
                    if (astNodeContainsSegmentsForProvidedParams(astNode.value, params, nextIndexes)) {
                        return stringify(astNode.value, params, nextIndexes);
                    } else {
                        return '';
                    }
            }
        };
        UrlPattern = function(arg1, arg2) {
            var groupCount, options, parsed, parser, withoutWhitespace;
            if (arg1 instanceof UrlPattern) {
                this.isRegex = arg1.isRegex;
                this.regex = arg1.regex;
                this.ast = arg1.ast;
                this.names = arg1.names;
                return;
            }
            this.isRegex = arg1 instanceof RegExp;
            if (!(('string' === typeof arg1) || this.isRegex)) {
                throw new TypeError('argument must be a regex or a string');
            }
            if (this.isRegex) {
                this.regex = arg1;
                if (arg2 != null) {
                    if (!Array.isArray(arg2)) {
                        throw new Error('if first argument is a regex the second argument may be an array of group names but you provided something else');
                    }
                    groupCount = regexGroupCount(this.regex);
                    if (arg2.length !== groupCount) {
                        throw new Error("regex contains " + groupCount + " groups but array of group names contains " + arg2.length);
                    }
                    this.names = arg2;
                }
                return;
            }
            if (arg1 === '') {
                throw new Error('argument must not be the empty string');
            }
            withoutWhitespace = arg1.replace(/\s+/g, '');
            if (withoutWhitespace !== arg1) {
                throw new Error('argument must not contain whitespace');
            }
            options = {
                escapeChar: (arg2 != null ? arg2.escapeChar : void 0) || defaultOptions.escapeChar,
                segmentNameStartChar: (arg2 != null ? arg2.segmentNameStartChar : void 0) || defaultOptions.segmentNameStartChar,
                segmentNameCharset: (arg2 != null ? arg2.segmentNameCharset : void 0) || defaultOptions.segmentNameCharset,
                segmentValueCharset: (arg2 != null ? arg2.segmentValueCharset : void 0) || defaultOptions.segmentValueCharset,
                optionalSegmentStartChar: (arg2 != null ? arg2.optionalSegmentStartChar : void 0) || defaultOptions.optionalSegmentStartChar,
                optionalSegmentEndChar: (arg2 != null ? arg2.optionalSegmentEndChar : void 0) || defaultOptions.optionalSegmentEndChar,
                wildcardChar: (arg2 != null ? arg2.wildcardChar : void 0) || defaultOptions.wildcardChar
            };
            parser = newParser(options);
            parsed = parser.pattern(arg1);
            if (parsed == null) {
                throw new Error("couldn't parse pattern");
            }
            if (parsed.rest !== '') {
                throw new Error("could only partially parse pattern");
            }
            this.ast = parsed.value;
            this.regex = new RegExp(astNodeToRegexString(this.ast, options.segmentValueCharset));
            this.names = astNodeToNames(this.ast);
        };
        UrlPattern.prototype.match = function(url) {
            var groups, match;
            match = this.regex.exec(url);
            if (match == null) {
                return null;
            }
            groups = match.slice(1);
            if (this.names) {
                return keysAndValuesToObject(this.names, groups);
            } else {
                return groups;
            }
        };
        UrlPattern.prototype.stringify = function(params) {
            if (params == null) {
                params = {};
            }
            if (this.isRegex) {
                throw new Error("can't stringify patterns generated from a regex");
            }
            if (params !== Object(params)) {
                throw new Error("argument must be an object or undefined");
            }
            return stringify(this.ast, params, {});
        };
        UrlPattern.escapeForRegex = escapeForRegex;
        UrlPattern.concatMap = concatMap;
        UrlPattern.stringConcatMap = stringConcatMap;
        UrlPattern.regexGroupCount = regexGroupCount;
        UrlPattern.keysAndValuesToObject = keysAndValuesToObject;
        UrlPattern.P = P;
        UrlPattern.newParser = newParser;
        UrlPattern.defaultOptions = defaultOptions;
        UrlPattern.astNodeToRegexString = astNodeToRegexString;
        UrlPattern.astNodeToNames = astNodeToNames;
        UrlPattern.getParam = getParam;
        UrlPattern.astNodeContainsSegmentsForProvidedParams = astNodeContainsSegmentsForProvidedParams;
        UrlPattern.stringify = stringify;
        return UrlPattern;
    }
    const UrlPattern = new UP();

    function Base( app = null)
    {
        this.app = app;
        this.__observables = null;
        this.__listeners = undefined;
        if ( this.app )
        {
            this.storage = this.app.storage;
        }
    }

    // Inheritance
    // none

    // Proto properties
    Base.prototype.EVENT = {};
    Base.prototype.resources = [];
    Base.prototype.__id = null;
    Base.prototype.getResource = function( url )
    {
        let rm = null,
            resource = null;

        if ( this.app )
        {
            rm = this.app.resourceManager;
        }
        else
        {
            if ( this.hasOwnProperty( 'resourceManager' ) )
            {
                rm = this.resourceManager;
            }
        }

        if ( rm )
        {
            resource = rm.get( url );
        }

        return resource;
    };

    Base.prototype.getId = function()
    {
        if ( this.hasOwnProperty( '__id' ) )
        {
            return this.__id;
        }
        else
        {
            return null;
        }
    };

    Base.prototype.observables = function( data )
    {
        const puid = 'PROXY-' + this.createUuid();

        this.__observables = ObservableSlim.create( data, true, null, puid );

        for ( let key in data )
        {
            Object.defineProperty( this, key, {
                get: function() { return this.__observables[ key ]; },
                set : function( newValue ) { this.__observables[ key ] = newValue; }
            });
        }

        ObservableSlim.observe( this.__observables, function( changes )
        {
            GlobalEventDispatcher.dispatchEvent( {
                type : 'OBSERVABLE_CHANGE_' + puid,
                changes : changes
            });
            for ( let ci = 0; ci < changes.length; ci++ )
            {
                GlobalEventDispatcher.dispatchEvent({
                    type : 'OBSERVABLE_CHANGE_' + changes[ ci ].property.toUpperCase() +  '_' + puid,
                    changes: changes[ ci ]
                });
            }
        }.bind( this ) );
    };

    Base.prototype.observe = function( onChangeEvent )
    {
        if ( null === this.__observables )
        {
            return;
        }

        if ( arguments.length === 2 )
        {
            this.observeProperty( arguments[ 0 ], arguments[ 1 ] );
        }
        else
        {
            GlobalEventDispatcher.addEventListener(
                'OBSERVABLE_CHANGE_' + this.__observables.__uid,
                onChangeEvent
            );
        }
    };

    Base.prototype.observeProperty = function( property, onChangeEvent )
    {
        if ( null === this.__observables )
        {
            return;
        }

        GlobalEventDispatcher.addEventListener(
            'OBSERVABLE_CHANGE_' + property.toUpperCase() + '_' + this.__observables.__uid,
            onChangeEvent
        );
    };

    Base.prototype.hasPropertyChanged = function( changes, property )
    {
        let hasChanged = false;

        if ( changes && changes.hasOwnProperty( 'changes' ) && changes.changes.length > 0 )
        {
            for ( let ci = 0; ci < changes.changes.length; ci++ )
            {
                if ( changes.changes[ ci ].property === property )
                {
                    hasChanged = true;
                    break;
                }
            }
        }

        return hasChanged;
    };

    Base.prototype.getCurrentPropertyValue = function( changes, property )
    {
        let propValue,
            propValueFound = false;

        if ( changes && changes.hasOwnProperty( 'changes' ) && changes.changes.length > 0 )
        {
            for ( let ci = 0; ci < changes.changes.length; ci++ )
            {
                if ( changes.changes[ ci ].property === property )
                {
                    propValue = changes.changes[ ci ].newValue;
                    propValueFound = true;
                    break;
                }
            }
        }

        if ( false === propValueFound && this.__observables )
        {
            for ( let k in this.__observables )
            {
                if ( k === property )
                {
                    propValue = this.__observables[ k ];
                    break;
                }
            }
        }

        return propValue;
    };

    Base.prototype.unobserve = function( fnOnChanges )
    {
        if ( null === this.__observables )
        {
            return;
        }

        GlobalEventDispatcher.removeEventListener(
            'OBSERVABLE_CHANGE_' + this.__observables.__uid,
            fnOnChanges
        );
    };

    Base.prototype.__destroy = function()
    {
        if ( null === this.__observables )
        {
            return;
        }

        GlobalEventDispatcher.removeAllEventListener(
            'OBSERVABLE_CHANGE_' + this.__observables.__uid
        );
    };

    Base.prototype.addEventListener = function ( type, listener )
    {
        if ( this.__listeners === undefined ) this.__listeners = {};

        const listeners = this.__listeners;
        if ( listeners[ type ] === undefined )
        {
            listeners[ type ] = [];
        }

        if ( listeners[ type ].indexOf( listener ) === - 1 )
        {
            listeners[ type ].push( listener );
        }
    };

    Base.prototype.hasEventListener = function ( type, listener )
    {
        if ( this.__listeners === undefined ) return false;

        const listeners = this.__listeners;
        return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
    };

    Base.prototype.removeEventListener = function ( type, listener )
    {
        if ( this.__listeners === undefined ) return;

        const listeners = this.__listeners;
        const listenerArray = listeners[ type ];

        if ( listenerArray !== undefined ) {

            const index = listenerArray.indexOf( listener );

            if ( index !== - 1 )
            {
                listenerArray.splice( index, 1 );
            }

        }

    };

    Base.prototype.removeAllEventListener = function( type )
    {
        if ( this.__listeners === undefined ) return;

        const listeners = this.__listeners;
        if ( listeners[ type ] !== undefined )
        {
            listeners[ type ] = [];
        }
    };

    Base.prototype.dispatchEvent = function ( event )
    {
        if ( this.__listeners === undefined ) return;

        const listeners = this.__listeners;
        const listenerArray = listeners[ event.type ];

        if ( listenerArray !== undefined )
        {
            event.target = this;

            var array = listenerArray.slice( 0 );
            for ( let i = 0, l = array.length; i < l; i ++ )
            {
                array[ i ].call( this, event );
            }
        }
    };

    Base.prototype.createInstance = function( classId, props = {} )
    {
        return this.app.classManager.create( classId, props );
    };

    Base.prototype.createComponent = function( componentId, container = null, props = {} )
    {
        return this.app.componentManager.create( componentId, container, props );
    };

    Base.prototype.createXhr = function( props = {} )
    {
        return this.app.createXhr( props );
    };

    Base.prototype.createUuid = function()
    {
        return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
            (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
        );
    };

    Base.prototype.redirect = function( url, forceReload = false )
    {
        this.app.controller.redirect( url, forceReload );
    };

    Base.prototype.reload = function( url, hardReload )
    {
        this.app.controller.reload( url, hardReload );
    };

    Base.prototype.getPropertyValue = function( obj, property, defaultValue = null )
    {
        if ( obj && obj.hasOwnProperty( property ) )
        {
            return obj[ property ];
        }
        else
        {
            return defaultValue;
        }
    };

    Base.prototype.throwBadRequest = function( errorMsg )
    {
        this.throw( 400, errorMsg );
    };

    Base.prototype.throwUnauthorized = function( errorMsg )
    {
        this.throw( 401, errorMsg );
    };

    Base.prototype.throwPaymentRequired = function( errorMsg )
    {
        this.throw( 402, errorMsg );
    };

    Base.prototype.throwForbidden = function( errorMsg )
    {
        this.throw( 403, errorMsg );
    };

    Base.prototype.throwNotFound = function( errorMsg )
    {
        this.throw( 404, errorMsg );
    };

    Base.prototype.throwError = function( errorMsg )
    {
        this.throw( 500, errorMsg );
    };

    Base.prototype.throw = function( errorCode = 500, errorMessage = null)
    {
        throw new Error( JSON.stringify( { code: errorCode, message: errorMessage } ) );
    };

    Base.prototype.createITBRpcClient = function( props = {})
    {
        return new ItbRpcClient( props );
    };

    Base.prototype.nf = nf;

    Base.prototype.getConfig = function( key, defaultValue = null )
    {
        if ( -1 < key.indexOf( '.') )
        {
            return key.split('.').reduce(function(prev, curr) {
                return prev ? prev[curr] : defaultValue
            }, this.app.config );
        }

        else if ( this.app.config.hasOwnProperty( key ) )
        {
            return this.app.config[ key ];
        }
        else
        {
            return defaultValue;
        }
    };

    function ClassManager( app )
    {
        Base.call( this, app );

        this.classBodies = {};
    }

    // Inheritance
    ClassManager.prototype = Object.create( Base.prototype );
    ClassManager.prototype.constructor = ClassManager;

    // Proto functions
    ClassManager.prototype.add = function( classId, classBody )
    {
        classBody.id = classId;
        this.classBodies[ classId ] = classBody;
    };

    ClassManager.prototype.get = function( classId )
    {
        if ( this.classBodies.hasOwnProperty( classId ) )
        {
            return this.classBodies[ classId ];
        }
        else
        {
            return null;
        }
    };

    ClassManager.prototype.create = function( classId, props = {} )
    {
        let classBody = this.get( classId ),
            instance = new Base( this.app );

        if ( classBody )
        {
            instance = applyBodyToObject( instance, classBody );
            instance.create && instance.create.call( instance, new Params( props ) );
        }

        return instance;
    };

    function Controller( app )
    {
        // Super
        Base.call( this, app );

        this.enabled = false;
        this.currentPath = null;
        this.previousPath = null;
    }

    // Inheritance
    Controller.prototype = Object.create( Base.prototype );
    Controller.prototype.constructor = Controller;

    Controller.prototype.EVENT.CONTROLLER_VIEW_CHANGED = 'EVENT_CONTROLLER_VIEW_CHANGED';

    // Proto properties
    Controller.prototype.enable = function()
    {
        if ( this.enabled )
        {
            return true;
        }

        window.addEventListener( 'hashchange', this.processHash.bind( this ) );
        this.enabled = true;
        this.processHash();
    };

    Controller.prototype.disable = function()
    {
        if ( this.enabled )
        {
            window.removeEventListener( 'hashchange', this.processHash.bind( this ) );
            this.enabled = false;
        }
    };

    Controller.prototype.reload = function( url = null, hardReload = false )
    {
        if ( null === url )
        {
            // Soft reload
            this.processHash();
        }
        else
        {
            this.disable();
            this.redirect( url );
            window.location.reload( hardReload );
        }
    };

    Controller.prototype.getCurrentView = function()
    {
        return this.app.viewManager.currentView;
    };

    Controller.prototype.processHash = function()
    {
        const hash = location.hash || '#';
        let path = hash.slice(1);

        // always start with a leading slash
        path = '/' + trim( path, '/' );

        this.previousPath = this.currentPath;
        this.currentPath = path;
        this.execute( path );
    };

    Controller.prototype.getPreviousPath = function()
    {
        return this.previousPath;
    };

    Controller.prototype.redirect = function( url, forceReload = false )
    {
        location.hash = '/' + trim( url, '/' );
        if ( true === forceReload )
        {
            this.processHash();
        }
    };

    Controller.prototype.execute = function( path )
    {
        // Get view call
        try
        {
            let viewCall = this.app.viewManager.resolveViewCallByPath( path ),
                viewParams = new Params( viewCall.params ),
                view = this.app.viewManager.create( viewCall.viewId, viewParams );

            if ( this.app.viewManager.canAccess( view, viewParams) )
            {
                this.app.viewManager.switchTo( view, viewParams );
                this.dispatchEvent( { type : this.EVENT.CONTROLLER_VIEW_CHANGED, data : { view : view, viewParams: viewParams } } );
            }
            else
            {
                if ( view.hasOwnProperty( 'redirectUrl' ) && view.redirectUrl )
                {
                    this.redirect( view.redirectUrl );
                }
                else
                {
                    this.throwUnauthorized( 'User is not allowed to access this view: ' + view.__id );
                }
            }
        }
        catch( e )
        {
            this.app.errorHandler.processError( e );
        }
    };

    function ErrorHandler( app )
    {
        Base.call( this, app );
    }

    // Inheritance
    ErrorHandler.prototype = Object.create( Base.prototype );
    ErrorHandler.prototype.constructor = ErrorHandler;

    // Proto properties
    ErrorHandler.prototype.on400 = function( error )
    {
        this.app.onBadRequest( error );
    };
    ErrorHandler.prototype.on401 = function( error )
    {
        this.app.onUnauthorized( error );
    };
    ErrorHandler.prototype.on402 = function( error )
    {
        this.app.onPaymentRequired( error );
    };
    ErrorHandler.prototype.on403 = function( error )
    {
        this.app.onForbidden( error );
    };
    ErrorHandler.prototype.on404 = function( error )
    {
        this.app.onNotFound( error );
    };
    ErrorHandler.prototype.on500 = function( error )
    {
        this.app.onGeneralError( error );
    };
    ErrorHandler.prototype.processError = function( error )
    {
        let errorMsg = ( error && error.hasOwnProperty( 'message' ) ) ? error.message : error,
            frontError = this.resolveError( errorMsg );

        if ( null === frontError )
        {
            this.on500( errorMsg );
        }
        else
        {
            switch( frontError.code )
            {
                case 400:
                    this.on400( frontError.message );
                    break;
                case 401:
                    this.on401( frontError.message );
                    break;
                case 402:
                    this.on402( frontError.message );
                    break;
                case 403:
                    this.on403( frontError.message );
                    break;
                case 404:
                    this.on404( frontError.message );
                    break;
                default:
                case 500:
                    this.on500( frontError.message );
                    break;
            }
        }
    };
    ErrorHandler.prototype.resolveError = function( errorMsg )
    {
        let frontError = null;
        try
        {
            frontError = JSON.parse( errorMsg );
            if ( !frontError || !frontError.hasOwnProperty( 'code' ) )
            {
                frontError = null;
            }
            else if ( !frontError.hasOwnProperty( 'message' ) )
            {
                frontError.message = null;
            }
        }
        catch ( e )
        {
            frontError = null;
        }

        return frontError;
    };

    function Localization( app )
    {
        Base.call( this, app );

        var defaultConfig = {
            defaultLanguage : 'en',
            language : null,
            dictionaryUrl : null,
            exposeFunctionName : '_lc'
        };

        this.config = Object.assign( defaultConfig, app.config.localization );
        this.language = null;
        this.dictionary = {};

        if ( null !== this.config.exposeFunctionName )
        {
            this.expose( this.config.exposeFunctionName );
        }
    }

    // Inheritance
    Localization.prototype = Object.create( Base.prototype );
    Localization.prototype.constructor = Localization;

    // Proto properties
    Localization.prototype.expose = function( fnName )
    {
        if ( window )
        {
            window[ fnName ] = this.getLocale.bind( this );
        }
    };

    Localization.prototype.getLocale = function( key, params )
    {
        const defaultLanguage = this.config.defaultLanguage,
            language = this.language,
            dictionary = this.dictionary;

        if ( language && dictionary[ language ].hasOwnProperty( key ) )
        {
            return dictionary[ language][ key ].replace(/{(\d+)}/g, function(match, number)
            {
                return typeof params[number] != 'undefined'
                    ? params[number]
                    : match
                    ;
            });
        }
        else if ( defaultLanguage &&
            dictionary.hasOwnProperty( defaultLanguage ) &&
            dictionary[ defaultLanguage ].hasOwnProperty( key ) )
        {
            return dictionary[ defaultLanguage ][ key ].replace(/{(\d+)}/g, function(match, number)
            {
                return typeof params[number] != 'undefined'
                    ? params[number]
                    : match
                    ;
            });
        }
        else
        {
            return '###' + key + '###';
        }
    };

    Localization.prototype.setLanguage = function( lang = null )
    {
        const dictionary = this.dictionary;

        if ( null === lang )
        {
            lang = this.config.language;
        }

        if ( this.hasLanguage( lang ) )
        {
            this.language = lang;
        }
        else if ( this.hasLanguage( this.getEnvironmentLanguage() ) )
        {
            this.language = this.getEnvironmentLanguage();
        }
        else if ( this.hasLanguage( this.config.defaultLanguage ) )
        {
            this.language = this.config.defaultLanguage;
        }
        else
        {
            this.language = null;
        }

        return ( this.language !== null );
    };

    Localization.prototype.hasLanguage = function( lang )
    {
        return this.dictionary.hasOwnProperty( lang );
    };

    Localization.prototype.getEnvironmentLanguage = function()
    {
        let envLang = null;

        if ( window && window.navigator && window.navigator.language )
        {
            if ( window.navigator.language.length > 2 )
            {
                envLang = window.navigator.language.substring( 0, 2 );
                envLang.toLowerCase();
            }
            else if ( window.navigator.language.length === 2 )
            {
                envLang = window.navigator.language;
                envLang.toLowerCase();
            }
        }

        return envLang;
    };

    Localization.prototype.__create = function()
    {
        if ( null !== this.config.dictionaryUrl )
        {
            let dict = this.getResource( this.config.dictionaryUrl );
            if ( dict )
            {
                this.dictionary = dict;
                this.setLanguage();
            }
        }
    };

    function Storage( ns = 'default', app = null )
    {
        if ( !window.localStorage ) throw new Error( 'window.localeStorage is not supported.' );

        Base.call( this, app );

        this.namespace = ns;
    }
    // Inheritance
    Storage.prototype = Object.create( Base.prototype );
    Storage.prototype.constructor = Storage;

    // Proto properties
    Storage.prototype.getPrefix = function()
    {
        return this.namespace + '-';
    };

    Storage.prototype.get = function( key )
    {
        return localStorage.getItem( this.getPrefix() + key );
    };

    Storage.prototype.set = function( key, value )
    {
        localStorage.setItem( this.getPrefix() + key, value );
    };

    Storage.prototype.remove = function( key )
    {
        localStorage.removeItem( this.getPrefix() + key );
    };

    Storage.prototype.clear = function()
    {
        // Loop over all keys - if key starts with prefix -> removeItem
        let k = null,
            ns = this.namespace;

        for ( var li = 0; li < localStorage.length; li++ )
        {
            k = localStorage.key( li );
            if ( 0 === k.indexOf( ns ) )
            {
                localStorage.removeItem( k );
            }
        }
    };

    function ResourceLoader( app )
    {
        Base.call( this, app );

        this.appLoader = app.config.appLoader;

        this.basePath = app.config.hasOwnProperty( 'resourceBasePath' ) ? app.config.resourceBasePath : null;
        this.totalFiles = 0;
        this.loadCount = 0;
        this.loadCountCss = 0;
        this.onLoad = null;

        this.cacheBreak = '?' + Date.now();

        this.resources = [];
        this.css = [];
        this.js = [];
    }

    // Inheritance
    ResourceLoader.prototype = Object.create( Base.prototype );
    ResourceLoader.prototype.constructor = ResourceLoader;

    // Proto properties
    ResourceLoader.prototype.load = function( onLoad )
    {
        this.onLoad = onLoad;

        let resolveUrl = function( resUrl )
        {
            let url = '';

            // If absolute path
            if ( -1 < resUrl.indexOf( 'http' ) )
            {
                url = resUrl;
            }
            else if ( null !== this.basePath )
            {
                url = this.basePath + '/' + resUrl;
            }
            else
            {
                url = resUrl;
            }

            // No cacheBreak on absolute URLs
            if ( this.cacheBreak && -1 === resUrl.indexOf( 'http' ) )
            {
                url = url + this.cacheBreak;
            }

            return url;
        }.bind( this );

        let onProgress = function()
        {
            this.loadCount++;

            if ( this.appLoader )
            {
                this.appLoader.__onProgress( this.loadCount, this.totalFiles );
            }

            if ( this.loadCount >= this.totalFiles )
            {
                this.onDone();
            }
        }.bind( this );


        let onProcessCss = function()
        {
            this.loadCountCss++;

            if ( this.loadCountCss >= this.css.length )
            {
                startLoadingResources();
            }
            else
            {
                loadResourceCss( this.css[ this.loadCountCss ] );
                onProgress();
            }
        }.bind( this );

        let startLoadingCss = function()
        {
            if ( this.css.length > 0 )
            {
                this.loadCountCss = -1;
                onProcessCss();
            }
            else
            {
                startLoadingResources();
            }
        }.bind( this );

        let startLoadingResources = function()
        {
            if ( this.resources.length > 0 )
            {
                for ( let li = 0; li < this.resources.length; li++ )
                {
                    loadResource( this.resources[ li ] );
                }
            }
            else
            {
                this.onDone();
            }

        }.bind( this );

        let loadResourceCss = function( res )
        {
            const request = new XMLHttpRequest(),
                resource = res,
                fullUrl = resolveUrl( resource.url );

            request.open( 'GET', fullUrl );

            request.onload = function()
            {

                const head = document.getElementsByTagName( 'head' )[ 0 ];
                const link = document.createElement( 'link' );
                link.rel = 'stylesheet';
                link.type = 'text/css';
                link.href = resource.url;
                link.media = 'all';
                head.appendChild( link );

                onProcessCss();

            }.bind( this );

            request.onabort = function()
            {
                console.log( "Aborted..." );
                if ( this.appLoader )
                {
                    this.appLoader.onError( 'abort', 'Unknown' );
                }
                onProcessCss();
            };

            request.onerror = function()
            {
                console.log( "Error..." );
                if ( this.appLoader )
                {
                    this.appLoader.onError( 'error', 'Unknown' );
                }
                onProcessCss();
            };

            request.send();
        }.bind( this );

        let loadResource = function( res )
        {
            const request = new XMLHttpRequest(),
                resource = res,
                fullUrl = resolveUrl( resource.url );

            request.open( 'GET', fullUrl, resource.type !== 'css' );

            request.onload = function()
            {
                if (request.status >= 200 && request.status < 400)
                {
                    const response = request.responseText;
                    switch( resource.type )
                    {
                        case 'htm':
                        case 'html':
                            let tmpl = document.createElement( 'script' );
                            tmpl.setAttribute( 'type', 'text/html' );
                            tmpl.setAttribute( 'data-if-tmpl-id', resource.id );
                            tmpl.insertAdjacentText( 'beforeEnd', response );
                            document.body.appendChild( tmpl );
                            break;

                        case 'json':
                            let jsonResponse = null;
                            try
                            {
                                jsonResponse = JSON.parse( response );
                            }
                            catch (e )
                            {
                                jsonResponse = null;
                            }
                            this.app.resourceManager.add( resource.url, jsonResponse );
                            break;

                        case 'css':
                            // CSS is a special case
                            // The stylesheet is just preloaded (and hopefully buffered by the browser)
                            // We add it to the DOM again in here
                            const head = document.getElementsByTagName( 'head' )[ 0 ];
                            const link = document.createElement( 'link' );
                            link.rel = 'stylesheet';
                            link.type = 'text/css';
                            link.href = fullUrl;
                            link.media = 'all';
                            head.appendChild( link );
                            break;
                    }
                }
                onProgress();
            }.bind( this );

            request.onabort = function()
            {
                console.log( "Aborted..." );
                if ( this.appLoader )
                {
                    this.appLoader.__onError( 'abort', null );
                }
                onProgress();
            }.bind( this );

            request.onerror = function()
            {
                console.log( "Error..." );
                if ( this.appLoader )
                {
                    this.appLoader.__onError( 'abort', null );
                }
                onProgress();
            }.bind( this );

            request.send();

        }.bind( this );

        // Start with asynchronous resources first
        for ( let componentId in this.app.componentManager.componentBodies )
        {
            let templateUrl = this.app.componentManager.componentBodies[ componentId ].templateUrl;

            if ( templateUrl )
            {
                this.addResource(
                    templateUrl,
                    'component-' + this.app.componentManager.componentBodies[ componentId ].__id
                );
            }
        }

        for ( let viewId in this.app.viewManager.viewBodies )
        {
            let templateUrl = this.app.viewManager.viewBodies[ viewId ].templateUrl;

            if ( templateUrl )
            {
                this.addResource(
                    templateUrl,
                    'view-' + this.app.viewManager.viewBodies[ viewId ].__id
                );
            }

            if ( this.app.viewManager.viewBodies[ viewId ].hasOwnProperty( 'resources' ) &&
                this.app.viewManager.viewBodies[ viewId ].resources instanceof Array &&
                this.app.viewManager.viewBodies[ viewId ].resources.length > 0 )
            {
                for ( let vri = 0; vri < this.app.viewManager.viewBodies[ viewId ].resources.length; vri++ )
                {
                    let vr = this.app.viewManager.viewBodies[ viewId ].resources[ vri ];
                    if ( vr.hasOwnProperty( 'id' ) && vr.hasOwnProperty( 'url' ) )
                    {
                        this.addResource(
                            vr.url,
                            vr.id
                        );
                    }
                }
            }
        }

        // Add resources from localization
        if ( null !== this.app.localization.config.dictionaryUrl )
        {
            this.addResource( this.app.localization.config.dictionaryUrl, 'app-dictionary', 'json' );
        }

        // Add apps js dependencies (e.g. libraries etc)
        if ( this.app.config.resources.hasOwnProperty( 'js' ) && this.app.config.resources.js.length > 0 )
        {
            for ( let ji = 0; ji < this.app.config.resources.js.length; ji++ )
            {
                this.addJs(
                    this.app.config.resources.js[ ji ],
                    'app-js-' + ji
                );
            }
        }

        // Add synchronous data at last
        if ( this.app.config.resources.hasOwnProperty( 'css' ) && this.app.config.resources.css.length > 0 )
        {
            for ( let ci = 0; ci < this.app.config.resources.css.length; ci++ )
            {
                this.addCss(
                    this.app.config.resources.css[ ci ],
                    'app-css-' + ci
                );
            }
        }

        this.totalFiles = this.resources.length + this.css.length + this.js.length;

        if ( this.appLoader )
        {
            this.appLoader.__onStart( this.loadCount, this.totalFiles );
        }

        // Start JS script-tag injection first
        if ( this.js.length > 0 )
        {
            let scriptTag;
            for ( let ji = 0; ji < this.js.length; ji++ )
            {
                scriptTag = document.createElement( 'script' );
                scriptTag.src = resolveUrl(  this.js[ ji ].url );
                scriptTag.onload = onProgress;
                scriptTag.onerror = onProgress;
                scriptTag.onabort = onProgress;
                document.body.appendChild( scriptTag );
            }
        }

        startLoadingCss();
    };

    ResourceLoader.prototype.addJs  = function( resUrl, resId )
    {
        let resourceId = resId.toLowerCase();
        this.js.push({
            url : resUrl,
            id : resourceId,
            type : 'js'
        });
    };

    ResourceLoader.prototype.addCss = function( resUrl, resId )
    {
        let resourceId = resId.toLowerCase();
        this.css.push({
            url : resUrl,
            id : resourceId,
            type : 'css'
        });
    };

    ResourceLoader.prototype.addResource = function( resUrl, resId )
    {
        let suffix,
            cacheBreak = '?' + Date.now(),
            resourceId = resId.toLowerCase();

        suffix = resUrl.split( '.' ).pop();
        resUrl = resUrl + cacheBreak;
        switch( suffix )
        {
            case 'htm':
            case 'html':
                this.resources.push({
                    url: resUrl,
                    id: resourceId,
                    type : 'html'
                });
                break;

            case 'js':
                this.resources.push({
                    url : resUrl,
                    id : resourceId,
                    type : 'js'
                });
                break;

            case 'json':
                this.resources.push({
                    url : resUrl,
                    id : resourceId,
                    type : 'json'
                });
                break;

            case 'css':
                this.resources.push({
                    url : resUrl,
                    id : resourceId,
                    type : 'css'
                });
                break;

            default:
                console.warn( 'Unknown resoruce type to add with suffix ' + suffix + '. Resource URL: ' + resUrl );
        }
    };

    ResourceLoader.prototype.onDone = function()
    {
        if ( this.appLoader )
        {
            this.appLoader.__onDone( this.onLoad );
        }
        else
        {
            this.onLoad && this.onLoad();
        }
    };

    function ResourceManager( app )
    {
        Base.call( this, app );

        this.res = {};
    }

    // Inheritance
    ResourceManager.prototype = Object.create( Base.prototype );
    ResourceManager.prototype.constructor = ResourceManager;

    // Proto properties
    ResourceManager.prototype.add = function( url, data )
    {
        this.res[ url ] = data;
    };

    ResourceManager.prototype.get = function( url )
    {
        if ( this.res.hasOwnProperty( url ) )
        {
            let suffix = url.split( '.' ).pop();

            switch( suffix )
            {
                case 'htm':
                case 'html':
                    let dp = new DOMParser();
                    return dp.parseFromString( this.res[ url ], 'text/html' ).body.childNodes;

                default:
                    return this.res[ url ];
            }
        }
        else
        {
            return null;
        }
    };

    function Renderable( app, container = null )
    {
        Base.call( this, app );

        this.container = container ? container : null;

        this.__delegateEvents = [];
    }

    // Inheritance
    Renderable.prototype = Object.create( Base.prototype );
    Renderable.prototype.constructor = Renderable;

    // Proto properties
    Renderable.prototype.template = null;

    Renderable.prototype.delegate = function( rootElement, selector, eventType, eventHandler )
    {
        if ( arguments.length === 3  )
        {
            eventHandler = eventType;
            eventType = selector;
            selector = rootElement;
            rootElement = this.container;
        }

        if ( selector.length && '#' === selector[0] )
        {
            selector = '[data-if-id="' + selector.substr(1) + '"]';
        }

        const d = delegate( rootElement, selector, eventType, eventHandler );
        if ( d )
        {
            this.__delegateEvents.push(
                {
                    re : rootElement,
                    s : selector,
                    et : eventType,
                    eh : eventHandler,
                    d : d
                }
            );
        }
        return d;
    };
    Renderable.prototype.undelegate = function( rootElement, selector, eventType, eventHandler )
    {
        if ( rootElement )
        {
            for ( let dei = 0; dei < this.__delegateEvents.length; dei++ )
            {
                if ( this.__delegateEvents[ dei ].re === rootElement &&
                    this.__delegateEvents[ dei ].s === selector &&
                    this.__delegateEvents[ dei ].et === eventType &&
                    this.__delegateEvents[ dei ].eh === eventHandler )
                {

                    this.__delegateEvents[ dei ].d.destroy();
                    this.__delegateEvents.splice( dei, 1 );
                    break;
                }
            }
        }
    };
    Renderable.prototype.__destroy = function()
    {
        Base.prototype.__destroy.call( this );

        if ( this.__delegateEvents && this.__delegateEvents.length > 0 )
        {
            for ( let dei = 0; dei < this.__delegateEvents.length; dei++ )
            {
                this.__delegateEvents[ dei ].d.destroy();
            }

            this.__delegateEvents = [];
        }
    };

    Renderable.prototype.findById = function( fId )
    {
        return this.container.querySelector( '[data-if-id="' + fId + '"]' );
    };

    Renderable.prototype.findOne = function( selector )
    {
        return this.container.querySelector( selector );
    };

    Renderable.prototype.findAll = function( selector )
    {
        return this.container.querySelectorAll( selector );
    };

    Renderable.prototype.renderTemplate = function( templateId, data = {} )
    {
        if ( this.__observables )
        {
            for( let k in this.__observables )
            {
                if ( !data.hasOwnProperty( k ) )
                {
                    data[ k ] = this.__observables[ k ];
                }
            }
        }

        if ( false === data.hasOwnProperty( '_nf' ) )
        {
            data[ '_nf' ] = this.nf;
        }

        let vDom = template$1( templateId, data );
        vDom = new DOMParser().parseFromString( vDom, 'text/html' );
        let vModels = vDom.querySelectorAll( '[data-if-model]' );
        let modelKey;
        for ( let vmi = 0; vmi < vModels.length; vmi++ )
        {
            modelKey = vModels[ vmi ].getAttribute( 'data-if-model' );

            if ( !data || false === data.hasOwnProperty( modelKey ) )
            {
                continue;
            }

            switch ( vModels[ vmi ].tagName )
            {
                case 'INPUT':
                    vModels[ vmi ].setAttribute( 'value', data[ modelKey ] );
                    break;

                case 'SELECT':
                    console.log( 'data-if-model in select tags is not supported.' );
                    break;

                default:
                    vModels[ vmi ].insertAdjacentHTML('beforeEnd', data[ modelKey ] );
                    break;
            }
        }

        return vDom.body.innerHTML;
    };

    Renderable.prototype.getTemplateId = function()
    {
        return null;
    };

    Renderable.prototype.render = function( params = {} )
    {
        if ( null === this.container )
        {
            // Create a virtual container
            this.container = document.createElement( 'div' );
        }
        this.container.innerHTML = this.renderTemplate( this.getTemplateId(), params );
    };

    function View( app, container = null )
    {
        Renderable.call( this, app, container );
    }

    // Inheritance
    View.prototype = Object.create( Renderable.prototype );
    View.prototype.constructor = View;

    // Proto functions
    View.prototype.isDefault = false;
    View.prototype.route = null;
    View.prototype.create = function() {};
    View.prototype.destroy = function() {};
    View.prototype.__canAccess = function( params = {} )
    {
        if ( this.hasOwnProperty( 'requiredRole' ) && this.requiredRole )
        {
            return this.app.user.hasRole( this.requiredRole );
        }

        if ( this.hasOwnProperty( 'canAccess' ) && "function" === typeof this.canAccess )
        {
            return this.canAccess( params );
        }

        return true;
    };
    View.prototype.__create = function( params = {} )
    {
        // does not exists yet: Renderable.prototype.__create.call( this );
    };
    View.prototype.__destroy = function()
    {
        Renderable.prototype.__destroy.call( this );
        if ( this.container )
        {
            this.container.innerHTML = '';
        }
    };
    View.prototype.isView = function()
    {
        return true;
    };
    View.prototype.getTemplateId = function()
    {
        return 'view-' + this.__id;
    };

    function ViewManager( app )
    {
        // Super
        Base.call( this, app );

        // Init
        this.currentView = null;
        this.defaultViewId = null;
        this.viewUrlPatterns = [];
        this.viewBodies = {};
    }

    // Inheritance
    ViewManager.prototype = Object.create( Base.prototype );
    ViewManager.prototype.constructor = ViewManager;

    // Proto properties
    ViewManager.prototype.add = function( viewId, viewBody )
    {
        viewBody.__id = viewId;
        if ( !viewBody.hasOwnProperty( 'resources') )
        {
            viewBody.resources = [];
        }
        this.viewBodies[ viewId ] = viewBody;

        if ( viewBody.hasOwnProperty( 'route' ) && viewBody.route.length)
        {
            let vRoute = trim( viewBody.route, '/' );
            vRoute = '/' + vRoute;
            this.viewUrlPatterns.push({
                viewId : viewId,
                pattern : new UrlPattern( vRoute )
            });
        }

        if ( viewBody.hasOwnProperty( 'isDefault' ) && viewBody.isDefault === true )
        {
            this.defaultViewId = viewId;
        }
    };

    ViewManager.prototype.resolveViewCallByPath = function( path )
    {
        let viewCall = null,
            params = null;

        if ( !path || path === '/' )
        {
            if ( this.defaultViewId )
            {
                viewCall = {
                    viewId : this.defaultViewId,
                    params : {}
                };
            }
            else
            {
                this.throwNotFound( 'No default view found.' );
            }
        }
        else
        {
            for (let ri = 0; ri < this.viewUrlPatterns.length; ri++ )
            {
                params = this.viewUrlPatterns[ ri ].pattern.match( path );
                if ( params )
                {
                    viewCall = {
                        viewId : this.viewUrlPatterns[ ri ].viewId,
                        params : params
                    };
                    break;
                }
            }

            if ( null === viewCall )
            {
                this.throwNotFound( path );
            }
        }

        return viewCall;
    };

    ViewManager.prototype.create = function( viewId, params = {} )
    {
        const viewBody  = this.viewBodies.hasOwnProperty( viewId ) ? this.viewBodies[ viewId ] : null;
        let view = null;

        if ( viewBody )
        {
            view = new View( this.app );
            view = applyBodyToObject( view, viewBody );
        }

        return view;
    };

    ViewManager.prototype.canAccess = function( view, params = {} )
    {
        return view.__canAccess( params );
    };

    ViewManager.prototype.switchTo = function( view, params = {} )
    {
        if ( view )
        {
            if ( this.exitCurrent( params ) )
            {
                this.enterNew( view, params );
            }
        }

        return true;
    };

    ViewManager.prototype.enterNew = function( view, params = {} )
    {
        try
        {
            view.__create( params );
            view.create && view.create( params );
            this.currentView = view;
        }
        catch( e )
        {
            console.log( e );
        }
    };

    ViewManager.prototype.exitCurrent = function( params = {} )
    {
        let res = true;
        if ( this.currentView )
        {
            res = this.currentView.destroy && this.currentView.destroy();
            this.currentView.__destroy();
        }

        return true;
    };

    ViewManager.prototype.createUrlPattern = function( route )
    {
        let vRoute = trim( route, '/' );
        vRoute = '/' + vRoute;
        return new UrlPattern( vRoute );
    };

    function Component( app, container = null )
    {
        Renderable.call( this, app, container );
    }

    // Inheritance
    Component.prototype = Object.create( Renderable.prototype );
    Component.prototype.constructor = Component;

    // Proto functions
    Component.prototype.create = function() {};
    Component.prototype.destroy = function() {};
    Component.prototype.__create = function( params = {} )
    {
        Renderable.prototype.__create.call( this );
    };
    Component.prototype.__destroy = function()
    {
        Renderable.prototype.__destroy.call( this );
        if ( this.container )
        {
            this.container.innerHTML = '';
        }
    };

    Component.prototype.getTemplateId = function()
    {
        return 'component-' + this.__id;
    };

    function ComponentManager( app )
    {
        Base.call( this, app );

        this.componentBodies = {};
    }

    // Inheritance
    ComponentManager.prototype = Object.create( Base.prototype );
    ComponentManager.prototype.constructor = ComponentManager;

    // Proto functions
    ComponentManager.prototype.add = function( componentId, componentBody )
    {
        componentBody.__id = componentId;
        this.componentBodies[ componentId ] = componentBody;
    };

    ComponentManager.prototype.get = function( componentId )
    {
        if ( this.componentBodies.hasOwnProperty( componentId ) )
        {
            return this.componentBodies[ componentId ];
        }
        else
        {
            return null;
        }
    };

    ComponentManager.prototype.create = function( componentId, container = null, props = {} )
    {
        /*
	    if ( !container )
	    {
	        this.throwError( 'Component ' + componentId + ' cannot be created without container.' );
	    }
	     */

        let componentBody = this.get( componentId ),
            instance = new Component( this.app, container );

        if ( componentBody )
        {
            instance = applyBodyToObject( instance, componentBody );
            instance.create && instance.create( new Params( props ) );
        }

        return instance;
    };

    function AppLoader()
    {
        this.app = null;
        this.currentFiles = 0;
        this.totalFiles = 0;
    }

    AppLoader.prototype.__create = function( app )
    {
        this.app = app;
        this.create && this.create();
    };

    AppLoader.prototype.__onDone = function( cbOnDone )
    {
        this.onDone && this.onDone();
        cbOnDone && cbOnDone();
    };

    AppLoader.prototype.__onStart = function( current, total )
    {
        this.currentFiles = current;
        this.totalFiles = total;

        this.onStart && this.onStart( current, total );
    };
    AppLoader.prototype.__onProgress = function( current, total )
    {
        this.onProgress && this.onProgress( current, total );
    };
    AppLoader.prototype.__onError = function( error, file )
    {
        this.onError && this.onError( error, file );
    };

    function Detector()
    {

    }

    Detector.prototype.isIE = function()
    {
        const ua = navigator.userAgent;
        /* MSIE used to detect old browsers and Trident used to newer ones*/
        return ( ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1 );
    };

    // Note
    // This requires jQuery

    const Form = {
        /**
         * Simple native bootstrap approach to validate form
         * @param $form
         */
        bootstrapValidate : function( $form )
        {
            Form.trimFormInputs( $form );
            var isValid = $form.get(0).checkValidity();
            $form.addClass( 'was-validated' );

            return isValid;
        }

        ,

        trimFormInputs : function( $form )
        {
            if ( !$form || !$form.length ) return;

            $form.find( 'input' ).each( function()
            {
                // Skip file inputs
                if ( 'file' === $(this).attr( 'type' ) )
                {
                    return true;
                }

                $(this).val( trim( $(this).val() ) );
            });
        }

        ,

        disableAutoSubmit : function( $form )
        {
            $form.submit( function() {
                return false;
            });
        }

        ,

        scrollInvalidIntoView : function( $form, offset = 0 )
        {
            if ( $form.find( '.form-control:invalid' ).first().length )
            {
                let elem = $form.find( '.form-control:invalid' ).first().get( 0 );
                let y = elem.getBoundingClientRect().top + window.pageYOffset + offset;
                window.scrollTo( { top: y, behavior : 'smooth'} );
            }
        },

        getFormData : function ( $form  )
        {
            if ( !$form || !$form.length ) return null;

            var disabled = $form.find(':input:disabled').removeAttr('disabled'),
                arr = $form.serializeArray(),
                data = {};
            for ( var ai = 0; ai < arr.length; ai++ )
            {
                data[ arr[ ai ].name ] = trim( arr[ ai ].value );
            }

            disabled.attr('disabled','disabled');

            return data;
        }

        ,

        getInvalidInputs : function( $form, cv )
        {
            var inputs = $form.find('[data-validate]'),
                $invalidInputs = [];


            $.each(inputs, function (i, input)
            {
                var $input = $(input);


                if (false === isValidInput($input))
                {
                    $invalidInputs.push($input);
                }

            });

            return $invalidInputs;
        }

        ,

        getValidationInputs : function( $form )
        {
            return $form.find( '[data-validate]' );
        }

        ,

        isValidInput : function( $input, customValidators )
        {
            var $input = $($input),
                val, regex,
                customValidators = customValidators || {};

            // Dont process invisble items
            if (false == $input.is(':visible')) return true;

            if ('checkbox' === $input.attr('type'))
            {
                if ($input.is('[data-validate-required]'))
                {
                    if (false === $input.is(':checked'))
                    {
                        return false;
                    }
                }
            }
            else if ('file' === $input.attr('type') && false === $input.is('[data-validate-custom'))
            {
                // If FileReader does not exists - we mark file as valid since we have no way to validate it
                if (typeof FileReader === "undefined") return true;

                if ($input.is('[data-max-filesize]'))
                {
                    if ($input.get(0).files.length === 0) return true;
                    return ($input.get(0).files[0].size < parseInt($input.attr('data-max-filesize')));
                }
            }
            else {

                if ($input.is('[data-validate-regex]'))
                {
                    val = $input.val();
                    regex = new RegExp(eval($input.attr('data-validate-regex')));
                    if ( !val.match( regex ) )
                    {
                        return false;
                    }
                }

                else if ( $input.is('[data-validate-email]' ) )
                {
                    val = $input.val();
                    regex = new RegExp(eval("/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;"));
                    if ( !val.match( ) )
                    {
                        return false;
                    }
                }

                else if ($input.is('[data-validate-required]'))
                {
                    val = $input.val().trim();
                    if (val.length === 0)
                    {
                        return false;
                    }
                }

                else if ($input.is('[data-validate-custom'))
                {
                    if (customValidators.hasOwnProperty( $input.attr( 'data-validate-custom' ) ) &&
                        "function" === typeof customValidators[ $input.attr( 'data-validate-custom' ) ] )
                    {
                        if ( false === customValidators[ $input.attr( 'data-validate-custom' ) ]( $input ) )
                        {
                            return false;
                        }
                    }
                }

            }

            return true;
        }

        ,

        markInputAsValid : function( $input )
        {
            // Normal form group input field
            if ( $input.closest( 'div.form-group' ).length > 0 )
            {
                $input.closest( 'div.form-group' ).first().removeClass('has-error').addClass('has-success').addClass('has-feedback');
                if ( $input.next('span.glyphicon ').length !== 0 )
                {
                    $input.next('span.glyphicon ').removeClass('glyphicon-remove').addClass('glyphicon-ok');
                }
                else
                {
                    $('<span class="glyphicon glyphicon-ok form-control-feedback"></span>').insertAfter( $input );
                }
                if ($input.nextAll('small.help-block').length !== 0 )
                {
                    $input.nextAll('small.help-block').remove();
                }
            }
            else if ( $input.parent( 'div').hasClass( 'input-group') )
            {
                // Input field with addon
                $input.parent('div.input-group').removeClass('has-error').addClass('has-success');
                $input.parent('div.input-group').parent('div.form-group').removeClass('has-error').addClass('has-success');
                if ( $input.parent( 'div.input-group' ).nextAll('small.help-block').length !== 0 )
                {
                    $input.parent( 'div.input-group' ).nextAll('small.help-block').remove();
                }

            }
        }
        ,

        markInputAsInvalid : function( $input )
        {
            // Error
            if ( $input.attr( 'type' ) == "checkbox" )
                ;
            else
            {
                // Normal form group input field
                if ( $input.closest( 'div.form-group' ).length > 0 )
                {
                    $input.closest( 'div.form-group' ).first().removeClass('has-success').addClass('has-error').addClass('has-feedback');
                    if ( $input.next('span.glyphicon ').length !== 0 )
                    {
                        $input.next('span.glyphicon ').removeClass('glyphicon-ok').addClass('glyphicon-remove');
                    }
                    else
                    {
                        $( '<span class="glyphicon glyphicon-remove form-control-feedback"></span>').insertAfter( $input );
                    }

                    if ( $input.is("[data-validate-msg]") && $input.nextAll('small.help-block').length === 0 )
                    {
                        $('<small class="help-block">' + $input.attr('data-validate-msg') + '</small>').insertAfter( $input.next('span.glyphicon ') );
                    }
                }
                else if ( $input.parent( 'div').hasClass( 'input-group') )
                {
                    // Input Fields with addons
                    $input.parent('div.input-group').removeClass('has-success').addClass('has-error');
                    $input.parent('div.input-group').parent('div.form-group').removeClass('has-success').addClass('has-error');
                    if ( $input.is("[data-validate-msg]") && $input.parent( 'div.input-group' ).nextAll('small.help-block').length === 0 )
                    {
                        $('<small class="help-block">' + $input.attr('data-validate-msg') + '</small>').insertAfter( $input.parent( 'div.input-group' ) );
                    }
                }
            }
        }

        ,

        validateForm : function( $form, customValidators )
        {
            var $inputs = this.getValidationInputs( $form ),
                isFormValid = true,
                $input;

            if ( $inputs && $inputs.length )
            {
                for ( var vi = 0; vi < $inputs.length; vi++ )
                {
                    $input = $( $inputs[ vi ] );

                    if ( this.isValidInput( $input, customValidators ) )
                    {
                        this.markInputAsValid( $input );
                    }
                    else
                    {
                        isFormValid = false;

                        this.markInputAsInvalid( $input );

                    }
                }
            }

            return isFormValid;
        }
    };

    const apps = {};
    function createApp( id, container = null, appBody = {}, appConfig =  {} )
    {
        if ( !id )
        {
            throw new Error( 'Invalid/no app id given.' );
        }

        if ( !container && !( container instanceof HTMLElement ) )
        {
            throw new Error( 'No or invalid container given.' );
        }

        let app = new App( appConfig );
        app = applyBodyToObject( app, appBody );
        app.container = container;
        app.__id = id;
        app.storage.namespace = app.__id;

        apps[ id ] = app;

        return app;
    }

    function getApp( id )
    {
        let app = null;

        for ( let ai = 0; ai < apps.length; ai++ )
        {
            if ( apps[ ai ].__id === id )
            {
                app = apps[ ai ];
                break;
            }
        }

        return app;
    }

    function createAppLoader( appLoaderBody )
    {
        let appLoader = new AppLoader();
        appLoader = applyBodyToObject( appLoader, appLoaderBody );

        return appLoader;
    }

    function App( props = {} )
    {
        Base.call( this, this );

        const defaultConfig = {
            title : 'InFront.js',
            resources : {
                css : []
            },
            appLoader : null,
            localization : {
                defaultLanguage : 'en',
                dictionaryUrl : null
            },
            server : {}
        };

        this.config = Object.assign( defaultConfig, props );

        this.errorHandler = new ErrorHandler( this );
        this.controller = new Controller( this );
        this.classManager = new ClassManager( this );
        this.componentManager = new ComponentManager( this );
        this.localization = new Localization( this );
        this.storage = new Storage();
        this.resourceLoader = new ResourceLoader( this );
        this.resourceManager = new ResourceManager( this );
        this.viewManager = new ViewManager( this );
        this.detector = new Detector();

        if ( this.config.appLoader )
        {
            this.config.appLoader.__create( this );
        }

        // Utils
        this.util = {
            Form : Form
        };
    }

    // Inheritance
    App.prototype = Object.create( Base.prototype );
    App.prototype.constructor = App;

    // Proto properties
    App.prototype.addView = function( viewId, viewBody )
    {
        this.viewManager.add( viewId, viewBody );
    };

    App.prototype.create = function()
    {
        return true;
    };

    App.prototype.addClass = function( classId, classBody )
    {
        this.classManager.add( classId, classBody );
    };

    App.prototype.createInstance = function( classId, props = {} )
    {
        return this.classManager.create( classId, props );
    };

    App.prototype.addComponent = function( componentId, componentBody )
    {
        this.componentManager.add( componentId, componentBody );
    };

    App.prototype.createComponent = function( componentId, container = null, props = {} )
    {
        return this.componentManager.create( componentId, container, props );
    };

    App.prototype.createXhr = function( props = {} )
    {
        return new Xhr( props );
    };

    App.prototype.run = function()
    {
        document.title= this.config.title;
        this.resourceLoader.load( function()
            {
                this.localization.__create();
                if ( this.create && true === this.create() )
                {
                    this.controller.enable();
                }
            }.bind( this )
        );
    };
    App.prototype.onBadRequest      = function( error ) { console.log( 400, error ); };
    App.prototype.onUnauthorized    = function( error ) { console.log( 401, error ); };
    App.prototype.onPaymentRequired = function( error ) { console.log( 402, error ); };
    App.prototype.onForbidden       = function( error ) { console.log( 403, error ); };
    App.prototype.onNotFound        = function( error ) { console.log( 404, error ); };
    App.prototype.onGeneralError    = function( error ) { console.log( 500, error ); };

    const version = "2.5.3";

    // Marketing ;-)
    console.log( "%c»InFront.js« Version " + version, "font-family: monospace sans-serif; background-color: black; color: white;" );

    exports.createApp = createApp;
    exports.createAppLoader = createAppLoader;
    exports.createParams = createParams;
    exports.getApp = getApp;
    exports.version = version;

    Object.defineProperty(exports, '__esModule', { value: true });

})));
