(function () {/**
 * almond 0.2.6 Copyright (c) 2011-2012, The Dojo Foundation All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/jrburke/almond for details
 */
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*jslint sloppy: true */
/*global setTimeout: false */

var requirejs, require, define;
(function (undef) {
    var main, req, makeMap, handlers,
        defined = {},
        waiting = {},
        config = {},
        defining = {},
        hasOwn = Object.prototype.hasOwnProperty,
        aps = [].slice;

    function hasProp(obj, prop) {
        return hasOwn.call(obj, prop);
    }

    /**
     * Given a relative module name, like ./something, normalize it to
     * a real name that can be mapped to a path.
     * @param {String} name the relative name
     * @param {String} baseName a real name that the name arg is relative
     * to.
     * @returns {String} normalized name
     */
    function normalize(name, baseName) {
        var nameParts, nameSegment, mapValue, foundMap,
            foundI, foundStarMap, starI, i, j, part,
            baseParts = baseName && baseName.split("/"),
            map = config.map,
            starMap = (map && map['*']) || {};

        //Adjust any relative paths.
        if (name && name.charAt(0) === ".") {
            //If have a base name, try to normalize against it,
            //otherwise, assume it is a top-level require that will
            //be relative to baseUrl in the end.
            if (baseName) {
                //Convert baseName to array, and lop off the last part,
                //so that . matches that "directory" and not name of the baseName's
                //module. For instance, baseName of "one/two/three", maps to
                //"one/two/three.js", but we want the directory, "one/two" for
                //this normalization.
                baseParts = baseParts.slice(0, baseParts.length - 1);

                name = baseParts.concat(name.split("/"));

                //start trimDots
                for (i = 0; i < name.length; i += 1) {
                    part = name[i];
                    if (part === ".") {
                        name.splice(i, 1);
                        i -= 1;
                    } else if (part === "..") {
                        if (i === 1 && (name[2] === '..' || name[0] === '..')) {
                            //End of the line. Keep at least one non-dot
                            //path segment at the front so it can be mapped
                            //correctly to disk. Otherwise, there is likely
                            //no path mapping for a path starting with '..'.
                            //This can still fail, but catches the most reasonable
                            //uses of ..
                            break;
                        } else if (i > 0) {
                            name.splice(i - 1, 2);
                            i -= 2;
                        }
                    }
                }
                //end trimDots

                name = name.join("/");
            } else if (name.indexOf('./') === 0) {
                // No baseName, so this is ID is resolved relative
                // to baseUrl, pull off the leading dot.
                name = name.substring(2);
            }
        }

        //Apply map config if available.
        if ((baseParts || starMap) && map) {
            nameParts = name.split('/');

            for (i = nameParts.length; i > 0; i -= 1) {
                nameSegment = nameParts.slice(0, i).join("/");

                if (baseParts) {
                    //Find the longest baseName segment match in the config.
                    //So, do joins on the biggest to smallest lengths of baseParts.
                    for (j = baseParts.length; j > 0; j -= 1) {
                        mapValue = map[baseParts.slice(0, j).join('/')];

                        //baseName segment has  config, find if it has one for
                        //this name.
                        if (mapValue) {
                            mapValue = mapValue[nameSegment];
                            if (mapValue) {
                                //Match, update name to the new value.
                                foundMap = mapValue;
                                foundI = i;
                                break;
                            }
                        }
                    }
                }

                if (foundMap) {
                    break;
                }

                //Check for a star map match, but just hold on to it,
                //if there is a shorter segment match later in a matching
                //config, then favor over this star map.
                if (!foundStarMap && starMap && starMap[nameSegment]) {
                    foundStarMap = starMap[nameSegment];
                    starI = i;
                }
            }

            if (!foundMap && foundStarMap) {
                foundMap = foundStarMap;
                foundI = starI;
            }

            if (foundMap) {
                nameParts.splice(0, foundI, foundMap);
                name = nameParts.join('/');
            }
        }

        return name;
    }

    function makeRequire(relName, forceSync) {
        return function () {
            //A version of a require function that passes a moduleName
            //value for items that may need to
            //look up paths relative to the moduleName
            return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
        };
    }

    function makeNormalize(relName) {
        return function (name) {
            return normalize(name, relName);
        };
    }

    function makeLoad(depName) {
        return function (value) {
            defined[depName] = value;
        };
    }

    function callDep(name) {
        if (hasProp(waiting, name)) {
            var args = waiting[name];
            delete waiting[name];
            defining[name] = true;
            main.apply(undef, args);
        }

        if (!hasProp(defined, name) && !hasProp(defining, name)) {
            throw new Error('No ' + name);
        }
        return defined[name];
    }

    //Turns a plugin!resource to [plugin, resource]
    //with the plugin being undefined if the name
    //did not have a plugin prefix.
    function splitPrefix(name) {
        var prefix,
            index = name ? name.indexOf('!') : -1;
        if (index > -1) {
            prefix = name.substring(0, index);
            name = name.substring(index + 1, name.length);
        }
        return [prefix, name];
    }

    function onResourceLoad(name, defined, deps){
        if(requirejs.onResourceLoad && name){
            requirejs.onResourceLoad({defined:defined}, {id:name}, deps);
        }
    }

    /**
     * Makes a name map, normalizing the name, and using a plugin
     * for normalization if necessary. Grabs a ref to plugin
     * too, as an optimization.
     */
    makeMap = function (name, relName) {
        var plugin,
            parts = splitPrefix(name),
            prefix = parts[0];

        name = parts[1];

        if (prefix) {
            prefix = normalize(prefix, relName);
            plugin = callDep(prefix);
        }

        //Normalize according
        if (prefix) {
            if (plugin && plugin.normalize) {
                name = plugin.normalize(name, makeNormalize(relName));
            } else {
                name = normalize(name, relName);
            }
        } else {
            name = normalize(name, relName);
            parts = splitPrefix(name);
            prefix = parts[0];
            name = parts[1];
            if (prefix) {
                plugin = callDep(prefix);
            }
        }

        //Using ridiculous property names for space reasons
        return {
            f: prefix ? prefix + '!' + name : name, //fullName
            n: name,
            pr: prefix,
            p: plugin
        };
    };

    function makeConfig(name) {
        return function () {
            return (config && config.config && config.config[name]) || {};
        };
    }

    handlers = {
        require: function (name) {
            return makeRequire(name);
        },
        exports: function (name) {
            var e = defined[name];
            if (typeof e !== 'undefined') {
                return e;
            } else {
                return (defined[name] = {});
            }
        },
        module: function (name) {
            return {
                id: name,
                uri: '',
                exports: defined[name],
                config: makeConfig(name)
            };
        }
    };

    main = function (name, deps, callback, relName) {
        var cjsModule, depName, ret, map, i,
            args = [],
            usingExports;

        //Use name if no relName
        relName = relName || name;

        //Call the callback to define the module, if necessary.
        if (typeof callback === 'function') {

            //Pull out the defined dependencies and pass the ordered
            //values to the callback.
            //Default to [require, exports, module] if no deps
            deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
            for (i = 0; i < deps.length; i += 1) {
                map = makeMap(deps[i], relName);
                depName = map.f;

                //Fast path CommonJS standard dependencies.
                if (depName === "require") {
                    args[i] = handlers.require(name);
                } else if (depName === "exports") {
                    //CommonJS module spec 1.1
                    args[i] = handlers.exports(name);
                    usingExports = true;
                } else if (depName === "module") {
                    //CommonJS module spec 1.1
                    cjsModule = args[i] = handlers.module(name);
                } else if (hasProp(defined, depName) ||
                           hasProp(waiting, depName) ||
                           hasProp(defining, depName)) {
                    args[i] = callDep(depName);
                } else if (map.p) {
                    map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                    args[i] = defined[depName];
                } else {
                    throw new Error(name + ' missing ' + depName);
                }
            }

            ret = callback.apply(defined[name], args);

            if (name) {
                //If setting exports via "module" is in play,
                //favor that over return value and exports. After that,
                //favor a non-undefined return value over exports use.
                if (cjsModule && cjsModule.exports !== undef &&
                        cjsModule.exports !== defined[name]) {
                    defined[name] = cjsModule.exports;
                } else if (ret !== undef || !usingExports) {
                    //Use the return value from the function.
                    defined[name] = ret;
                }
            }
        } else if (name) {
            //May just be an object definition for the module. Only
            //worry about defining if have a module name.
            defined[name] = callback;
        }

        onResourceLoad(name, defined, args);
    };

    requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
        if (typeof deps === "string") {
            if (handlers[deps]) {
                //callback in this case is really relName
                return handlers[deps](callback);
            }
            //Just return the module wanted. In this scenario, the
            //deps arg is the module name, and second arg (if passed)
            //is just the relName.
            //Normalize module name, if it contains . or ..
            return callDep(makeMap(deps, callback).f);
        } else if (!deps.splice) {
            //deps is a config object, not an array.
            config = deps;
            if (callback.splice) {
                //callback is an array, which means it is a dependency list.
                //Adjust args if there are dependencies
                deps = callback;
                callback = relName;
                relName = null;
            } else {
                deps = undef;
            }
        }

        //Support require(['a'])
        callback = callback || function () {};

        //If relName is a function, it is an errback handler,
        //so remove it.
        if (typeof relName === 'function') {
            relName = forceSync;
            forceSync = alt;
        }

        //Simulate async callback;
        if (forceSync) {
            main(undef, deps, callback, relName);
        } else {
            //Using a non-zero value because of concern for what old browsers
            //do, and latest browsers "upgrade" to 4 if lower value is used:
            //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
            //If want a value immediately, use require('id') instead -- something
            //that works in almond on the global level, but not guaranteed and
            //unlikely to work in other AMD implementations.
            setTimeout(function () {
                main(undef, deps, callback, relName);
            }, 4);
        }

        return req;
    };

    /**
     * Just drops the config on the floor, but returns req in case
     * the config return value is used.
     */
    req.config = function (cfg) {
        config = cfg;
        if (config.deps) {
            req(config.deps, config.callback);
        }
        return req;
    };

    /**
     * Expose module registry for debugging and tooling
     */
    requirejs._defined = defined;

    define = function (name, deps, callback) {

        //This module may not have dependencies
        if (!deps.splice) {
            //deps is not an array, so probably means
            //an object literal or factory function for
            //the value. Adjust args.
            callback = deps;
            deps = [];
        }

        if (!hasProp(defined, name) && !hasProp(waiting, name)) {
            waiting[name] = [name, deps, callback];
        }
    };

    define.amd = {
        jQuery: true
    };
}());

define("../Scripts/almond-custom", function(){});

define('core/constants',["require", "exports"], function (require, exports) {
    exports.services = {
        serviceBaseUrl: app.hostUrl + 'api/',
        breezeServiceBaseUrl: app.hostUrl + 'bapi/'
    };
    exports.globalization = {
        defaultCulture: 'en-US',
        defaultTimeZone: 'Eastern Standard Time'
    };
    exports.ajax = {
        maxAttempts: 3,
        defaultTimeout: 6000000,
        timeoutTextStatus: 'timeout'
    };
    exports.connection = {
        unknown: 'Unknown',
        connected: 'Connected',
        timingOut: 'Timing Out',
        disconnected: 'Disconnected'
    };
    exports.guid = {
        empty: '00000000-0000-0000-0000-000000000000',
        regex: /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i,
    };
    exports.date = {
        min: new Date(1850, 0, 1),
        max: new Date(2250, 11, 31),
    };
    exports.email = {
        regex: /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
    };
    exports.customHeaderFooter = {
        MAWebIntakeResources: 'MAWebIntakeResources',
        MAWebIntakeResourcesVisible: 'MAWebIntakeResourcesVisible',
        MAWebIntakeHeader: 'MAWebIntakeHeader',
        MAWebIntakeHeaderVisible: 'MAWebIntakeHeaderVisible',
        MAWebIntakeFooter: 'MAWebIntakeFooter',
        MAWebIntakeFooterVisible: 'MAWebIntakeFooterVisible',
    };
});

define('core/util',["require", "exports", 'core/constants'], function (require, exports, constants) {
    var NetworkError = (function () {
        function NetworkError(reason) {
            if (reason.hasOwnProperty('status'))
                this.status = reason.status;
            if (reason.hasOwnProperty('statusText'))
                this.statusText = reason.statusText;
            if (reason.hasOwnProperty('responseText'))
                this.responseText = reason.responseText;
            if (reason.hasOwnProperty('responseJSON'))
                this.responseJSON = reason.responseJSON;
            if (reason.hasOwnProperty('description'))
                this.description = reason.description;
            if (reason.hasOwnProperty('entityErrors'))
                this.entityErrors = reason.entityErrors;
            if (reason.hasOwnProperty('httpResponse'))
                this.httpResponse = reason.httpResponse;
            if (reason.hasOwnProperty('message'))
                this.message = reason.message;
        }
        NetworkError.prototype.toString = function () {
            var message = '';
            if (this.hasOwnProperty('status')) {
                message = this.status + ' - ' + this.statusText + ':';
            }
            if (this.hasOwnProperty('responseJSON')) {
                message += '\r\n';
                message += this.responseJSON.Message;
                if (this.responseJSON.hasOwnProperty('MessageDetail')) {
                    message += '\r\n';
                    message += this.responseJSON.MessageDetail;
                }
                else {
                    if (this.responseJSON.hasOwnProperty('ExceptionMessage')) {
                        message += '\r\n';
                        message += this.responseJSON.ExceptionMessage;
                    }
                    if (this.responseJSON.hasOwnProperty('StackTrace')) {
                        message += '\r\n';
                        message += 'Stack Trace: ' + this.responseJSON.StackTrace;
                    }
                }
                return message;
            }
            if (this.hasOwnProperty('description') && this.description.indexOf("Concurrent saves not allowed") != -1) {
                message += this.description;
            }
            if (this.hasOwnProperty('entityErrors')) {
                this.entityErrors.forEach(function (e) {
                    message += e.errorMessage + ' ';
                });
            }
            if (this.hasOwnProperty('httpResponse') && this.httpResponse.status === 500) {
                message = this.message;
            }
            return message;
        };
        NetworkError.prototype.isConnectionFailure = function (reason) {
            return isConnectionFailure(reason);
        };
        return NetworkError;
    })();
    exports.NetworkError = NetworkError;
    function isNullOrEmpty(value) {
        return value === null || value.length === 0;
    }
    function equalsIgnoreCase(stringA, stringB) {
        if (stringA === stringB)
            return true;
        if (stringA === null || stringB === null)
            return false;
        return stringA.toLowerCase && stringA.toLowerCase() === stringB.toLowerCase();
    }
    exports.equalsIgnoreCase = equalsIgnoreCase;
    function guidEqual(guidA, guidB) {
        return equalsIgnoreCase(normalizeGuid(guidA), normalizeGuid(guidB));
    }
    exports.guidEqual = guidEqual;
    function normalizeGuid(guid) {
        if (guid && guid.replace)
            return guid.replace(/^\{|\}$/g, '').toLowerCase();
        return guid;
    }
    exports.normalizeGuid = normalizeGuid;
    function isGuidNullOrEmpty(guid) {
        return guid === null || guidEqual(guid, constants.guid.empty);
    }
    exports.isGuidNullOrEmpty = isGuidNullOrEmpty;
    function recurse(value, next) {
        var items = [], addNext = function () {
            if (typeof value === 'undefined' || value === null)
                return;
            items.push(value);
            value = next(value);
            addNext();
        };
        addNext();
        return items;
    }
    exports.recurse = recurse;
    function htmlEncode(str) {
        return String(str).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }
    exports.htmlEncode = htmlEncode;
    function getDate() {
        var now = new Date();
        now.setHours(0, 0, 0, 0);
        return now;
    }
    exports.getDate = getDate;
    function getOrigin(url) {
        var pathArray = url.split('/'), protocol = pathArray[0], host = pathArray[2], origin = protocol + '//' + host;
        return origin;
    }
    exports.getOrigin = getOrigin;
    function ensureUrlHasTrailingBackslash() {
        if (/^.*\/$/.test(location.pathname))
            return;
        location.assign(getOrigin(window.location.href) + location.pathname + '/');
    }
    exports.ensureUrlHasTrailingBackslash = ensureUrlHasTrailingBackslash;
    function compareVersions(versionA, versionB) {
        var regex = /^\d\.\d+\.\d+(\.\d+)?/;
        var regexWBuild = /^\d\.\d+\.\d+\.\d+/;
        if (!regex.test(versionA))
            throw new Error('Unable to parse version string: ' + versionA);
        if (!regex.test(versionB))
            throw new Error('Unable to parse version string: ' + versionB);
        if (regexWBuild.test(versionA) !== regexWBuild.test(versionB))
            throw new Error('One version string contains the build version and the other does not: ' + versionA + '; ' + versionB);
        var a = (versionA + '.0').split('.');
        var b = (versionB + '.0').split('.');
        var i = 0;
        while (i < 3 && a[i] === b[i]) {
            i++;
        }
        var x = parseInt(a[i]);
        var y = parseInt(b[i]);
        if (x === y)
            return 0;
        if (x > y)
            return 1;
        return -1;
    }
    exports.compareVersions = compareVersions;
    function escapeRegExp(str) {
        return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }
    exports.escapeRegExp = escapeRegExp;
    function replaceAll(find, replace, str) {
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }
    exports.replaceAll = replaceAll;
    function stringComparisonOrdinalIgnoreCase(a, b) {
        if (a === null)
            a = '';
        if (b === null)
            b = '';
        a = a.toLowerCase();
        b = b.toLowerCase();
        if (a < b)
            return -1;
        if (a > b)
            return 1;
        return 0;
    }
    exports.stringComparisonOrdinalIgnoreCase = stringComparisonOrdinalIgnoreCase;
    function dateComparison(a, b) {
        if (a === null)
            a = new Date(1900, 0, 1);
        if (b === null)
            b = new Date(1900, 0, 1);
        return moment(b).diff(moment(a));
    }
    exports.dateComparison = dateComparison;
    function isConnectionFailure(obj) {
        var result = obj && obj.hasOwnProperty('status') && (obj.status === 0 || obj.status === 404) && (obj.hasOwnProperty('readyState') && obj.hasOwnProperty('statusText') || obj.hasOwnProperty('httpResponse'));
        return result;
    }
    exports.isConnectionFailure = isConnectionFailure;
    function getDomainException(obj) {
        var error = getDotNetException(obj);
        if (error === null || error.ExceptionType !== 'System.ServiceModel.DomainServices.Server.DomainException')
            return null;
        return error;
    }
    exports.getDomainException = getDomainException;
    function getDotNetException(obj) {
        if (obj && obj.hasOwnProperty('status') && obj.status === 500 && obj.responseJSON && obj.responseJSON.ExceptionMessage && obj.responseJSON.ExceptionType && obj.responseJSON.StackTrace) {
            return obj.responseJSON;
        }
        return null;
    }
    exports.getDotNetException = getDotNetException;
    function deparam(query) {
        var match, pl = /\+/g, search = /([^&=]+)=?([^&]*)/g, decode = function (s) {
            return decodeURIComponent(s.replace(pl, " "));
        }, urlParams = {};
        while (match = search.exec(query))
            urlParams[decode(match[1])] = decode(match[2]);
        return urlParams;
    }
    exports.deparam = deparam;
    function deleteById(id, controllerAndMethod) {
        return Q($.post(constants.services.breezeServiceBaseUrl + controllerAndMethod + '?id=' + id));
    }
    exports.deleteById = deleteById;
    var Arrays = (function () {
        function Arrays() {
        }
        Arrays.toIndex = function (array, key, value) {
            var i = array.length, item, index = {};
            value = value || (function (v) { return v; });
            while (i--) {
                item = array[i];
                index[key(item)] = value(item);
            }
            return index;
        };
        Arrays.isArray = function (value) {
            return Object.prototype.toString.apply(value, []) === '[object Array]';
        };
        Arrays.sequenceEquals = function (array1, array2, equals) {
            if (array1 === array2) {
                return true;
            }
            if (array1 === null || array2 === null) {
                return false;
            }
            if (array1.length !== array2.length) {
                return false;
            }
            for (var i = 0, n = array1.length; i < n; i++) {
                if (!equals(array1[i], array2[i])) {
                    return false;
                }
            }
            return true;
        };
        Arrays.contains = function (array, value) {
            for (var i = 0; i < array.length; i++) {
                if (array[i] === value) {
                    return true;
                }
            }
            return false;
        };
        Arrays.distinct = function (array, equalsFn) {
            var result = [];
            if (!equalsFn) {
                equalsFn = function (a, b) { return a === b; };
            }
            for (var i = 0, n = array.length; i < n; i++) {
                var current = array[i];
                for (var j = 0; j < result.length; j++) {
                    if (equalsFn(result[j], current)) {
                        break;
                    }
                }
                if (j === result.length) {
                    result.push(current);
                }
            }
            return result;
        };
        Arrays.distinctFast = function (array, keySelector) {
            var result = [], dictionary = {}, current, key;
            if (!keySelector) {
                keySelector = function (item) { return item.toString(); };
            }
            for (var i = 0, n = array.length; i < n; i++) {
                current = array[i];
                key = keySelector(current);
                if (dictionary.hasOwnProperty(key))
                    continue;
                dictionary[key] = 1;
                result.push(current);
            }
            return result;
        };
        Arrays.min = function (array, func) {
            var min = func(array[0]);
            for (var i = 1; i < array.length; i++) {
                var next = func(array[i]);
                if (next < min) {
                    min = next;
                }
            }
            return min;
        };
        Arrays.max = function (array, func) {
            var max = func(array[0]);
            for (var i = 1; i < array.length; i++) {
                var next = func(array[i]);
                if (next > max) {
                    max = next;
                }
            }
            return max;
        };
        Arrays.last = function (array) {
            if (array.length === 0) {
                throw 'array is empty';
            }
            return array[array.length - 1];
        };
        Arrays.lastOrDefault = function (array, predicate) {
            for (var i = array.length - 1; i >= 0; i--) {
                var v = array[i];
                if (predicate(v, i)) {
                    return v;
                }
            }
            return null;
        };
        Arrays.firstOrDefault = function (array, func) {
            for (var i = 0, n = array.length; i < n; i++) {
                var value = array[i];
                if (!func || func(value, i)) {
                    return value;
                }
            }
            return null;
        };
        Arrays.first = function (array, func) {
            for (var i = 0, n = array.length; i < n; i++) {
                var value = array[i];
                if (!func || func(value, i)) {
                    return value;
                }
            }
            throw 'array is empty';
        };
        Arrays.sum = function (array, func) {
            var result = 0;
            for (var i = 0, n = array.length; i < n; i++) {
                result += func(array[i]);
            }
            return result;
        };
        Arrays.select = function (values, func) {
            var result = new Array(values.length);
            for (var i = 0; i < values.length; i++) {
                result[i] = func(values[i]);
            }
            return result;
        };
        Arrays.where = function (values, func) {
            var result = new Array();
            for (var i = 0; i < values.length; i++) {
                if (func(values[i])) {
                    result.push(values[i]);
                }
            }
            return result;
        };
        Arrays.any = function (array, func) {
            for (var i = 0, n = array.length; i < n; i++) {
                if (func(array[i])) {
                    return true;
                }
            }
            return false;
        };
        Arrays.all = function (array, func) {
            for (var i = 0, n = array.length; i < n; i++) {
                if (!func(array[i])) {
                    return false;
                }
            }
            return true;
        };
        Arrays.binarySearch = function (array, value) {
            var low = 0;
            var high = array.length - 1;
            while (low <= high) {
                var middle = low + ((high - low) >> 1);
                var midValue = array[middle];
                if (midValue === value) {
                    return middle;
                }
                else if (midValue > value) {
                    high = middle - 1;
                }
                else {
                    low = middle + 1;
                }
            }
            return ~low;
        };
        Arrays.createArray = function (length, defaultValue) {
            var result = new Array(length);
            for (var i = 0; i < length; i++) {
                result[i] = defaultValue;
            }
            return result;
        };
        Arrays.grow = function (array, length, defaultValue) {
            var count = length - array.length;
            for (var i = 0; i < count; i++) {
                array.push(defaultValue);
            }
        };
        Arrays.copy = function (sourceArray, sourceIndex, destinationArray, destinationIndex, length) {
            for (var i = 0; i < length; i++) {
                destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i];
            }
        };
        Arrays.indexOf = function (array, predicate) {
            for (var i = 0, n = array.length; i < n; i++) {
                if (predicate(array[i])) {
                    return i;
                }
            }
            return -1;
        };
        Arrays.selectMany = function (array, callbackfn, thisArg) {
            var apply = Function.prototype.apply;
            var flatten = apply.bind(Array.prototype.concat, []);
            return flatten(array.map(callbackfn, thisArg));
        };
        Arrays.groupBy = function (array, callbackfn, thisArg) {
            var dictionary = {}, results = [], i, max = array.length, key, keyString;
            for (i = 0; i < max; i++) {
                key = callbackfn.apply(thisArg, [array[i], i, array]);
                if (key === null)
                    keyString = '<null>';
                else
                    keyString = key.toString();
                if (dictionary.hasOwnProperty(keyString)) {
                    dictionary[keyString].push(array[i]);
                    continue;
                }
                dictionary[keyString] = [array[i]];
                dictionary[keyString].key = key;
                results.push(dictionary[keyString]);
            }
            return results;
        };
        return Arrays;
    })();
    exports.Arrays = Arrays;
    function getAge(dob) {
        return Math.floor(moment().diff(moment(dob), 'year', false));
    }
    exports.getAge = getAge;
    function removeOffsetFromDate(d) {
        var tzOffSet = d.getTimezoneOffset();
        return new Date(d.getTime() + tzOffSet * 60 * 1000);
    }
    exports.removeOffsetFromDate = removeOffsetFromDate;
    if (!window.hasOwnProperty('equalsIgnoreCase')) {
        window['isNullOrEmpty'] = isNullOrEmpty;
        window['equalsIgnoreCase'] = equalsIgnoreCase;
        window['guidEqual'] = guidEqual;
        window['normalizeGuid'] = normalizeGuid;
        window['getDate'] = getDate;
        window['isGuidNullOrEmpty'] = isGuidNullOrEmpty;
        window['htmlEncode'] = htmlEncode;
    }
    if (!String.prototype['format']) {
        String.prototype['format'] = function () {
            var args = arguments;
            return this.replace(/{(\d+)}/g, function (match, number) { return typeof args[number] != 'undefined' ? args[number] : match; });
        };
    }
    exports.dmsUploadFileModel = {
        dmsUploadFile: ko.observable(null)
    };
    function isValidFileName(fileName) {
        var isValid = true;
        var rexp = /^[0-9A-Za-z\_\-\ ]+$/;
        if (!rexp.test(fileName.substring(0, fileName.lastIndexOf('.')))) {
            isValid = false;
        }
        return isValid;
    }
    exports.isValidFileName = isValidFileName;
    function setCFWebIntakePageTitle() {
        if (!app.CFWebIntakePageTitle) {
            return;
        }
        document.title = app.CFWebIntakePageTitle;
    }
    exports.setCFWebIntakePageTitle = setCFWebIntakePageTitle;
    function setCustomHeaderAndFooter() {
        var integrationParameterUrl = app.hostUrl + "/api/IntegrationParameter/GetCustomHeaderAndFooter";
        $.get(integrationParameterUrl, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        }).then(function (response) {
            if (!response) {
                return;
            }
            var resources = getParameterValue(response, constants.customHeaderFooter.MAWebIntakeResources, constants.customHeaderFooter.MAWebIntakeResourcesVisible);
            if (resources) {
                var head = document.head || document.getElementsByTagName('head')[0];
                head.innerHTML += resources;
            }
            var header = getParameterValue(response, constants.customHeaderFooter.MAWebIntakeHeader, constants.customHeaderFooter.MAWebIntakeHeaderVisible);
            if (header) {
                var custom_header = document.getElementById('custom_header');
                custom_header.insertAdjacentHTML('beforeend', header);
            }
            var footer = getParameterValue(response, constants.customHeaderFooter.MAWebIntakeFooter, constants.customHeaderFooter.MAWebIntakeFooterVisible);
            if (footer) {
                var custom_footer = document.getElementById('custom_footer');
                custom_footer.insertAdjacentHTML('beforeend', footer);
            }
        }).fail(function () {
            return;
        });
    }
    exports.setCustomHeaderAndFooter = setCustomHeaderAndFooter;
    function getParameterValue(parameters, parameterNameToGet, visibilityParameterName) {
        var isVisible = parameters.find(function (obj) { return obj.ParameterName === visibilityParameterName && obj.ParameterValue === 'true'; });
        if (isVisible) {
            var parameter = parameters.find(function (obj) { return obj.ParameterName === parameterNameToGet; });
            if (parameter) {
                return parameter.ParameterValue;
            }
        }
        return null;
    }
});

define('core/cycle',["require", "exports"], function (require, exports) {
    function decycle(object) {
        'use strict';
        var objects = [], paths = [];
        return (function derez(value, path) {
            var i, name, nu;
            if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) {
                for (i = 0; i < objects.length; i += 1) {
                    if (objects[i] === value) {
                        return { $ref: paths[i] };
                    }
                }
                objects.push(value);
                paths.push(path);
                if (Object.prototype.toString.apply(value) === '[object Array]') {
                    nu = [];
                    for (i = 0; i < value.length; i += 1) {
                        nu[i] = derez(value[i], path + '[' + i + ']');
                    }
                }
                else {
                    nu = {};
                    for (name in value) {
                        if (Object.prototype.hasOwnProperty.call(value, name)) {
                            nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']');
                        }
                    }
                }
                return nu;
            }
            return value;
        }(object, '$'));
    }
    exports.decycle = decycle;
    function retrocycle($) {
        'use strict';
        var px = /^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/;
        (function rez(value) {
            var i, item, name, path;
            if (value && typeof value === 'object') {
                if (Object.prototype.toString.apply(value) === '[object Array]') {
                    for (i = 0; i < value.length; i += 1) {
                        item = value[i];
                        if (item && typeof item === 'object') {
                            path = item.$ref;
                            if (typeof path === 'string' && px.test(path)) {
                                value[i] = eval(path);
                            }
                            else {
                                rez(item);
                            }
                        }
                    }
                }
                else {
                    for (name in value) {
                        if (typeof value[name] === 'object') {
                            item = value[name];
                            if (item) {
                                path = item.$ref;
                                if (typeof path === 'string' && px.test(path)) {
                                    value[name] = eval(path);
                                }
                                else {
                                    rez(item);
                                }
                            }
                        }
                    }
                }
            }
        }($));
        return $;
    }
    exports.retrocycle = retrocycle;
    function removeId(obj, handled) {
        var i;
        if (obj && typeof obj === 'object') {
            if (handled === undefined) {
                handled = [];
            }
            if (handled.indexOf(obj) !== -1) {
                return;
            }
            handled.push(obj);
            if (typeof obj.$id !== 'undefined') {
                delete obj.$id;
            }
            if (Object.prototype.toString.apply(obj) === '[object Array]') {
                for (i = 0; i < obj.length; i += 1) {
                    removeId(obj[i], handled);
                }
            }
            else {
                for (name in obj) {
                    if (obj[name] && typeof obj[name] === 'object') {
                        removeId(obj[name], handled);
                    }
                }
            }
        }
    }
    exports.removeId = removeId;
});

define('core/worker',["require", "exports"], function (require, exports) {
    var nextId = 0;
    var pendingTasks = [];
    var worker = new Worker(app.workerUrl);
    worker.addEventListener('message', handleMessage, false);
    function executeTaskAsync(task) {
        var id = getWorkNextId();
        task['_task_id'] = id;
        var deferred = Q.defer();
        pendingTasks['w' + id.toString()] = deferred;
        worker.postMessage(task);
        return deferred.promise;
    }
    exports.executeTaskAsync = executeTaskAsync;
    function handleMessage(event) {
        if (typeof event.data['_task_id'] === 'undefined')
            return;
        var id = event.data['_task_id'];
        var deferred = pendingTasks['w' + id.toString()];
        delete pendingTasks['w' + id.toString()];
        if (event.data.error)
            deferred.reject(event.data.error);
        else
            deferred.resolve(event.data);
    }
    function getWorkNextId() {
        var id = nextId;
        nextId++;
        return id;
    }
});

define('core/storage',["require", "exports", 'core/cycle', 'core/worker'], function (require, exports, cycle, worker) {
    var defaultOptions = { global: false, hipaa: false, shared: false };
    function normalizeOptions(options) {
        if (!options)
            return defaultOptions;
        return $.extend({}, defaultOptions, options);
    }
    function getKey(key, options) {
        if (key === null || key === '')
            throw 'key is required';
        key = key.toLowerCase();
        if (options.global)
            return 'global/' + key;
        if (!User.IsLoggedIn)
            throw 'the user must be logged in to use the non-global cache';
        var a = User.Current, userId = options.shared ? 'shared' : a.UserId;
        return (a.SqlServer + '/' + a.Database + '/' + userId + '/' + key).toLowerCase();
    }
    function getItem(key, options, shallow) {
        options = normalizeOptions(options);
        key = getKey(key, options);
        return Q(localforage.getItem(key)).then(function (value) { return value === null ? Q.reject(null) : value; }).then(function (data) {
            var firstPipe = data.indexOf('|');
            var secondPipe = data.indexOf('|', firstPipe + 1);
            var thirdPipe = data.indexOf('|', secondPipe + 1);
            var fourthPipe = data.indexOf('|', thirdPipe + 1);
            var date = moment(data.substring(0, firstPipe)).toDate();
            var version = data.substring(firstPipe + 1, secondPipe);
            var type = data.substring(secondPipe + 1, thirdPipe);
            var status = data.substring(thirdPipe + 1, fourthPipe);
            var data = data.substring(fourthPipe + 1);
            if (shallow) {
                return Q.resolve({
                    data: null,
                    type: type,
                    timestamp: date,
                    version: version,
                    status: status
                });
            }
            return worker.executeTaskAsync({ type: 'decompress', data: data, decrypt: options.hipaa }).then(function (task) {
                data = task.data;
                var object = data;
                switch (type) {
                    case 'number':
                    case 'string':
                    case 'boolean':
                        break;
                    default:
                        object = JSON.parse(data);
                        object = cycle.retrocycle(object);
                        break;
                }
                return Q.resolve({
                    data: object,
                    type: type,
                    timestamp: date,
                    version: version,
                    status: status
                });
            });
        }).fail(function (reason) {
            return Q.reject('key not found: ' + key);
        });
    }
    exports.getItem = getItem;
    function setItem(key, data, options, timestamp, asObject, status) {
        options = normalizeOptions(options);
        key = getKey(key, options);
        var type = typeof data;
        switch (type) {
            case 'number':
            case 'string':
            case 'boolean':
                break;
            default:
                try {
                    data = JSON.stringify(data);
                }
                catch (ex) {
                    data = cycle.decycle(data);
                    data = JSON.stringify(data);
                }
                break;
        }
        if (asObject) {
            type = 'object';
        }
        if (typeof status === 'undefined' || status === null) {
            status = '';
        }
        if (typeof status !== 'string') {
            status = status.toString();
        }
        return worker.executeTaskAsync({ type: 'compress', data: data, encrypt: options.hipaa }).then(function (task) {
            data = task.data;
            if (!timestamp) {
                timestamp = new Date();
            }
            data = moment(timestamp).toISOString() + '|' + app.shortVersion + '|' + type + '|' + status + '|' + data;
            return Q(localforage.setItem(key, data));
        });
    }
    exports.setItem = setItem;
    function removeItem(key, options) {
        options = normalizeOptions(options);
        key = getKey(key, options);
        var deferred = Q.defer();
        Q(localforage.removeItem(key)).then(function () {
            deferred.resolve(null);
        });
        return deferred.promise;
    }
    exports.removeItem = removeItem;
    function unlock(encryptionKey) {
        return worker.executeTaskAsync({ type: 'unlock', encryptionKey: encryptionKey });
    }
    exports.unlock = unlock;
});

define('entities/core',["require", "exports", 'core/storage'], function (require, exports, storage) {
    exports.versions = ko.observable([]);
    function updateVersions(newVersions) {
        exports.versions(newVersions);
        return storage.setItem('versions', newVersions, exports.storageOptions);
    }
    exports.updateVersions = updateVersions;
    exports.storageOptions = { global: false, hipaa: true };
    exports.isSyncing = ko.observable(false);
    function composeFullyQualifiedId(typeName, id) {
        return typeName + '/' + id.toString();
    }
    exports.composeFullyQualifiedId = composeFullyQualifiedId;
    function getFullyQualifiedId(entity) {
        var typeName = getBaseType(entity).name;
        var id = getEntityId(entity);
        return composeFullyQualifiedId(typeName, id);
    }
    exports.getFullyQualifiedId = getFullyQualifiedId;
    function getEntityId(entity) {
        return entity.entityAspect.getKey().values[0];
    }
    exports.getEntityId = getEntityId;
    function getEntityIdProperty(entity) {
        return entity.entityType.keyProperties[0];
    }
    exports.getEntityIdProperty = getEntityIdProperty;
    function getBaseType(entity) {
        return entity.entityType.baseEntityType ? entity.entityType.baseEntityType : entity.entityType;
    }
    exports.getBaseType = getBaseType;
    function convertToShortName(typeName) {
        var index = typeName.indexOf(':#');
        if (index > 0) {
            return typeName.substr(0, index);
        }
        return typeName;
    }
    exports.convertToShortName = convertToShortName;
    var timezoneOffset = new Date().getTimezoneOffset();
    function adjustBreezeDate(value) {
        return moment(value).add('minutes', timezoneOffset).toDate();
    }
    function isConcurrencyException(reason) {
        return reason.message && /Store update, insert, or delete statement affected an unexpected number of rows/.test(reason.message);
    }
    exports.isConcurrencyException = isConcurrencyException;
    function getDotNetTypeName(breezeTypeName) {
        return breezeTypeName.replace(/^(.+):#(.+)$/, '$2.$1');
    }
    exports.getDotNetTypeName = getDotNetTypeName;
    function getCrudOperation(entity) {
        var isNew = entity.IsNew();
        return isNew ? security.CrudOperation.Create : security.CrudOperation.Update;
    }
    exports.getCrudOperation = getCrudOperation;
});

define('entities/registry',["require", "exports"], function (require, exports) {
    var metadataStoreInitializers = {};
    var typeIndex = {};
    var types = [];
    var rootTypeIndex = {};
    var rootTypes = [];
    var displayTypeIndex = {};
    var displayTypes = [];
    var constructors = {};
    exports.saveChangesHandlers = [];
    function registerMetadataStoreInitializer(controllerName, initializer) {
        metadataStoreInitializers[controllerName] = initializer;
    }
    exports.registerMetadataStoreInitializer = registerMetadataStoreInitializer;
    function getMetadataStoreInitializer(controllerName) {
        return metadataStoreInitializers[controllerName] || null;
    }
    exports.getMetadataStoreInitializer = getMetadataStoreInitializer;
    function registerRootType(type) {
        if (typeof type.loadById !== 'function')
            throw new Error('Argument \'type.loadById\' is required and must be a function.');
        registerType(type);
        rootTypeIndex[type.name] = type;
        rootTypes.push(type);
    }
    exports.registerRootType = registerRootType;
    function registerType(type) {
        if (type === null)
            throw new Error('Argument \'type\' is required.');
        if (typeof type.name !== 'string')
            throw new Error('Argument \'type.name\' is required and must be a string.');
        if (typeof type.getTitle !== 'function')
            throw new Error('Argument \'type.getTitle\' is required and must be a function.');
        if (typeIndex.hasOwnProperty(type.name))
            throw new Error(type.name + ' is already registered');
        typeIndex[type.name] = type;
        types.push(type);
    }
    exports.registerType = registerType;
    function getType(typeName) {
        if (!typeIndex.hasOwnProperty(typeName))
            throw new Error(typeName + ' is not registered');
        return typeIndex[typeName];
    }
    exports.getType = getType;
    function getRootType(typeName) {
        if (!typeIndex.hasOwnProperty(typeName))
            throw new Error(typeName + ' is not registered');
        if (!rootTypeIndex.hasOwnProperty(typeName))
            throw new Error(typeName + ' is not registered as a root entity type.');
        return rootTypeIndex[typeName];
    }
    exports.getRootType = getRootType;
    function registerDisplayType(type) {
        if (type === undefined || type === null || typeof type.name !== 'string')
            throw new Error('Argument \'type\' is required and must be a string.');
        if (typeof type.getTitle !== 'function')
            throw new Error('Argument \'type.getTitle\' is required and must be a function.');
        if (displayTypeIndex.hasOwnProperty(type.name))
            throw new Error(type.name + ' is already registered');
        displayTypeIndex[type.name] = type;
        displayTypes.push(type);
    }
    exports.registerDisplayType = registerDisplayType;
    function getDisplayType(typeName) {
        if (!displayTypeIndex.hasOwnProperty(typeName))
            throw new Error(typeName + ' is not registered as a root entity type.');
        return displayTypeIndex[typeName];
    }
    exports.getDisplayType = getDisplayType;
    function registerEntityTypeCtor(entityTypeName, entityCtor, initializationFn) {
        constructors[entityTypeName] = { entityCtor: entityCtor, initializationFn: initializationFn };
    }
    exports.registerEntityTypeCtor = registerEntityTypeCtor;
    function getEntityTypeCtor(entityTypeName) {
        return constructors[entityTypeName] || null;
    }
    exports.getEntityTypeCtor = getEntityTypeCtor;
    function convertToLongTypeName(typeName) {
        if (typeName.indexOf(':#') < 0) {
            var regex = RegExp('^' + typeName + ':#', 'i');
            var matches = types.filter(function (t) { return regex.test(t.name); });
            if (matches.length === 1) {
                return matches[0].name;
            }
        }
        return typeName;
    }
    exports.convertToLongTypeName = convertToLongTypeName;
});

define('entities/url',["require", "exports", 'entities/core', 'entities/registry'], function (require, exports, core, registry) {
    (function (EntityAction) {
        EntityAction[EntityAction["Open"] = 0] = "Open";
        EntityAction[EntityAction["New"] = 1] = "New";
        EntityAction[EntityAction["Copy"] = 2] = "Copy";
        EntityAction[EntityAction["Print"] = 3] = "Print";
    })(exports.EntityAction || (exports.EntityAction = {}));
    var EntityAction = exports.EntityAction;
    function parseFragment(fragment) {
        var parts, typeName, result = {
            action: 0 /* Open */,
        };
        if (/^#/.test(fragment)) {
            fragment = fragment.substr(1);
        }
        parts = fragment.split('/').reverse();
        if (parts[0] === 'new') {
            result.action = 1 /* New */;
            parts.shift();
        }
        if (parts[0] === 'copy') {
            result.action = 2 /* Copy */;
            parts.shift();
        }
        else if (parts[0] === 'print') {
            result.action = 3 /* Print */;
            parts.shift();
        }
        if (result.action !== 1 /* New */) {
            result.id = parseInt(parts[0], 10);
            parts.shift();
        }
        typeName = registry.convertToLongTypeName(parts[0]);
        parts.shift();
        result.type = registry.getRootType(typeName);
        if (parts.length) {
            result.parentId = parseInt(parts[0], 10);
            parts.shift();
            typeName = registry.convertToLongTypeName(parts[0]);
            parts.shift();
            result.parentType = registry.getRootType(typeName);
        }
        return result;
    }
    exports.parseFragment = parseFragment;
    function getFragment(entityManager, action) {
        var parentEntity = entityManager.parentEntityManager ? entityManager.parentEntityManager.entity : null, entity = entityManager.entity, getEntityId = core.getEntityId, getBaseType = core.getBaseType, convertToShortName = core.convertToShortName, fragment;
        fragment = convertToShortName(getBaseType(entity).name) + '/' + getEntityId(entity).toString(10);
        if (parentEntity)
            fragment = convertToShortName(getBaseType(parentEntity).name) + '/' + getEntityId(parentEntity).toString(10) + '/' + fragment;
        switch (action || 0 /* Open */) {
            case 2 /* Copy */:
                fragment += '/copy';
                break;
            case 1 /* New */:
                fragment += '/new';
                break;
            case 3 /* Print */:
                fragment += '/print';
                break;
        }
        return fragment;
    }
    exports.getFragment = getFragment;
    function synchronize(entityType, oldId, newId) {
        var info, ex, regex, href;
        try {
            info = parseFragment(location.hash);
        }
        catch (ex) {
            return;
        }
        if (!(info.type.name === entityType.name && info.id === oldId || info.parentType && info.parentType.name === entityType.name && info.parentId === oldId)) {
            return;
        }
        regex = new RegExp('([^\w])' + entityType.shortName + '/' + oldId.toString(10) + '(/|$)');
        href = location.href.replace(regex, '$1' + entityType.shortName + '/' + newId.toString(10) + '$2');
        history.replaceState(null, '', href);
    }
    exports.synchronize = synchronize;
    function getParamsAfterHash() {
        var url = location.href;
        url = url.split("#")[1];
        if (!url)
            return {};
        url = url.split("?")[1];
        if (!url)
            return {};
        return url.split("&").reduce(function (result, param) {
            var split = param.split("=");
            result[split[0]] = split[1];
            return result;
        }, {});
    }
    exports.getParamsAfterHash = getParamsAfterHash;
});

define('entities/keys',["require", "exports", 'core/util'], function (require, exports, util) {
    var inUse = [], expectedId = null, expectedEntityType = null;
    function add(entityType, id) {
        if (util.Arrays.any(inUse, function (k) { return k.id === id && k.entityType === entityType; })) {
            return;
        }
        inUse.push({ id: id, entityType: entityType });
    }
    exports.add = add;
    function setExpectedKey(entityType, id) {
        expectedEntityType = entityType;
        expectedId = id;
    }
    exports.setExpectedKey = setExpectedKey;
    var KeyGenerator = (function () {
        function KeyGenerator() {
        }
        KeyGenerator.prototype.generateTempKeyValue = function (entityType) {
            var id = -1;
            if (entityType.name === expectedEntityType) {
                expectedEntityType = null;
                return expectedId;
            }
            while (util.Arrays.any(inUse, function (k) { return k.id === id && k.entityType === entityType.name; })) {
                id--;
            }
            inUse.push({ id: id, entityType: entityType.name });
            return id;
        };
        return KeyGenerator;
    })();
    exports.KeyGenerator = KeyGenerator;
});

define('entities/breeze',["require", "exports", 'core/constants', 'core/storage', 'core/util', 'entities/registry', 'entities/keys'], function (require, exports, constants, storage, util, registry, keys) {
    var storageOptions = { global: true, hipaa: false };
    var referenceEntityManagers = {};
    function createBreezeEntityManager(controllerName) {
        var serviceUrl = constants.services.breezeServiceBaseUrl + controllerName, metadataUrl = constants.services.breezeServiceBaseUrl + 'BreezeMetadata/Metadata', entityManager, importMetadata = function (metadataJson) {
            entityManager.metadataStore.importMetadata(metadataJson);
            entityManager.metadataStore.addDataService(new breeze.DataService({ serviceName: serviceUrl }));
            initializeMetadataStore(controllerName, entityManager.metadataStore, metadataJson);
            referenceEntityManagers[controllerName] = entityManager;
            return entityManager.createEmptyCopy();
        };
        if (referenceEntityManagers[controllerName]) {
            entityManager = referenceEntityManagers[controllerName].createEmptyCopy();
            return Q.resolve(entityManager);
        }
        entityManager = new breeze.EntityManager(serviceUrl);
        entityManager.setProperties({ keyGeneratorCtor: keys.KeyGenerator });
        return storage.getItem(metadataUrl, storageOptions).then(function (x) {
            if (util.compareVersions(x.version, app.shortVersion) !== 0) {
                throw new Error('version mismatch.');
            }
            return importMetadata(x.data);
        }).fail(function (reason) {
            app.statusBar.download($.i18n.t('sync.systemData'));
            return Q($.ajax({ url: metadataUrl, type: 'GET', dataType: 'text' })).then(function (metadataJson) { return storage.setItem(metadataUrl, metadataJson, storageOptions).then(function () { return importMetadata(metadataJson); }); });
        });
    }
    exports.createBreezeEntityManager = createBreezeEntityManager;
    function initializeMetadataStore(controllerName, metadataStore, metadataJson) {
        var metadata = JSON.parse(metadataJson), metadataType, metadataProperty, entityProperty, i, j;
        for (i = 0; i < metadata.schema.entityType.length; i++) {
            metadataType = metadata.schema.entityType[i];
            var entityType = metadataStore.getEntityType(metadataType.name);
            if (typeof metadataType.securedEntity !== 'undefined') {
                entityType.securedEntity = metadataType.securedEntity;
            }
            if (typeof metadataType.programSecuredEntity !== 'undefined') {
                entityType.programSecuredEntity = metadataType.programSecuredEntity;
            }
            for (j = 0; metadataType.property && j < metadataType.property.length; j++) {
                metadataProperty = metadataType.property[j];
                entityProperty = entityType.getProperty(metadataProperty.name);
                if (entityProperty) {
                    if (typeof metadataProperty.displayName !== 'undefined') {
                        entityProperty.displayName = metadataProperty.displayName;
                    }
                    if (typeof metadataProperty.displayOrder !== 'undefined') {
                        entityProperty.displayOrder = metadataProperty.displayOrder;
                    }
                    if (typeof metadataProperty.autoGenerateField !== 'undefined') {
                        entityProperty.autoGenerateField = metadataProperty.autoGenerateField;
                    }
                    if (typeof metadataProperty.allowEmptyStrings !== 'undefined') {
                        entityProperty.allowEmptyStrings = metadataProperty.allowEmptyStrings;
                    }
                    if (typeof metadataProperty.fieldProtectedItem !== 'undefined') {
                        entityProperty.fieldProtectedItem = metadataProperty.fieldProtectedItem;
                    }
                    if (typeof metadataProperty.organizationProperty !== 'undefined') {
                        entityProperty.organizationProperty = metadataProperty.organizationProperty;
                    }
                    if (typeof metadataProperty.isLevelCareLocusCareUuid !== 'undefined') {
                        entityProperty.isLevelCareLocusCareUuid = metadataProperty.isLevelCareLocusCareUuid;
                    }
                    if (typeof metadataProperty.referenceProtectedItemType !== 'undefined') {
                        entityProperty.referenceProtectedItemType = metadataProperty.referenceProtectedItemType;
                    }
                    if (typeof metadataProperty.lookup !== 'undefined') {
                        entityProperty.lookup = metadataProperty.lookup;
                    }
                }
            }
        }
        metadataStore.getEntityTypes().forEach(function (e) {
            e['concurrencyProperties'] = [];
            var constructorInfo = registry.getEntityTypeCtor(e.name);
            var ctor = function () {
                this.IsNew = false;
                if (constructorInfo !== null) {
                    constructorInfo.entityCtor(this);
                }
            };
            metadataStore.registerEntityTypeCtor(e.name, ctor, constructorInfo === null ? null : constructorInfo.initializationFn);
        });
        if (registry.getMetadataStoreInitializer(controllerName)) {
            registry.getMetadataStoreInitializer(controllerName)(metadataStore);
        }
    }
});

define('entities/cache',["require", "exports", 'core/storage', 'entities/core'], function (require, exports, storage, core) {
    function getEntityState(fullyQualifiedId) {
        return storage.getItem(fullyQualifiedId, core.storageOptions, true).then(function (result) { return Q.resolve({ lupdateDateTime: result.timestamp, isModified: result.status === breeze.EntityState.Modified.toString() }); }).fail(function (reason) {
            return { lupdateDateTime: new Date(1900, 0, 1), isModified: false };
        });
    }
    exports.getEntityState = getEntityState;
    function retrieve(fullyQualifiedId, shallow) {
        return storage.getItem(fullyQualifiedId, core.storageOptions, shallow).then(function (result) { return { json: result.data, lupdateDateTime: result.timestamp, entityState: breeze.EntityState.fromName(result.status) }; });
    }
    exports.retrieve = retrieve;
    function store(entityManager, lupdateDateTime) {
        var fullyQualifiedId = core.getFullyQualifiedId(entityManager.entity), json = entityManager.exportEntities(), status = entityManager.entity.entityAspect.entityState.toString();
        return storage.setItem(fullyQualifiedId, json, core.storageOptions, lupdateDateTime, false, status);
    }
    exports.store = store;
    function remove(entityManager) {
        var fullyQualifiedId = core.getFullyQualifiedId(entityManager.entity);
        return removeById(fullyQualifiedId);
    }
    exports.remove = remove;
    function removeById(fullyQualifiedId) {
        return storage.removeItem(fullyQualifiedId, core.storageOptions);
    }
    exports.removeById = removeById;
});

define('entities/sync',["require", "exports", 'core/constants', 'core/storage', 'entities/core', 'entities/cache', 'entities/repo', 'entities/breeze', 'core/util'], function (require, exports, constants, storage, core, cache, repo, breezeModule, util) {
    exports.versions = core.versions;
    function getClientVersions() {
        return storage.getItem('versions', core.storageOptions).then(function (result) { return result.data; }).fail(function (reason) { return []; });
    }
    exports.getClientVersions = getClientVersions;
    function getServerVersions() {
        return Q($.getJSON(constants.services.serviceBaseUrl + 'Sync/ServerVersions'));
    }
    function syncEntity(serverVersion) {
        var fullyQualifiedId = core.composeFullyQualifiedId(serverVersion.Type, serverVersion.ID);
        return function () { return cache.getEntityState(fullyQualifiedId).then(function (state) {
            if (state.isModified || moment(state.lupdateDateTime).diff(moment(serverVersion.LUpdateDateTime)) === 0) {
                return Q.resolve(null);
            }
            app.statusBar.download($.i18n.t('common.downloading') + ' ' + serverVersion.Description + '...');
            return repo.getInstance(serverVersion.Type, serverVersion.ID).then(function (entityManager) {
                var lupdateDateTime = moment(serverVersion.LUpdateDateTime).toDate();
                return cache.store(entityManager, lupdateDateTime);
            }).fail(function (reason) {
                if (reason === repo.getInstanceExceptions.entityDoesNotExistOnServer) {
                    return;
                }
                return Q.reject(reason);
            });
        }); };
    }
    function sync() {
        var serverVersions;
        var clientVersions;
        core.isSyncing(true);
        return storage.getItem('versions', core.storageOptions).then(function (result) {
            clientVersions = result.data;
            exports.versions(clientVersions);
        }).fail(function (reason) { return clientVersions = []; }).then(function () { return breezeModule.createBreezeEntityManager('BreezeMetadata'); }).then(function (x) { return getServerVersions(); }).then(function (sv) {
            serverVersions = sv;
            if (serverVersions.length === 0)
                return Q.resolve(null);
            var promise = syncEntity(serverVersions[0])();
            for (var i = 1; i < serverVersions.length; i++) {
                promise = promise.then(syncEntity(serverVersions[i]));
            }
            return promise;
        }).then(function () {
            if (!app.isOffline()) {
                var clientVersionsToRemove = clientVersions.filter(function (cv) { return serverVersions.filter(function (sv) { return sv.ID === cv.ID && sv.Type === cv.Type; }).length === 0; });
                exports.versions(serverVersions);
                return core.updateVersions(serverVersions).then(function () { return Q.all(clientVersionsToRemove.map(function (cv) { return repo.removeLocalRootInstance(cv.ID, cv.Type); })); });
            }
            else {
                exports.versions(clientVersions);
            }
        }).then(function () { return app.statusBar.success($.i18n.t('sync.complete'), 3000); }).fail(function (reason) {
            if (util.isConnectionFailure(reason)) {
                app.statusBar.warning($.i18n.t('sync.failed'), 3000);
            }
            else {
                return Q.reject(reason);
            }
        }).finally(function () { return core.isSyncing(false); });
    }
    exports.sync = sync;
    function makeConsumerAvailableOffline(id) {
        return Q($.post(constants.services.serviceBaseUrl + 'Sync/MakeConsumerAvailableOffline', '=' + id)).then(sync);
    }
    exports.makeConsumerAvailableOffline = makeConsumerAvailableOffline;
    function makeConsumerUnvailableOffline(id) {
        var consumerType = 'DEMOGRAPHIC:#Server.Domain';
        return Q($.post(constants.services.serviceBaseUrl + 'Sync/MakeConsumerUnavailableOffline', '=' + id)).then(function () {
            exports.versions(exports.versions().filter(function (v) { return !(v.Type === consumerType && v.ID === id); }));
            return storage.setItem('versions', exports.versions(), core.storageOptions);
        }).then(function () { return repo.removeLocalRootInstance(id, consumerType); }).then(sync);
    }
    exports.makeConsumerUnvailableOffline = makeConsumerUnvailableOffline;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * The system module encapsulates the most basic features used by other modules.
 * @module system
 * @requires require
 * @requires jquery
 */
define('durandal/system',['require', 'jquery'], function(require, $) {
    var isDebugging = false,
        nativeKeys = Object.keys,
        hasOwnProperty = Object.prototype.hasOwnProperty,
        toString = Object.prototype.toString,
        system,
        treatAsIE8 = false,
        nativeIsArray = Array.isArray,
        slice = Array.prototype.slice;

    //polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
    if (!String.prototype.trim) {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }

    //see http://patik.com/blog/complete-cross-browser-console-log/
    // Tell IE9 to use its built-in console
    if (Function.prototype.bind && (typeof console === 'object' || typeof console === 'function') && typeof console.log == 'object') {
        try {
            ['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd']
                .forEach(function(method) {
                    console[method] = this.call(console[method], console);
                }, Function.prototype.bind);
        } catch (ex) {
            treatAsIE8 = true;
        }
    }

    // callback for dojo's loader
    // note: if you wish to use Durandal with dojo's AMD loader,
    // currently you must fork the dojo source with the following
    // dojo/dojo.js, line 1187, the last line of the finishExec() function:
    //  (add) signal("moduleLoaded", [module.result, module.mid]);
    // an enhancement request has been submitted to dojo to make this
    // a permanent change. To view the status of this request, visit:
    // http://bugs.dojotoolkit.org/ticket/16727

    if (require.on) {
        require.on("moduleLoaded", function(module, mid) {
            system.setModuleId(module, mid);
        });
    }

    // callback for require.js loader
    if (typeof requirejs !== 'undefined') {
        requirejs.onResourceLoad = function(context, map, depArray) {
            system.setModuleId(context.defined[map.id], map.id);
        };
    }

    var noop = function() { };

    var log = function() {
        try {
            // Modern browsers
            if (typeof console != 'undefined' && typeof console.log == 'function') {
                // Opera 11
                if (window.opera) {
                    var i = 0;
                    while (i < arguments.length) {
                        console.log('Item ' + (i + 1) + ': ' + arguments[i]);
                        i++;
                    }
                }
                // All other modern browsers
                else if ((slice.call(arguments)).length == 1 && typeof slice.call(arguments)[0] == 'string') {
                    console.log((slice.call(arguments)).toString());
                } else {
                    console.log.apply(console, slice.call(arguments));
                }
            }
            // IE8
            else if ((!Function.prototype.bind || treatAsIE8) && typeof console != 'undefined' && typeof console.log == 'object') {
                Function.prototype.call.call(console.log, console, slice.call(arguments));
            }

            // IE7 and lower, and other old browsers
        } catch (ignore) { }
    };

    var logError = function(error, err) {
        var exception;

        if(error instanceof Error){
            exception = error;
        } else {
            exception = new Error(error);
        }

        exception.innerError = err;

        //Report the error as an error, not as a log
        try {
            // Modern browsers (it's only a single item, no need for argument splitting as in log() above)
            if (typeof console != 'undefined' && typeof console.error == 'function') {
                console.error(exception);
            }
            // IE8
            else if ((!Function.prototype.bind || treatAsIE8) && typeof console != 'undefined' && typeof console.error == 'object') {
                Function.prototype.call.call(console.error, console, exception);
            }
            // IE7 and lower, and other old browsers
        } catch (ignore) { }

        throw exception;
    };

    /**
     * @class SystemModule
     * @static
     */
    system = {
        /**
         * Durandal's version.
         * @property {string} version
         */
        version: "2.2.0",
        /**
         * A noop function.
         * @method noop
         */
        noop: noop,
        /**
         * Gets the module id for the specified object.
         * @method getModuleId
         * @param {object} obj The object whose module id you wish to determine.
         * @return {string} The module id.
         */
        getModuleId: function(obj) {
            if (!obj) {
                return null;
            }

            if (typeof obj == 'function' && obj.prototype) {
                return obj.prototype.__moduleId__;
            }

            if (typeof obj == 'string') {
                return null;
            }

            return obj.__moduleId__;
        },
        /**
         * Sets the module id for the specified object.
         * @method setModuleId
         * @param {object} obj The object whose module id you wish to set.
         * @param {string} id The id to set for the specified object.
         */
        setModuleId: function(obj, id) {
            if (!obj) {
                return;
            }

            if (typeof obj == 'function' && obj.prototype) {
                obj.prototype.__moduleId__ = id;
                return;
            }

            if (typeof obj == 'string') {
                return;
            }

            obj.__moduleId__ = id;
        },
        /**
         * Resolves the default object instance for a module. If the module is an object, the module is returned. If the module is a function, that function is called with `new` and it's result is returned.
         * @method resolveObject
         * @param {object} module The module to use to get/create the default object for.
         * @return {object} The default object for the module.
         */
        resolveObject: function(module) {
            if (system.isFunction(module)) {
                return new module();
            } else {
                return module;
            }
        },
        /**
         * Gets/Sets whether or not Durandal is in debug mode.
         * @method debug
         * @param {boolean} [enable] Turns on/off debugging.
         * @return {boolean} Whether or not Durandal is current debugging.
         */
        debug: function(enable) {
            if (arguments.length == 1) {
                isDebugging = enable;
                if (isDebugging) {
                    this.log = log;
                    this.error = logError;
                    this.log('Debug:Enabled');
                } else {
                    this.log('Debug:Disabled');
                    this.log = noop;
                    this.error = noop;
                }
            }

            return isDebugging;
        },
        /**
         * Logs data to the console. Pass any number of parameters to be logged. Log output is not processed if the framework is not running in debug mode.
         * @method log
         * @param {object} info* The objects to log.
         */
        log: noop,
        /**
         * Logs an error.
         * @method error
         * @param {string|Error} obj The error to report.
         */
        error: noop,
        /**
         * Asserts a condition by throwing an error if the condition fails.
         * @method assert
         * @param {boolean} condition The condition to check.
         * @param {string} message The message to report in the error if the condition check fails.
         */
        assert: function (condition, message) {
            if (!condition) {
                system.error(new Error(message || 'Assert:Failed'));
            }
        },
        /**
         * Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise.
         * @method defer
         * @param {function} [action] The action to defer. You will be passed the deferred object as a paramter.
         * @return {Deferred} The deferred object.
         */
        defer: function(action) {
            return $.Deferred(action);
        },
        /**
         * Creates a simple V4 UUID. This should not be used as a PK in your database. It can be used to generate internal, unique ids. For a more robust solution see [node-uuid](https://github.com/broofa/node-uuid).
         * @method guid
         * @return {string} The guid.
         */
        guid: function() {
            var d = new Date().getTime();
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d/16);
                return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
            });
        },
        /**
         * Uses require.js to obtain a module. This function returns a promise which resolves with the module instance. You can pass more than one module id to this function or an array of ids. If more than one or an array is passed, then the promise will resolve with an array of module instances.
         * @method acquire
         * @param {string|string[]} moduleId The id(s) of the modules to load.
         * @return {Promise} A promise for the loaded module(s).
         */
        acquire: function() {
            var modules,
                first = arguments[0],
                arrayRequest = false;

            if(system.isArray(first)){
                modules = first;
                arrayRequest = true;
            }else{
                modules = slice.call(arguments, 0);
            }

            return this.defer(function(dfd) {
                require(modules, function() {
                    var args = arguments;
                    setTimeout(function() {
                        if(args.length > 1 || arrayRequest){
                            dfd.resolve(slice.call(args, 0));
                        }else{
                            dfd.resolve(args[0]);
                        }
                    }, 1);
                }, function(err){
                    dfd.reject(err);
                });
            }).promise();
        },
        /**
         * Extends the first object with the properties of the following objects.
         * @method extend
         * @param {object} obj The target object to extend.
         * @param {object} extension* Uses to extend the target object.
         */
        extend: function(obj) {
            var rest = slice.call(arguments, 1);

            for (var i = 0; i < rest.length; i++) {
                var source = rest[i];

                if (source) {
                    for (var prop in source) {
                        obj[prop] = source[prop];
                    }
                }
            }

            return obj;
        },
        /**
         * Uses a setTimeout to wait the specified milliseconds.
         * @method wait
         * @param {number} milliseconds The number of milliseconds to wait.
         * @return {Promise}
         */
        wait: function(milliseconds) {
            return system.defer(function(dfd) {
                setTimeout(dfd.resolve, milliseconds);
            }).promise();
        }
    };

    /**
     * Gets all the owned keys of the specified object.
     * @method keys
     * @param {object} object The object whose owned keys should be returned.
     * @return {string[]} The keys.
     */
    system.keys = nativeKeys || function(obj) {
        if (obj !== Object(obj)) {
            throw new TypeError('Invalid object');
        }

        var keys = [];

        for (var key in obj) {
            if (hasOwnProperty.call(obj, key)) {
                keys[keys.length] = key;
            }
        }

        return keys;
    };

    /**
     * Determines if the specified object is an html element.
     * @method isElement
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */
    system.isElement = function(obj) {
        return !!(obj && obj.nodeType === 1);
    };

    /**
     * Determines if the specified object is an array.
     * @method isArray
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */
    system.isArray = nativeIsArray || function(obj) {
        return toString.call(obj) == '[object Array]';
    };

    /**
     * Determines if the specified object is...an object. ie. Not an array, string, etc.
     * @method isObject
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */
    system.isObject = function(obj) {
        return obj === Object(obj);
    };

    /**
     * Determines if the specified object is a boolean.
     * @method isBoolean
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */
    system.isBoolean = function(obj) {
        return typeof(obj) === "boolean";
    };

    /**
     * Determines if the specified object is a promise.
     * @method isPromise
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */
    system.isPromise = function(obj) {
        return obj && system.isFunction(obj.then);
    };

    /**
     * Determines if the specified object is a function arguments object.
     * @method isArguments
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */

    /**
     * Determines if the specified object is a function.
     * @method isFunction
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */

    /**
     * Determines if the specified object is a string.
     * @method isString
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */

    /**
     * Determines if the specified object is a number.
     * @method isNumber
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */

    /**
     * Determines if the specified object is a date.
     * @method isDate
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */

    /**
     * Determines if the specified object is a boolean.
     * @method isBoolean
     * @param {object} object The object to check.
     * @return {boolean} True if matches the type, false otherwise.
     */

    //isArguments, isFunction, isString, isNumber, isDate, isRegExp.
    var isChecks = ['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'];

    function makeIsFunction(name) {
        var value = '[object ' + name + ']';
        system['is' + name] = function(obj) {
            return toString.call(obj) == value;
        };
    }

    for (var i = 0; i < isChecks.length; i++) {
        makeIsFunction(isChecks[i]);
    }

    return system;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * The viewEngine module provides information to the viewLocator module which is used to locate the view's source file. The viewEngine also transforms a view id into a view instance.
 * @module viewEngine
 * @requires system
 * @requires jquery
 */
define('durandal/viewEngine',['durandal/system', 'jquery'], function (system, $) {
    var parseMarkup;

    if ($.parseHTML) {
        parseMarkup = function (html) {
            return $.parseHTML(html);
        };
    } else {
        parseMarkup = function (html) {
            return $(html).get();
        };
    }

    /**
     * @class ViewEngineModule
     * @static
     */
    return {
        cache:{},
        /**
         * The file extension that view source files are expected to have.
         * @property {string} viewExtension
         * @default .html
         */
        viewExtension: '.html',
        /**
         * The name of the RequireJS loader plugin used by the viewLocator to obtain the view source. (Use requirejs to map the plugin's full path).
         * @property {string} viewPlugin
         * @default text
         */
        viewPlugin: 'text',
        /**
         * Parameters passed to the RequireJS loader plugin used by the viewLocator to obtain the view source.
         * @property {string} viewPluginParameters
         * @default The empty string by default.
         */
        viewPluginParameters: '',
        /**
         * Determines if the url is a url for a view, according to the view engine.
         * @method isViewUrl
         * @param {string} url The potential view url.
         * @return {boolean} True if the url is a view url, false otherwise.
         */
        isViewUrl: function (url) {
            return url.indexOf(this.viewExtension, url.length - this.viewExtension.length) !== -1;
        },
        /**
         * Converts a view url into a view id.
         * @method convertViewUrlToViewId
         * @param {string} url The url to convert.
         * @return {string} The view id.
         */
        convertViewUrlToViewId: function (url) {
            return url.substring(0, url.length - this.viewExtension.length);
        },
        /**
         * Converts a view id into a full RequireJS path.
         * @method convertViewIdToRequirePath
         * @param {string} viewId The view id to convert.
         * @return {string} The require path.
         */
        convertViewIdToRequirePath: function (viewId) {
            var plugin = this.viewPlugin ? this.viewPlugin + '!' : '';
            return plugin + viewId + this.viewExtension + this.viewPluginParameters;
        },
        /**
         * Parses the view engine recognized markup and returns DOM elements.
         * @method parseMarkup
         * @param {string} markup The markup to parse.
         * @return {DOMElement[]} The elements.
         */
        parseMarkup: parseMarkup,
        /**
         * Calls `parseMarkup` and then pipes the results through `ensureSingleElement`.
         * @method processMarkup
         * @param {string} markup The markup to process.
         * @return {DOMElement} The view.
         */
        processMarkup: function (markup) {
            var allElements = this.parseMarkup(markup);
            return this.ensureSingleElement(allElements);
        },
        /**
         * Converts an array of elements into a single element. White space and comments are removed. If a single element does not remain, then the elements are wrapped.
         * @method ensureSingleElement
         * @param {DOMElement[]} allElements The elements.
         * @return {DOMElement} A single element.
         */
        ensureSingleElement:function(allElements){
            if (!allElements) { 
                $('<div></div>')[0];
            } else if (allElements.length == 1) {
                return allElements[0];
            }

            var withoutCommentsOrEmptyText = [];

            for (var i = 0; i < allElements.length; i++) {
                var current = allElements[i];
                if (current.nodeType != 8) {
                    if (current.nodeType == 3) {
                        var result = /\S/.test(current.nodeValue);
                        if (!result) {
                            continue;
                        }
                    }

                    withoutCommentsOrEmptyText.push(current);
                }
            }

            if (withoutCommentsOrEmptyText.length > 1) {
                return $(withoutCommentsOrEmptyText).wrapAll('<div class="durandal-wrapper"></div>').parent().get(0);
            }

            return withoutCommentsOrEmptyText[0];
        },
        /**
         * Gets the view associated with the id from the cache of parsed views.
         * @method tryGetViewFromCache
         * @param {string} id The view id to lookup in the cache.
         * @return {DOMElement|null} The cached view or null if it's not in the cache.
         */
        tryGetViewFromCache:function(id) {
            return this.cache[id];
        },
        /**
         * Puts the view associated with the id into the cache of parsed views.
         * @method putViewInCache
         * @param {string} id The view id whose view should be cached.
         * @param {DOMElement} view The view to cache.
         */
        putViewInCache: function (id, view) {
            this.cache[id] = view;
        },
        /**
         * Creates the view associated with the view id.
         * @method createView
         * @param {string} viewId The view id whose view should be created.
         * @return {Promise} A promise of the view.
         */
        createView: function(viewId) {
            var that = this;
            var requirePath = this.convertViewIdToRequirePath(viewId);
            var existing = this.tryGetViewFromCache(requirePath);

            if (existing) {
                return system.defer(function(dfd) {
                    dfd.resolve(existing.cloneNode(true));
                }).promise();
            }

            return system.defer(function(dfd) {
                system.acquire(requirePath).then(function(markup) {
                    var element = that.processMarkup(markup);
                    element.setAttribute('data-view', viewId);
                    that.putViewInCache(requirePath, element);
                    dfd.resolve(element.cloneNode(true));
                }).fail(function(err) {
                    that.createFallbackView(viewId, requirePath, err).then(function(element) {
                        element.setAttribute('data-view', viewId);
                        that.cache[requirePath] = element;
                        dfd.resolve(element.cloneNode(true));
                    });
                });
            }).promise();
        },
        /**
         * Called when a view cannot be found to provide the opportunity to locate or generate a fallback view. Mainly used to ease development.
         * @method createFallbackView
         * @param {string} viewId The view id whose view should be created.
         * @param {string} requirePath The require path that was attempted.
         * @param {Error} requirePath The error that was returned from the attempt to locate the default view.
         * @return {Promise} A promise for the fallback view.
         */
        createFallbackView: function (viewId, requirePath, err) {
            var that = this,
                message = 'View Not Found. Searched for "' + viewId + '" via path "' + requirePath + '".';

            return system.defer(function(dfd) {
                dfd.resolve(that.processMarkup('<div class="durandal-view-404">' + message + '</div>'));
            }).promise();
        }
    };
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * The viewLocator module collaborates with the viewEngine module to provide views (literally dom sub-trees) to other parts of the framework as needed. The primary consumer of the viewLocator is the composition module.
 * @module viewLocator
 * @requires system
 * @requires viewEngine
 */
define('durandal/viewLocator',['durandal/system', 'durandal/viewEngine'], function (system, viewEngine) {
    function findInElements(nodes, url) {
        for (var i = 0; i < nodes.length; i++) {
            var current = nodes[i];
            var existingUrl = current.getAttribute('data-view');
            if (existingUrl == url) {
                return current;
            }
        }
    }
    
    function escape(str) {
        return (str + '').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
    }

    /**
     * @class ViewLocatorModule
     * @static
     */
    return {
        /**
         * Allows you to set up a convention for mapping module folders to view folders. It is a convenience method that customizes `convertModuleIdToViewId` and `translateViewIdToArea` under the covers.
         * @method useConvention
         * @param {string} [modulesPath] A string to match in the path and replace with the viewsPath. If not specified, the match is 'viewmodels'.
         * @param {string} [viewsPath] The replacement for the modulesPath. If not specified, the replacement is 'views'.
         * @param {string} [areasPath] Partial views are mapped to the "views" folder if not specified. Use this parameter to change their location.
         */
        useConvention: function(modulesPath, viewsPath, areasPath) {
            modulesPath = modulesPath || 'viewmodels';
            viewsPath = viewsPath || 'views';
            areasPath = areasPath || viewsPath;

            var reg = new RegExp(escape(modulesPath), 'gi');

            this.convertModuleIdToViewId = function (moduleId) {
                return moduleId.replace(reg, viewsPath);
            };

            this.translateViewIdToArea = function (viewId, area) {
                if (!area || area == 'partial') {
                    return areasPath + '/' + viewId;
                }
                
                return areasPath + '/' + area + '/' + viewId;
            };
        },
        /**
         * Maps an object instance to a view instance.
         * @method locateViewForObject
         * @param {object} obj The object to locate the view for.
         * @param {string} [area] The area to translate the view to.
         * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first.
         * @return {Promise} A promise of the view.
         */
        locateViewForObject: function(obj, area, elementsToSearch) {
            var view;

            if (obj.getView) {
                view = obj.getView();
                if (view) {
                    return this.locateView(view, area, elementsToSearch);
                }
            }

            if (obj.viewUrl) {
                return this.locateView(obj.viewUrl, area, elementsToSearch);
            }

            var id = system.getModuleId(obj);
            if (id) {
                return this.locateView(this.convertModuleIdToViewId(id), area, elementsToSearch);
            }

            return this.locateView(this.determineFallbackViewId(obj), area, elementsToSearch);
        },
        /**
         * Converts a module id into a view id. By default the ids are the same.
         * @method convertModuleIdToViewId
         * @param {string} moduleId The module id.
         * @return {string} The view id.
         */
        convertModuleIdToViewId: function(moduleId) {
            return moduleId;
        },
        /**
         * If no view id can be determined, this function is called to genreate one. By default it attempts to determine the object's type and use that.
         * @method determineFallbackViewId
         * @param {object} obj The object to determine the fallback id for.
         * @return {string} The view id.
         */
        determineFallbackViewId: function (obj) {
            var funcNameRegex = /function (.{1,})\(/;
            var results = (funcNameRegex).exec((obj).constructor.toString());
            var typeName = (results && results.length > 1) ? results[1] : "";
            typeName = typeName.trim();
            return 'views/' + typeName;
        },
        /**
         * Takes a view id and translates it into a particular area. By default, no translation occurs.
         * @method translateViewIdToArea
         * @param {string} viewId The view id.
         * @param {string} area The area to translate the view to.
         * @return {string} The translated view id.
         */
        translateViewIdToArea: function (viewId, area) {
            return viewId;
        },
        /**
         * Locates the specified view.
         * @method locateView
         * @param {string|DOMElement} viewOrUrlOrId A view, view url or view id to locate.
         * @param {string} [area] The area to translate the view to.
         * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first.
         * @return {Promise} A promise of the view.
         */
        locateView: function(viewOrUrlOrId, area, elementsToSearch) {
            if (typeof viewOrUrlOrId === 'string') {
                var viewId;

                if (viewEngine.isViewUrl(viewOrUrlOrId)) {
                    viewId = viewEngine.convertViewUrlToViewId(viewOrUrlOrId);
                } else {
                    viewId = viewOrUrlOrId;
                }

                if (area) {
                    viewId = this.translateViewIdToArea(viewId, area);
                }

                if (elementsToSearch) {
                    var existing = findInElements(elementsToSearch, viewId);
                    if (existing) {
                        return system.defer(function(dfd) {
                            dfd.resolve(existing);
                        }).promise();
                    }
                }

                return viewEngine.createView(viewId);
            }

            return system.defer(function(dfd) {
                dfd.resolve(viewOrUrlOrId);
            }).promise();
        }
    };
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * The binder joins an object instance and a DOM element tree by applying databinding and/or invoking binding lifecycle callbacks (binding and bindingComplete).
 * @module binder
 * @requires system
 * @requires knockout
 */
define('durandal/binder',['durandal/system', 'knockout'], function (system, ko) {
    var binder,
        insufficientInfoMessage = 'Insufficient Information to Bind',
        unexpectedViewMessage = 'Unexpected View Type',
        bindingInstructionKey = 'durandal-binding-instruction',
        koBindingContextKey = '__ko_bindingContext__';

    function normalizeBindingInstruction(result){
        if(result === undefined){
            return { applyBindings: true };
        }

        if(system.isBoolean(result)){
            return { applyBindings:result };
        }

        if(result.applyBindings === undefined){
            result.applyBindings = true;
        }

        return result;
    }

    function doBind(obj, view, bindingTarget, data){
        if (!view || !bindingTarget) {
            if (binder.throwOnErrors) {
                system.error(insufficientInfoMessage);
            } else {
                system.log(insufficientInfoMessage, view, data);
            }
            return;
        }

        if (!view.getAttribute) {
            if (binder.throwOnErrors) {
                system.error(unexpectedViewMessage);
            } else {
                system.log(unexpectedViewMessage, view, data);
            }
            return;
        }

        var viewName = view.getAttribute('data-view');

        try {
            var instruction;

            if (obj && obj.binding) {
                instruction = obj.binding(view);
            }

            instruction = normalizeBindingInstruction(instruction);
            binder.binding(data, view, instruction);

            if(instruction.applyBindings){
                system.log('Binding', viewName, data);
                ko.applyBindings(bindingTarget, view);
            }else if(obj){
                ko.utils.domData.set(view, koBindingContextKey, { $data:obj });
            }

            binder.bindingComplete(data, view, instruction);

            if (obj && obj.bindingComplete) {
                obj.bindingComplete(view);
            }

            ko.utils.domData.set(view, bindingInstructionKey, instruction);
            return instruction;
        } catch (e) {
            e.message = e.message + ';\nView: ' + viewName + ";\nModuleId: " + system.getModuleId(data);
            if (binder.throwOnErrors) {
                system.error(e);
            } else {
                system.log(e.message);
            }
        }
    }

    /**
     * @class BinderModule
     * @static
     */
    return binder = {
        /**
         * Called before every binding operation. Does nothing by default.
         * @method binding
         * @param {object} data The data that is about to be bound.
         * @param {DOMElement} view The view that is about to be bound.
         * @param {object} instruction The object that carries the binding instructions.
         */
        binding: system.noop,
        /**
         * Called after every binding operation. Does nothing by default.
         * @method bindingComplete
         * @param {object} data The data that has just been bound.
         * @param {DOMElement} view The view that has just been bound.
         * @param {object} instruction The object that carries the binding instructions.
         */
        bindingComplete: system.noop,
        /**
         * Indicates whether or not the binding system should throw errors or not.
         * @property {boolean} throwOnErrors
         * @default false The binding system will not throw errors by default. Instead it will log them.
         */
        throwOnErrors: false,
        /**
         * Gets the binding instruction that was associated with a view when it was bound.
         * @method getBindingInstruction
         * @param {DOMElement} view The view that was previously bound.
         * @return {object} The object that carries the binding instructions.
         */
        getBindingInstruction:function(view){
            return ko.utils.domData.get(view, bindingInstructionKey);
        },
        /**
         * Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context.
         * @method bindContext
         * @param {KnockoutBindingContext} bindingContext The current binding context.
         * @param {DOMElement} view The view to bind.
         * @param {object} [obj] The data to bind to, causing the creation of a child binding context if present.
         * @param {string} [dataAlias] An alias for $data if present.
         */
        bindContext: function(bindingContext, view, obj, dataAlias) {
            if (obj && bindingContext) {
                bindingContext = bindingContext.createChildContext(obj, typeof(dataAlias) === 'string' ? dataAlias : null);
            }

            return doBind(obj, view, bindingContext, obj || (bindingContext ? bindingContext.$data : null));
        },
        /**
         * Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context.
         * @method bind
         * @param {object} obj The data to bind to.
         * @param {DOMElement} view The view to bind.
         */
        bind: function(obj, view) {
            return doBind(obj, view, obj, obj);
        }
    };
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * The activator module encapsulates all logic related to screen/component activation.
 * An activator is essentially an asynchronous state machine that understands a particular state transition protocol.
 * The protocol ensures that the following series of events always occur: `canDeactivate` (previous state), `canActivate` (new state), `deactivate` (previous state), `activate` (new state).
 * Each of the _can_ callbacks may return a boolean, affirmative value or promise for one of those. If either of the _can_ functions yields a false result, then activation halts.
 * @module activator
 * @requires system
 * @requires knockout
 */
define('durandal/activator',['durandal/system', 'knockout'], function (system, ko) {
    var activator;
    var defaultOptions = {
        canDeactivate:true
    };

    function ensureSettings(settings) {
        if (settings == undefined) {
            settings = {};
        }

        if (!system.isBoolean(settings.closeOnDeactivate)) {
            settings.closeOnDeactivate = activator.defaults.closeOnDeactivate;
        }

        if (!settings.beforeActivate) {
            settings.beforeActivate = activator.defaults.beforeActivate;
        }

        if (!settings.afterDeactivate) {
            settings.afterDeactivate = activator.defaults.afterDeactivate;
        }

        if(!settings.affirmations){
            settings.affirmations = activator.defaults.affirmations;
        }

        if (!settings.interpretResponse) {
            settings.interpretResponse = activator.defaults.interpretResponse;
        }

        if (!settings.areSameItem) {
            settings.areSameItem = activator.defaults.areSameItem;
        }

        if (!settings.findChildActivator) {
            settings.findChildActivator = activator.defaults.findChildActivator;
        }

        return settings;
    }

    function invoke(target, method, data) {
        if (system.isArray(data)) {
            return target[method].apply(target, data);
        }

        return target[method](data);
    }

    function deactivate(item, close, settings, dfd, setter) {
        if (item && item.deactivate) {
            system.log('Deactivating', item);

            var result;
            try {
                result = item.deactivate(close);
            } catch(error) {
                system.log('ERROR: ' + error.message, error);
                dfd.resolve(false);
                return;
            }

            if (result && result.then) {
                result.then(function() {
                    settings.afterDeactivate(item, close, setter);
                    dfd.resolve(true);
                }, function(reason) {
                    if (reason) {
                        system.log(reason);
                    }

                    dfd.resolve(false);
                });
            } else {
                settings.afterDeactivate(item, close, setter);
                dfd.resolve(true);
            }
        } else {
            if (item) {
                settings.afterDeactivate(item, close, setter);
            }

            dfd.resolve(true);
        }
    }

    function activate(newItem, activeItem, callback, activationData) {
        var result;

        if(newItem && newItem.activate) {
            system.log('Activating', newItem);

            try {
                result = invoke(newItem, 'activate', activationData);
            } catch (error) {
                system.log('ERROR: ' + error.message, error);
                callback(false);
                return;
            }
        }

        if(result && result.then) {
            result.then(function() {
                activeItem(newItem);
                callback(true);
            }, function (reason) {
                if (reason) {
                    system.log('ERROR: ' + reason.message, reason);
                }

                callback(false);
            });
        } else {
            activeItem(newItem);
            callback(true);
        }
    }

    function canDeactivateItem(item, close, settings, options) {
        options = system.extend({}, defaultOptions, options);
        settings.lifecycleData = null;

        return system.defer(function (dfd) {
            function continueCanDeactivate() {
                if (item && item.canDeactivate && options.canDeactivate) {
                    var resultOrPromise;
                    try {
                        resultOrPromise = item.canDeactivate(close);
                    } catch (error) {
                        system.log('ERROR: ' + error.message, error);
                        dfd.resolve(false);
                        return;
                    }

                    if (resultOrPromise.then) {
                        resultOrPromise.then(function (result) {
                            settings.lifecycleData = result;
                            dfd.resolve(settings.interpretResponse(result));
                        }, function (reason) {
                            if (reason) {
                                system.log('ERROR: ' + reason.message, reason);
                            }

                            dfd.resolve(false);
                        });
                    } else {
                        settings.lifecycleData = resultOrPromise;
                        dfd.resolve(settings.interpretResponse(resultOrPromise));
                    }
                } else {
                    dfd.resolve(true);
                }
            }

            var childActivator = settings.findChildActivator(item);
            if (childActivator) {
                childActivator.canDeactivate().then(function(result) {
                    if (result) {
                        continueCanDeactivate();
                    } else {
                        dfd.resolve(false);
                    }
                });
            } else {
                continueCanDeactivate();
            }
        }).promise();
    };

    function canActivateItem(newItem, activeItem, settings, activeData, newActivationData) {
        settings.lifecycleData = null;

        return system.defer(function (dfd) {
            if (settings.areSameItem(activeItem(), newItem, activeData, newActivationData)) {
                dfd.resolve(true);
                return;
            }

            if (newItem && newItem.canActivate) {
                var resultOrPromise;
                try {
                    resultOrPromise = invoke(newItem, 'canActivate', newActivationData);
                } catch (error) {
                    system.log('ERROR: ' + error.message, error);
                    dfd.resolve(false);
                    return;
                }

                if (resultOrPromise.then) {
                    resultOrPromise.then(function(result) {
                        settings.lifecycleData = result;
                        dfd.resolve(settings.interpretResponse(result));
                    }, function(reason) {
                        if (reason) {
                            system.log('ERROR: ' + reason.message, reason);
                        }

                        dfd.resolve(false);
                    });
                } else {
                    settings.lifecycleData = resultOrPromise;
                    dfd.resolve(settings.interpretResponse(resultOrPromise));
                }
            } else {
                dfd.resolve(true);
            }
        }).promise();
    };

    /**
     * An activator is a read/write computed observable that enforces the activation lifecycle whenever changing values.
     * @class Activator
     */
    function createActivator(initialActiveItem, settings) {
        var activeItem = ko.observable(null);
        var activeData;

        settings = ensureSettings(settings);

        var computed = ko.computed({
            read: function () {
                return activeItem();
            },
            write: function (newValue) {
                computed.viaSetter = true;
                computed.activateItem(newValue);
            }
        });

        computed.__activator__ = true;

        /**
         * The settings for this activator.
         * @property {ActivatorSettings} settings
         */
        computed.settings = settings;
        settings.activator = computed;

        /**
         * An observable which indicates whether or not the activator is currently in the process of activating an instance.
         * @method isActivating
         * @return {boolean}
         */
        computed.isActivating = ko.observable(false);

        computed.forceActiveItem = function (item) {
            activeItem(item);
        };

        /**
         * Determines whether or not the specified item can be deactivated.
         * @method canDeactivateItem
         * @param {object} item The item to check.
         * @param {boolean} close Whether or not to check if close is possible.
         * @param {object} options Options for controlling the activation process.
         * @return {promise}
         */
        computed.canDeactivateItem = function (item, close, options) {
            return canDeactivateItem(item, close, settings, options);
        };

        /**
         * Deactivates the specified item.
         * @method deactivateItem
         * @param {object} item The item to deactivate.
         * @param {boolean} close Whether or not to close the item.
         * @return {promise}
         */
        computed.deactivateItem = function (item, close) {
            return system.defer(function(dfd) {
                computed.canDeactivateItem(item, close).then(function(canDeactivate) {
                    if (canDeactivate) {
                        deactivate(item, close, settings, dfd, activeItem);
                    } else {
                        computed.notifySubscribers();
                        dfd.resolve(false);
                    }
                });
            }).promise();
        };

        /**
         * Determines whether or not the specified item can be activated.
         * @method canActivateItem
         * @param {object} item The item to check.
         * @param {object} activationData Data associated with the activation.
         * @return {promise}
         */
        computed.canActivateItem = function (newItem, activationData) {
            return canActivateItem(newItem, activeItem, settings, activeData, activationData);
        };

        /**
         * Activates the specified item.
         * @method activateItem
         * @param {object} newItem The item to activate.
         * @param {object} newActivationData Data associated with the activation.
         * @param {object} options Options for controlling the activation process.
         * @return {promise}
         */
        computed.activateItem = function (newItem, newActivationData, options) {
            var viaSetter = computed.viaSetter;
            computed.viaSetter = false;

            return system.defer(function (dfd) {
                if (computed.isActivating()) {
                    dfd.resolve(false);
                    return;
                }

                computed.isActivating(true);

                var currentItem = activeItem();
                if (settings.areSameItem(currentItem, newItem, activeData, newActivationData)) {
                    computed.isActivating(false);
                    dfd.resolve(true);
                    return;
                }

                computed.canDeactivateItem(currentItem, settings.closeOnDeactivate, options).then(function (canDeactivate) {
                    if (canDeactivate) {
                        computed.canActivateItem(newItem, newActivationData).then(function (canActivate) {
                            if (canActivate) {
                                system.defer(function (dfd2) {
                                    deactivate(currentItem, settings.closeOnDeactivate, settings, dfd2);
                                }).promise().then(function () {
                                        newItem = settings.beforeActivate(newItem, newActivationData);
                                        activate(newItem, activeItem, function (result) {
                                            activeData = newActivationData;
                                            computed.isActivating(false);
                                            dfd.resolve(result);
                                        }, newActivationData);
                                    });
                            } else {
                                if (viaSetter) {
                                    computed.notifySubscribers();
                                }

                                computed.isActivating(false);
                                dfd.resolve(false);
                            }
                        });
                    } else {
                        if (viaSetter) {
                            computed.notifySubscribers();
                        }

                        computed.isActivating(false);
                        dfd.resolve(false);
                    }
                });
            }).promise();
        };

        /**
         * Determines whether or not the activator, in its current state, can be activated.
         * @method canActivate
         * @return {promise}
         */
        computed.canActivate = function () {
            var toCheck;

            if (initialActiveItem) {
                toCheck = initialActiveItem;
                initialActiveItem = false;
            } else {
                toCheck = computed();
            }

            return computed.canActivateItem(toCheck);
        };

        /**
         * Activates the activator, in its current state.
         * @method activate
         * @return {promise}
         */
        computed.activate = function () {
            var toActivate;

            if (initialActiveItem) {
                toActivate = initialActiveItem;
                initialActiveItem = false;
            } else {
                toActivate = computed();
            }

            return computed.activateItem(toActivate);
        };

        /**
         * Determines whether or not the activator, in its current state, can be deactivated.
         * @method canDeactivate
         * @return {promise}
         */
        computed.canDeactivate = function (close) {
            return computed.canDeactivateItem(computed(), close);
        };

        /**
         * Deactivates the activator, in its current state.
         * @method deactivate
         * @return {promise}
         */
        computed.deactivate = function (close) {
            return computed.deactivateItem(computed(), close);
        };

        computed.includeIn = function (includeIn) {
            includeIn.canActivate = function () {
                return computed.canActivate();
            };

            includeIn.activate = function () {
                return computed.activate();
            };

            includeIn.canDeactivate = function (close) {
                return computed.canDeactivate(close);
            };

            includeIn.deactivate = function (close) {
                return computed.deactivate(close);
            };
        };

        if (settings.includeIn) {
            computed.includeIn(settings.includeIn);
        } else if (initialActiveItem) {
            computed.activate();
        }

        computed.forItems = function (items) {
            settings.closeOnDeactivate = false;

            settings.determineNextItemToActivate = function (list, lastIndex) {
                var toRemoveAt = lastIndex - 1;

                if (toRemoveAt == -1 && list.length > 1) {
                    return list[1];
                }

                if (toRemoveAt > -1 && toRemoveAt < list.length - 1) {
                    return list[toRemoveAt];
                }

                return null;
            };

            settings.beforeActivate = function (newItem) {
                var currentItem = computed();

                if (!newItem) {
                    newItem = settings.determineNextItemToActivate(items, currentItem ? items.indexOf(currentItem) : 0);
                } else {
                    var index = items.indexOf(newItem);

                    if (index == -1) {
                        items.push(newItem);
                    } else {
                        newItem = items()[index];
                    }
                }

                return newItem;
            };

            settings.afterDeactivate = function (oldItem, close) {
                if (close) {
                    items.remove(oldItem);
                }
            };

            var originalCanDeactivate = computed.canDeactivate;
            computed.canDeactivate = function (close) {
                if (close) {
                    return system.defer(function (dfd) {
                        var list = items();
                        var results = [];

                        function finish() {
                            for (var j = 0; j < results.length; j++) {
                                if (!results[j]) {
                                    dfd.resolve(false);
                                    return;
                                }
                            }

                            dfd.resolve(true);
                        }

                        for (var i = 0; i < list.length; i++) {
                            computed.canDeactivateItem(list[i], close).then(function (result) {
                                results.push(result);
                                if (results.length == list.length) {
                                    finish();
                                }
                            });
                        }
                    }).promise();
                } else {
                    return originalCanDeactivate();
                }
            };

            var originalDeactivate = computed.deactivate;
            computed.deactivate = function (close) {
                if (close) {
                    return system.defer(function (dfd) {
                        var list = items();
                        var results = 0;
                        var listLength = list.length;

                        function doDeactivate(item) {
                            setTimeout(function () {
                                computed.deactivateItem(item, close).then(function () {
                                    results++;
                                    items.remove(item);
                                    if (results == listLength) {
                                        dfd.resolve();
                                    }
                                });
                            }, 1);
                        }

                        for (var i = 0; i < listLength; i++) {
                            doDeactivate(list[i]);
                        }
                    }).promise();
                } else {
                    return originalDeactivate();
                }
            };

            return computed;
        };

        return computed;
    }

    /**
     * @class ActivatorSettings
     * @static
     */
    var activatorSettings = {
        /**
         * The default value passed to an object's deactivate function as its close parameter.
         * @property {boolean} closeOnDeactivate
         * @default true
         */
        closeOnDeactivate: true,
        /**
         * Lower-cased words which represent a truthy value.
         * @property {string[]} affirmations
         * @default ['yes', 'ok', 'true']
         */
        affirmations: ['yes', 'ok', 'true'],
        /**
         * Interprets the response of a `canActivate` or `canDeactivate` call using the known affirmative values in the `affirmations` array.
         * @method interpretResponse
         * @param {object} value
         * @return {boolean}
         */
        interpretResponse: function(value) {
            if(system.isObject(value)) {
                value = value.can || false;
            }

            if(system.isString(value)) {
                return ko.utils.arrayIndexOf(this.affirmations, value.toLowerCase()) !== -1;
            }

            return value;
        },
        /**
         * Determines whether or not the current item and the new item are the same.
         * @method areSameItem
         * @param {object} currentItem
         * @param {object} newItem
         * @param {object} currentActivationData
         * @param {object} newActivationData
         * @return {boolean}
         */
        areSameItem: function(currentItem, newItem, currentActivationData, newActivationData) {
            return currentItem == newItem;
        },
        /**
         * Called immediately before the new item is activated.
         * @method beforeActivate
         * @param {object} newItem
         */
        beforeActivate: function(newItem) {
            return newItem;
        },
        /**
         * Called immediately after the old item is deactivated.
         * @method afterDeactivate
         * @param {object} oldItem The previous item.
         * @param {boolean} close Whether or not the previous item was closed.
         * @param {function} setter The activate item setter function.
         */
        afterDeactivate: function(oldItem, close, setter) {
            if(close && setter) {
                setter(null);
            }
        },
        findChildActivator: function(item){
            return null;
        }
    };

    /**
     * @class ActivatorModule
     * @static
     */
    activator = {
        /**
         * The default settings used by activators.
         * @property {ActivatorSettings} defaults
         */
        defaults: activatorSettings,
        /**
         * Creates a new activator.
         * @method create
         * @param {object} [initialActiveItem] The item which should be immediately activated upon creation of the ativator.
         * @param {ActivatorSettings} [settings] Per activator overrides of the default activator settings.
         * @return {Activator} The created activator.
         */
        create: createActivator,
        /**
         * Determines whether or not the provided object is an activator or not.
         * @method isActivator
         * @param {object} object Any object you wish to verify as an activator or not.
         * @return {boolean} True if the object is an activator; false otherwise.
         */
        isActivator:function(object){
            return object && object.__activator__;
        }
    };

    return activator;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * The composition module encapsulates all functionality related to visual composition.
 * @module composition
 * @requires system
 * @requires viewLocator
 * @requires binder
 * @requires viewEngine
 * @requires activator
 * @requires jquery
 * @requires knockout
 */
define('durandal/composition',['durandal/system', 'durandal/viewLocator', 'durandal/binder', 'durandal/viewEngine', 'durandal/activator', 'jquery', 'knockout'], function (system, viewLocator, binder, viewEngine, activator, $, ko) {
    var dummyModel = {},
        activeViewAttributeName = 'data-active-view',
        composition,
        compositionCompleteCallbacks = [],
        compositionCount = 0,
        compositionDataKey = 'durandal-composition-data',
        partAttributeName = 'data-part',
        bindableSettings = ['model', 'view', 'transition', 'area', 'strategy', 'activationData', 'onError'],
        visibilityKey = "durandal-visibility-data",
        composeBindings = ['compose:'];
    
    function onError(context, error, element) {
        try {
            if (context.onError) {
                try {
                    context.onError(error, element);
                } catch (e) {
                    system.error(e);
                }
            } else {
                system.error(error);
            }
        } finally {
            endComposition(context, element, true);
        }
    }

    function getHostState(parent) {
        var elements = [];
        var state = {
            childElements: elements,
            activeView: null
        };

        var child = ko.virtualElements.firstChild(parent);

        while (child) {
            if (child.nodeType == 1) {
                elements.push(child);
                if (child.getAttribute(activeViewAttributeName)) {
                    state.activeView = child;
                }
            }

            child = ko.virtualElements.nextSibling(child);
        }

        if(!state.activeView){
            state.activeView = elements[0];
        }

        return state;
    }

    function endComposition(context, element, error) {
        compositionCount--;

        if(compositionCount === 0) {
            var callBacks = compositionCompleteCallbacks;
            compositionCompleteCallbacks = [];
            
            if (!error) {
                setTimeout(function () {
                    var i = callBacks.length;

                    while (i--) {
                        try {
                            callBacks[i]();
                        } catch (e) {
                            onError(context, e, element);
                        }
                    }
                }, 1);
            }
        }

        cleanUp(context);
    }

    function cleanUp(context){
        delete context.activeView;
        delete context.viewElements;
    }

    function tryActivate(context, successCallback, skipActivation, element) {
        if(skipActivation){
            successCallback();
        } else if (context.activate && context.model && context.model.activate) {
            var result;

            try{
                if(system.isArray(context.activationData)) {
                    result = context.model.activate.apply(context.model, context.activationData);
                } else {
                    result = context.model.activate(context.activationData);
                }

                if(result && result.then) {
                    result.then(successCallback, function(reason) {
                        onError(context, reason, element);
                        successCallback();
                    });
                } else if(result || result === undefined) {
                    successCallback();
                } else {
                    endComposition(context, element);
                }
            }
            catch(e){
                onError(context, e, element);
            }
        } else {
            successCallback();
        }
    }

    function triggerAttach(context, element) {
        var context = this;

        if (context.activeView) {
            context.activeView.removeAttribute(activeViewAttributeName);
        }

        if (context.child) {
            try{
                if (context.model && context.model.attached) {
                    if (context.composingNewView || context.alwaysTriggerAttach) {
                        context.model.attached(context.child, context.parent, context);
                    }
                }

                if (context.attached) {
                    context.attached(context.child, context.parent, context);
                }

                context.child.setAttribute(activeViewAttributeName, true);

                if (context.composingNewView && context.model && context.model.detached) {
                    ko.utils.domNodeDisposal.addDisposeCallback(context.child, function () {
                        try{
                            context.model.detached(context.child, context.parent, context);
                        }catch(e2){
                            onError(context, e2, element);
                        }
                    });
                }
            }catch(e){
                onError(context, e, element);
            }
        }

        context.triggerAttach = system.noop;
    }

    function shouldTransition(context) {
        if (system.isString(context.transition)) {
            if (context.activeView) {
                if (context.activeView == context.child) {
                    return false;
                }

                if (!context.child) {
                    return true;
                }

                if (context.skipTransitionOnSameViewId) {
                    var currentViewId = context.activeView.getAttribute('data-view');
                    var newViewId = context.child.getAttribute('data-view');
                    return currentViewId != newViewId;
                }
            }

            return true;
        }

        return false;
    }

    function cloneNodes(nodesArray) {
        for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
            var clonedNode = nodesArray[i].cloneNode(true);
            newNodesArray.push(clonedNode);
        }
        return newNodesArray;
    }

    function replaceParts(context){
        var parts = cloneNodes(context.parts);
        var replacementParts = composition.getParts(parts);
        var standardParts = composition.getParts(context.child);

        for (var partId in replacementParts) {
            var toReplace = standardParts[partId];
            if (!toReplace) {
                toReplace = $('[data-part="' + partId + '"]', context.child).get(0);
                if (!toReplace) {
                    system.log('Could not find part to override: ' + partId);
                    continue;
                }
            }

            toReplace.parentNode.replaceChild(replacementParts[partId], toReplace);
        }
    }

    function removePreviousView(context){
        var children = ko.virtualElements.childNodes(context.parent), i, len;

        if(!system.isArray(children)){
            var arrayChildren = [];
            for(i = 0, len = children.length; i < len; i++){
                arrayChildren[i] = children[i];
            }
            children = arrayChildren;
        }

        for(i = 1,len = children.length; i < len; i++){
            ko.removeNode(children[i]);
        }
    }

    function hide(view) {
        ko.utils.domData.set(view, visibilityKey, view.style.display);
        view.style.display = 'none';
    }

    function show(view) {
        var displayStyle = ko.utils.domData.get(view, visibilityKey);
        view.style.display = displayStyle === 'none' ? 'block' : displayStyle;
    }

    function hasComposition(element){
        var dataBind = element.getAttribute('data-bind');
        if(!dataBind){
            return false;
        }

        for(var i = 0, length = composeBindings.length; i < length; i++){
            if(dataBind.indexOf(composeBindings[i]) > -1){
                return true;
            }
        }

        return false;
    }

    /**
     * @class CompositionTransaction
     * @static
     */
    var compositionTransaction = {
        /**
         * Registers a callback which will be invoked when the current composition transaction has completed. The transaction includes all parent and children compositions.
         * @method complete
         * @param {function} callback The callback to be invoked when composition is complete.
         */
        complete: function (callback) {
            compositionCompleteCallbacks.push(callback);
        }
    };

    /**
     * @class CompositionModule
     * @static
     */
    composition = {
        /**
         * An array of all the binding handler names (includeing :) that trigger a composition.
         * @property {string} composeBindings
         * @default ['compose:']
         */
        composeBindings:composeBindings,
        /**
         * Converts a transition name to its moduleId.
         * @method convertTransitionToModuleId
         * @param {string} name The name of the transtion.
         * @return {string} The moduleId.
         */
        convertTransitionToModuleId: function (name) {
            return 'transitions/' + name;
        },
        /**
         * The name of the transition to use in all compositions.
         * @property {string} defaultTransitionName
         * @default null
         */
        defaultTransitionName: null,
        /**
         * Represents the currently executing composition transaction.
         * @property {CompositionTransaction} current
         */
        current: compositionTransaction,
        /**
         * Registers a binding handler that will be invoked when the current composition transaction is complete.
         * @method addBindingHandler
         * @param {string} name The name of the binding handler.
         * @param {object} [config] The binding handler instance. If none is provided, the name will be used to look up an existing handler which will then be converted to a composition handler.
         * @param {function} [initOptionsFactory] If the registered binding needs to return options from its init call back to knockout, this function will server as a factory for those options. It will receive the same parameters that the init function does.
         */
        addBindingHandler:function(name, config, initOptionsFactory){
            var key,
                dataKey = 'composition-handler-' + name,
                handler;

            config = config || ko.bindingHandlers[name];
            initOptionsFactory = initOptionsFactory || function(){ return undefined;  };

            handler = ko.bindingHandlers[name] = {
                init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                    if(compositionCount > 0){
                        var data = {
                            trigger:ko.observable(null)
                        };

                        composition.current.complete(function(){
                            if(config.init){
                                config.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
                            }

                            if(config.update){
                                ko.utils.domData.set(element, dataKey, config);
                                data.trigger('trigger');
                            }
                        });

                        ko.utils.domData.set(element, dataKey, data);
                    }else{
                        ko.utils.domData.set(element, dataKey, config);

                        if(config.init){
                            config.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
                        }
                    }

                    return initOptionsFactory(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
                },
                update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                    var data = ko.utils.domData.get(element, dataKey);

                    if(data.update){
                        return data.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
                    }

                    if(data.trigger){
                        data.trigger();
                    }
                }
            };

            for (key in config) {
                if (key !== "init" && key !== "update") {
                    handler[key] = config[key];
                }
            }
        },
        /**
         * Gets an object keyed with all the elements that are replacable parts, found within the supplied elements. The key will be the part name and the value will be the element itself.
         * @method getParts
         * @param {DOMElement\DOMElement[]} elements The element(s) to search for parts.
         * @return {object} An object keyed by part.
         */
        getParts: function(elements, parts) {
            parts = parts || {};

            if (!elements) {
                return parts;
            }

            if (elements.length === undefined) {
                elements = [elements];
            }

            for (var i = 0, length = elements.length; i < length; i++) {
                var element = elements[i],
                    id;

                if (element.getAttribute) {
                    id = element.getAttribute(partAttributeName);
                    if (id) {
                        parts[id] = element;
                    }

                    if (element.hasChildNodes() && !hasComposition(element)) {
                        composition.getParts(element.childNodes, parts);
                    }
                }
            }

            return parts;
        },
        cloneNodes:cloneNodes,
        finalize: function (context, element) {
            if(context.transition === undefined) {
                context.transition = this.defaultTransitionName;
            }

            if(!context.child && !context.activeView){
                if (!context.cacheViews) {
                    ko.virtualElements.emptyNode(context.parent);
                }

                context.triggerAttach(context, element);
                endComposition(context, element);
            } else if (shouldTransition(context)) {
                var transitionModuleId = this.convertTransitionToModuleId(context.transition);

                system.acquire(transitionModuleId).then(function (transition) {
                    context.transition = transition;

                    transition(context).then(function () {
                        if (!context.cacheViews) {
                            if(!context.child){
                                ko.virtualElements.emptyNode(context.parent);
                            }else{
                                removePreviousView(context);
                            }
                        }else if(context.activeView){
                            var instruction = binder.getBindingInstruction(context.activeView);
                            if(instruction && instruction.cacheViews != undefined && !instruction.cacheViews){
                                ko.removeNode(context.activeView);
                            }else{
                                hide(context.activeView);
                            }
                        }

                        if (context.child) {
                            show(context.child);
                        }

                        context.triggerAttach(context, element);
                        endComposition(context, element);
                    });
                }).fail(function(err){
                    onError(context, 'Failed to load transition (' + transitionModuleId + '). Details: ' + err.message, element);
                });
            } else {
                if (context.child != context.activeView) {
                    if (context.cacheViews && context.activeView) {
                        var instruction = binder.getBindingInstruction(context.activeView);
                        if(!instruction || (instruction.cacheViews != undefined && !instruction.cacheViews)){
                            ko.removeNode(context.activeView);
                        }else{
                            hide(context.activeView);
                        }
                    }

                    if (!context.child) {
                        if (!context.cacheViews) {
                            ko.virtualElements.emptyNode(context.parent);
                        }
                    } else {
                        if (!context.cacheViews) {
                            removePreviousView(context);
                        }

                        show(context.child);
                    }
                }

                context.triggerAttach(context, element);
                endComposition(context, element);
            }
        },
        bindAndShow: function (child, element, context, skipActivation) {
            context.child = child;
            context.parent.__composition_context = context;

            if (context.cacheViews) {
                context.composingNewView = (ko.utils.arrayIndexOf(context.viewElements, child) == -1);
            } else {
                context.composingNewView = true;
            }

            tryActivate(context, function () {
                if (context.parent.__composition_context == context) {
                    try {
                        delete context.parent.__composition_context;
                    }
                    catch(e) {
                        context.parent.__composition_context = undefined;
                    }

                    if (context.binding) {
                        context.binding(context.child, context.parent, context);
                    }

                    if (context.preserveContext && context.bindingContext) {
                        if (context.composingNewView) {
                            if(context.parts){
                                replaceParts(context);
                            }

                            hide(child);
                            ko.virtualElements.prepend(context.parent, child);

                        binder.bindContext(context.bindingContext, child, context.model, context.as);
                        }
                    } else if (child) {
                        var modelToBind = context.model || dummyModel;
                        var currentModel = ko.dataFor(child);

                        if (currentModel != modelToBind) {
                            if (!context.composingNewView) {
                                ko.removeNode(child);
                                viewEngine.createView(child.getAttribute('data-view')).then(function(recreatedView) {
                                    composition.bindAndShow(recreatedView, element, context, true);
                                });
                                return;
                            }

                            if(context.parts){
                                replaceParts(context);
                            }

                            hide(child);
                            ko.virtualElements.prepend(context.parent, child);

                            binder.bind(modelToBind, child);
                        }
                    }

                    composition.finalize(context, element);
                } else {
                    endComposition(context, element);
                }
            }, skipActivation, element);
        },
        /**
         * Eecutes the default view location strategy.
         * @method defaultStrategy
         * @param {object} context The composition context containing the model and possibly existing viewElements.
         * @return {promise} A promise for the view.
         */
        defaultStrategy: function (context) {
            return viewLocator.locateViewForObject(context.model, context.area, context.viewElements);
        },
        getSettings: function (valueAccessor, element) {
            var value = valueAccessor(),
                settings = ko.utils.unwrapObservable(value) || {},
                activatorPresent = activator.isActivator(value),
                moduleId;

            if (system.isString(settings)) {
                if (viewEngine.isViewUrl(settings)) {
                    settings = {
                        view: settings
                    };
                } else {
                    settings = {
                        model: settings,
                        activate: !activatorPresent
                    };
                }

                return settings;
            }

            moduleId = system.getModuleId(settings);
            if (moduleId) {
                settings = {
                    model: settings,
                    activate: !activatorPresent
                };

                return settings;
            }

            if(!activatorPresent && settings.model) {
                activatorPresent = activator.isActivator(settings.model);
            }

            for (var attrName in settings) {
                if (ko.utils.arrayIndexOf(bindableSettings, attrName) != -1) {
                    settings[attrName] = ko.utils.unwrapObservable(settings[attrName]);
                } else {
                    settings[attrName] = settings[attrName];
                }
            }

            if (activatorPresent) {
                settings.activate = false;
            } else if (settings.activate === undefined) {
                settings.activate = true;
            }

            return settings;
        },
        executeStrategy: function (context, element) {
            context.strategy(context).then(function (child) {
                composition.bindAndShow(child, element, context);
            });
        },
        inject: function (context, element) {
            if (!context.model) {
                this.bindAndShow(null, element, context);
                return;
            }

            if (context.view) {
                viewLocator.locateView(context.view, context.area, context.viewElements).then(function (child) {
                    composition.bindAndShow(child, element, context);
                });
                return;
            }

            if (!context.strategy) {
                context.strategy = this.defaultStrategy;
            }

            if (system.isString(context.strategy)) {
                system.acquire(context.strategy).then(function (strategy) {
                    context.strategy = strategy;
                    composition.executeStrategy(context, element);
                }).fail(function (err) {
                    onError(context, 'Failed to load view strategy (' + context.strategy + '). Details: ' + err.message, element);
                });
            } else {
                this.executeStrategy(context, element);
            }
        },
        /**
         * Initiates a composition.
         * @method compose
         * @param {DOMElement} element The DOMElement or knockout virtual element that serves as the parent for the composition.
         * @param {object} settings The composition settings.
         * @param {object} [bindingContext] The current binding context.
         */
        compose: function (element, settings, bindingContext, fromBinding) {
            compositionCount++;

            if(!fromBinding){
                settings = composition.getSettings(function() { return settings; }, element);
            }

            if (settings.compositionComplete) {
                compositionCompleteCallbacks.push(function () {
                    settings.compositionComplete(settings.child, settings.parent, settings);
                });
            }

            compositionCompleteCallbacks.push(function () {
                if(settings.composingNewView && settings.model && settings.model.compositionComplete){
                    settings.model.compositionComplete(settings.child, settings.parent, settings);
                }
            });

            var hostState = getHostState(element);

            settings.activeView = hostState.activeView;
            settings.parent = element;
            settings.triggerAttach = triggerAttach;
            settings.bindingContext = bindingContext;

            if (settings.cacheViews && !settings.viewElements) {
                settings.viewElements = hostState.childElements;
            }

            if (!settings.model) {
                if (!settings.view) {
                    this.bindAndShow(null, element, settings);
                } else {
                    settings.area = settings.area || 'partial';
                    settings.preserveContext = true;

                    viewLocator.locateView(settings.view, settings.area, settings.viewElements).then(function (child) {
                        composition.bindAndShow(child, element, settings);
                    });
                }
            } else if (system.isString(settings.model)) {
                system.acquire(settings.model).then(function (module) {
                    settings.model = system.resolveObject(module);
                    composition.inject(settings, element);
                }).fail(function (err) {
                    onError(settings, 'Failed to load composed module (' + settings.model + '). Details: ' + err.message, element);
                });
            } else {
                composition.inject(settings, element);
            }
        }
    };

    ko.bindingHandlers.compose = {
        init: function() {
            return { controlsDescendantBindings: true };
        },
        update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var settings = composition.getSettings(valueAccessor, element);
            if(settings.mode){
                var data = ko.utils.domData.get(element, compositionDataKey);
                if(!data){
                    var childNodes = ko.virtualElements.childNodes(element);
                    data = {};

                    if(settings.mode === 'inline'){
                        data.view = viewEngine.ensureSingleElement(childNodes);
                    }else if(settings.mode === 'templated'){
                        data.parts = cloneNodes(childNodes);
                    }

                    ko.virtualElements.emptyNode(element);
                    ko.utils.domData.set(element, compositionDataKey, data);
                }

                if(settings.mode === 'inline'){
                    settings.view = data.view.cloneNode(true);
                }else if(settings.mode === 'templated'){
                    settings.parts = data.parts;
                }

                settings.preserveContext = true;
            }

            composition.compose(element, settings, bindingContext, true);
        }
    };

    ko.virtualElements.allowedBindings.compose = true;

    return composition;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * Durandal events originate from backbone.js but also combine some ideas from signals.js as well as some additional improvements.
 * Events can be installed into any object and are installed into the `app` module by default for convenient app-wide eventing.
 * @module events
 * @requires system
 */
define('durandal/events',['durandal/system'], function (system) {
    var eventSplitter = /\s+/;
    var Events = function() { };

    /**
     * Represents an event subscription.
     * @class Subscription
     */
    var Subscription = function(owner, events) {
        this.owner = owner;
        this.events = events;
    };

    /**
     * Attaches a callback to the event subscription.
     * @method then
     * @param {function} callback The callback function to invoke when the event is triggered.
     * @param {object} [context] An object to use as `this` when invoking the `callback`.
     * @chainable
     */
    Subscription.prototype.then = function (callback, context) {
        this.callback = callback || this.callback;
        this.context = context || this.context;
        
        if (!this.callback) {
            return this;
        }

        this.owner.on(this.events, this.callback, this.context);
        return this;
    };

    /**
     * Attaches a callback to the event subscription.
     * @method on
     * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, the previous callback will be re-activated.
     * @param {object} [context] An object to use as `this` when invoking the `callback`.
     * @chainable
     */
    Subscription.prototype.on = Subscription.prototype.then;

    /**
     * Cancels the subscription.
     * @method off
     * @chainable
     */
    Subscription.prototype.off = function () {
        this.owner.off(this.events, this.callback, this.context);
        return this;
    };

    /**
     * Creates an object with eventing capabilities.
     * @class Events
     */

    /**
     * Creates a subscription or registers a callback for the specified event.
     * @method on
     * @param {string} events One or more events, separated by white space.
     * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, a subscription instance is returned.
     * @param {object} [context] An object to use as `this` when invoking the `callback`.
     * @return {Subscription|Events} A subscription is returned if no callback is supplied, otherwise the events object is returned for chaining.
     */
    Events.prototype.on = function(events, callback, context) {
        var calls, event, list;

        if (!callback) {
            return new Subscription(this, events);
        } else {
            calls = this.callbacks || (this.callbacks = {});
            events = events.split(eventSplitter);

            while (event = events.shift()) {
                list = calls[event] || (calls[event] = []);
                list.push(callback, context);
            }

            return this;
        }
    };

    /**
     * Removes the callbacks for the specified events.
     * @method off
     * @param {string} [events] One or more events, separated by white space to turn off. If no events are specified, then the callbacks will be removed.
     * @param {function} [callback] The callback function to remove. If `callback` is not provided, all callbacks for the specified events will be removed.
     * @param {object} [context] The object that was used as `this`. Callbacks with this context will be removed.
     * @chainable
     */
    Events.prototype.off = function(events, callback, context) {
        var event, calls, list, i;

        // No events
        if (!(calls = this.callbacks)) {
            return this;
        }

        //removing all
        if (!(events || callback || context)) {
            delete this.callbacks;
            return this;
        }

        events = events ? events.split(eventSplitter) : system.keys(calls);

        // Loop through the callback list, splicing where appropriate.
        while (event = events.shift()) {
            if (!(list = calls[event]) || !(callback || context)) {
                delete calls[event];
                continue;
            }

            for (i = list.length - 2; i >= 0; i -= 2) {
                if (!(callback && list[i] !== callback || context && list[i + 1] !== context)) {
                    list.splice(i, 2);
                }
            }
        }

        return this;
    };

    /**
     * Triggers the specified events.
     * @method trigger
     * @param {string} [events] One or more events, separated by white space to trigger.
     * @chainable
     */
    Events.prototype.trigger = function(events) {
        var event, calls, list, i, length, args, all, rest;
        if (!(calls = this.callbacks)) {
            return this;
        }

        rest = [];
        events = events.split(eventSplitter);
        for (i = 1, length = arguments.length; i < length; i++) {
            rest[i - 1] = arguments[i];
        }

        // For each event, walk through the list of callbacks twice, first to
        // trigger the event, then to trigger any `"all"` callbacks.
        while (event = events.shift()) {
            // Copy callback lists to prevent modification.
            if (all = calls.all) {
                all = all.slice();
            }

            if (list = calls[event]) {
                list = list.slice();
            }

            // Execute event callbacks.
            if (list) {
                for (i = 0, length = list.length; i < length; i += 2) {
                    list[i].apply(list[i + 1] || this, rest);
                }
            }

            // Execute "all" callbacks.
            if (all) {
                args = [event].concat(rest);
                for (i = 0, length = all.length; i < length; i += 2) {
                    all[i].apply(all[i + 1] || this, args);
                }
            }
        }

        return this;
    };

    /**
     * Creates a function that will trigger the specified events when called. Simplifies proxying jQuery (or other) events through to the events object.
     * @method proxy
     * @param {string} events One or more events, separated by white space to trigger by invoking the returned function.
     * @return {function} Calling the function will invoke the previously specified events on the events object.
     */
    Events.prototype.proxy = function(events) {
        var that = this;
        return (function(arg) {
            that.trigger(events, arg);
        });
    };

    /**
     * Creates an object with eventing capabilities.
     * @class EventsModule
     * @static
     */

    /**
     * Adds eventing capabilities to the specified object.
     * @method includeIn
     * @param {object} targetObject The object to add eventing capabilities to.
     */
    Events.includeIn = function(targetObject) {
        targetObject.on = Events.prototype.on;
        targetObject.off = Events.prototype.off;
        targetObject.trigger = Events.prototype.trigger;
        targetObject.proxy = Events.prototype.proxy;
    };

    return Events;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * The app module controls app startup, plugin loading/configuration and root visual display.
 * @module app
 * @requires system
 * @requires viewEngine
 * @requires composition
 * @requires events
 * @requires jquery
 */
define('durandal/app',['durandal/system', 'durandal/viewEngine', 'durandal/composition', 'durandal/events', 'jquery'], function(system, viewEngine, composition, Events, $) {
    var app,
        allPluginIds = [],
        allPluginConfigs = [];

    function loadPlugins(){
        return system.defer(function(dfd){
            if(allPluginIds.length == 0){
                dfd.resolve();
                return;
            }

            system.acquire(allPluginIds).then(function(loaded){
                for(var i = 0; i < loaded.length; i++){
                    var currentModule = loaded[i];

                    if(currentModule.install){
                        var config = allPluginConfigs[i];
                        if(!system.isObject(config)){
                            config = {};
                        }

                        currentModule.install(config);
                        system.log('Plugin:Installed ' + allPluginIds[i]);
                    }else{
                        system.log('Plugin:Loaded ' + allPluginIds[i]);
                    }
                }

                dfd.resolve();
            }).fail(function(err){
                system.error('Failed to load plugin(s). Details: ' + err.message);
            });
        }).promise();
    }

    /**
     * @class AppModule
     * @static
     * @uses Events
     */
    app = {
        /**
         * The title of your application.
         * @property {string} title
         */
        title: 'Application',
        /**
         * Configures one or more plugins to be loaded and installed into the application.
         * @method configurePlugins
         * @param {object} config Keys are plugin names. Values can be truthy, to simply install the plugin, or a configuration object to pass to the plugin.
         * @param {string} [baseUrl] The base url to load the plugins from.
         */
        configurePlugins:function(config, baseUrl){
            var pluginIds = system.keys(config);
            baseUrl = baseUrl || 'plugins/';

            if(baseUrl.indexOf('/', baseUrl.length - 1) === -1){
                baseUrl += '/';
            }

            for(var i = 0; i < pluginIds.length; i++){
                var key = pluginIds[i];
                allPluginIds.push(baseUrl + key);
                allPluginConfigs.push(config[key]);
            }
        },
        /**
         * Starts the application.
         * @method start
         * @return {promise}
         */
        start: function() {
            system.log('Application:Starting');

            if (this.title) {
                document.title = this.title;
            }

            return system.defer(function (dfd) {
                $(function() {
                    loadPlugins().then(function(){
                        dfd.resolve();
                        system.log('Application:Started');
                    });
                });
            }).promise();
        },
        /**
         * Sets the root module/view for the application.
         * @method setRoot
         * @param {string} root The root view or module.
         * @param {string} [transition] The transition to use from the previous root (or splash screen) into the new root.
         * @param {string} [applicationHost] The application host element or id. By default the id 'applicationHost' will be used.
         */
        setRoot: function(root, transition, applicationHost) {
            var hostElement, settings = { activate:true, transition: transition };

            if (!applicationHost || system.isString(applicationHost)) {
                hostElement = document.getElementById(applicationHost || 'applicationHost');
            } else {
                hostElement = applicationHost;
            }

            if (system.isString(root)) {
                if (viewEngine.isViewUrl(root)) {
                    settings.view = root;
                } else {
                    settings.model = root;
                }
            } else {
                settings.model = root;
            }

            function finishComposition() {
                if(settings.model) {
                    if (settings.model.canActivate) {
                        try {
                            var result = settings.model.canActivate();
                            if (result && result.then) {
                                result.then(function (actualResult) {
                                    if (actualResult) {
                                        composition.compose(hostElement, settings);
                                    }
                                }).fail(function (err) {
                                    system.error(err);
                                });
                            } else if (result) {
                                composition.compose(hostElement, settings);
                            }
                        } catch (er) {
                            system.error(er);
                        }
                    } else {
                        composition.compose(hostElement, settings);
                    }
                } else {
                    composition.compose(hostElement, settings);
                }
            }

            if(system.isString(settings.model)) {
                system.acquire(settings.model).then(function(module) {
                    settings.model = system.resolveObject(module);
                    finishComposition();
                }).fail(function(err) {
                    system.error('Failed to load root module (' + settings.model + '). Details: ' + err.message);
                });
            } else {
                finishComposition();
            }
        }
    };

    Events.includeIn(app);

    return app;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * The dialog module enables the display of message boxes, custom modal dialogs and other overlays or slide-out UI abstractions. Dialogs are constructed by the composition system which interacts with a user defined dialog context. The dialog module enforced the activator lifecycle.
 * @module dialog
 * @requires system
 * @requires app
 * @requires composition
 * @requires activator
 * @requires viewEngine
 * @requires jquery
 * @requires knockout
 */
define('plugins/dialog',['durandal/system', 'durandal/app', 'durandal/composition', 'durandal/activator', 'durandal/viewEngine', 'jquery', 'knockout'], function (system, app, composition, activator, viewEngine, $, ko) {
    var contexts = {},
        dialogCount = ko.observable(0),
        dialog;

    /**
     * Models a message box's message, title and options.
     * @class MessageBox
     */
    var MessageBox = function (message, title, options, autoclose, settings) {
        this.message = message;
        this.title = title || MessageBox.defaultTitle;
        this.options = options || MessageBox.defaultOptions;
        this.autoclose = autoclose || false;
        this.settings = $.extend({}, MessageBox.defaultSettings, settings);
    };

    /**
     * Selects an option and closes the message box, returning the selected option through the dialog system's promise.
     * @method selectOption
     * @param {string} dialogResult The result to select.
     */
    MessageBox.prototype.selectOption = function (dialogResult) {
        dialog.close(this, dialogResult);
    };

    /**
     * Provides the view to the composition system.
     * @method getView
     * @return {DOMElement} The view of the message box.
     */
    MessageBox.prototype.getView = function () {
        return viewEngine.processMarkup(MessageBox.defaultViewMarkup);
    };

    /**
     * Configures a custom view to use when displaying message boxes.
     * @method setViewUrl
     * @param {string} viewUrl The view url relative to the base url which the view locator will use to find the message box's view.
     * @static
     */
    MessageBox.setViewUrl = function (viewUrl) {
        delete MessageBox.prototype.getView;
        MessageBox.prototype.viewUrl = viewUrl;
    };

    /**
     * The title to be used for the message box if one is not provided.
     * @property {string} defaultTitle
     * @default Application
     * @static
     */
    MessageBox.defaultTitle = app.title || 'Application';

    /**
     * The options to display in the message box if none are specified.
     * @property {string[]} defaultOptions
     * @default ['Ok']
     * @static
     */
    MessageBox.defaultOptions = ['Ok'];

    
    MessageBox.defaultSettings = { buttonClass: "btn btn-default", primaryButtonClass: "btn-primary autofocus", secondaryButtonClass: "", "class": "modal-content messageBox", style: null };

    /**
    * Sets the classes and styles used throughout the message box markup.
    * @method setDefaults
    * @param {object} settings A settings object containing the following optional properties: buttonClass, primaryButtonClass, secondaryButtonClass, class, style.
    */
    MessageBox.setDefaults = function (settings) {
        $.extend(MessageBox.defaultSettings, settings);
    };

    MessageBox.prototype.getButtonClass = function ($index) {
        var c = "";
        if (this.settings) {
            if (this.settings.buttonClass) {
                c = this.settings.buttonClass;
            }
            if ($index() === 0 && this.settings.primaryButtonClass) {
                if (c.length > 0) {
                    c += " ";
                }
                c += this.settings.primaryButtonClass;
            }
            if ($index() > 0 && this.settings.secondaryButtonClass) {
                if (c.length > 0) {
                    c += " ";
                }
                c += this.settings.secondaryButtonClass;
            }
        }
        return c;
    };

    MessageBox.prototype.getClass = function () {
        if (this.settings) {
            return this.settings["class"];
        }
        return "messageBox";
    };

    MessageBox.prototype.getStyle = function () {
        if (this.settings) {
            return this.settings.style;
        }
        return null;
    };

    MessageBox.prototype.getButtonText = function (stringOrObject) {
        var t = $.type(stringOrObject);
        if (t === "string") {
            return stringOrObject;
        }
        else if (t === "object") {
            if ($.type(stringOrObject.text) === "string") {
                return stringOrObject.text;
            } else {
                system.error('The object for a MessageBox button does not have a text property that is a string.');
                return null;
            }
        }
        system.error('Object for a MessageBox button is not a string or object but ' + t + '.');
        return null;
    };

    MessageBox.prototype.getButtonValue = function (stringOrObject) {
        var t = $.type(stringOrObject);
        if (t === "string") {
            return stringOrObject;
        }
        else if (t === "object") {
            if ($.type(stringOrObject.value) === "undefined") {
                system.error('The object for a MessageBox button does not have a value property defined.');
                return null;
            } else {
                return stringOrObject.value;
            }
        }
        system.error('Object for a MessageBox button is not a string or object but ' + t + '.');
        return null;
    };

    /**
     * The markup for the message box's view.
     * @property {string} defaultViewMarkup
     * @static
     */
    MessageBox.defaultViewMarkup = [
        '<div data-view="plugins/messageBox" data-bind="css: getClass(), style: getStyle()">',
            '<div class="modal-header">',
                '<h3 data-bind="html: title"></h3>',
            '</div>',
            '<div class="modal-body">',
                '<p class="message" data-bind="html: message"></p>',
            '</div>',
            '<div class="modal-footer">',
                '<!-- ko foreach: options -->',
                '<button data-bind="click: function () { $parent.selectOption($parent.getButtonValue($data)); }, text: $parent.getButtonText($data), css: $parent.getButtonClass($index)"></button>',
                '<!-- /ko -->',
                '<div style="clear:both;"></div>',
            '</div>',
        '</div>'
    ].join('\n');

    function ensureDialogInstance(objOrModuleId) {
        return system.defer(function (dfd) {
            if (system.isString(objOrModuleId)) {
                system.acquire(objOrModuleId).then(function (module) {
                    dfd.resolve(system.resolveObject(module));
                }).fail(function (err) {
                    system.error('Failed to load dialog module (' + objOrModuleId + '). Details: ' + err.message);
                });
            } else {
                dfd.resolve(objOrModuleId);
            }
        }).promise();
    }

    /**
     * @class DialogModule
     * @static
     */
    dialog = {
        /**
         * The constructor function used to create message boxes.
         * @property {MessageBox} MessageBox
         */
        MessageBox: MessageBox,
        /**
         * The css zIndex that the last dialog was displayed at.
         * @property {number} currentZIndex
         */
        currentZIndex: 1050,
        /**
         * Gets the next css zIndex at which a dialog should be displayed.
         * @method getNextZIndex
         * @return {number} The next usable zIndex.
         */
        getNextZIndex: function () {
            return ++this.currentZIndex;
        },
        /**
         * Determines whether or not there are any dialogs open.
         * @method isOpen
         * @return {boolean} True if a dialog is open. false otherwise.
         */
        isOpen: ko.computed(function() {
            return dialogCount() > 0;
        }),
        /**
         * Gets the dialog context by name or returns the default context if no name is specified.
         * @method getContext
         * @param {string} [name] The name of the context to retrieve.
         * @return {DialogContext} True context.
         */
        getContext: function (name) {
            return contexts[name || 'default'];
        },
        /**
         * Adds (or replaces) a dialog context.
         * @method addContext
         * @param {string} name The name of the context to add.
         * @param {DialogContext} dialogContext The context to add.
         */
        addContext: function (name, dialogContext) {
            dialogContext.name = name;
            contexts[name] = dialogContext;

            var helperName = 'show' + name.substr(0, 1).toUpperCase() + name.substr(1);
            this[helperName] = function (obj, activationData) {
                return this.show(obj, activationData, name);
            };
        },
        createCompositionSettings: function (obj, dialogContext) {
            var settings = {
                model: obj,
                activate: false,
                transition: false
            };

            if (dialogContext.binding) {
                settings.binding = dialogContext.binding;
            }

            if (dialogContext.attached) {
                settings.attached = dialogContext.attached;
            }

            if (dialogContext.compositionComplete) {
                settings.compositionComplete = dialogContext.compositionComplete;
            }

            return settings;
        },
        /**
         * Gets the dialog model that is associated with the specified object.
         * @method getDialog
         * @param {object} obj The object for whom to retrieve the dialog.
         * @return {Dialog} The dialog model.
         */
        getDialog: function (obj) {
            if (obj) {
                return obj.__dialog__;
            }

            return undefined;
        },
        /**
         * Closes the dialog associated with the specified object.
         * @method close
         * @param {object} obj The object whose dialog should be closed.
         * @param {object} results* The results to return back to the dialog caller after closing.
         */
        close: function (obj) {
            var theDialog = this.getDialog(obj);
            if (theDialog) {
                var rest = Array.prototype.slice.call(arguments, 1);
                theDialog.close.apply(theDialog, rest);
            }
        },
        /**
         * Shows a dialog.
         * @method show
         * @param {object|string} obj The object (or moduleId) to display as a dialog.
         * @param {object} [activationData] The data that should be passed to the object upon activation.
         * @param {string} [context] The name of the dialog context to use. Uses the default context if none is specified.
         * @return {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing.
         */
        show: function (obj, activationData, context) {
            var that = this;
            var dialogContext = contexts[context || 'default'];

            return system.defer(function (dfd) {
                ensureDialogInstance(obj).then(function (instance) {
                    var dialogActivator = activator.create();

                    dialogActivator.activateItem(instance, activationData).then(function (success) {
                        if (success) {
                            var theDialog = instance.__dialog__ = {
                                owner: instance,
                                context: dialogContext,
                                activator: dialogActivator,
                                close: function () {
                                    var args = arguments;
                                    dialogActivator.deactivateItem(instance, true).then(function (closeSuccess) {
                                        if (closeSuccess) {
                                            dialogCount(dialogCount() - 1);
                                            dialogContext.removeHost(theDialog);
                                            delete instance.__dialog__;

                                            if (args.length === 0) {
                                                dfd.resolve();
                                            } else if (args.length === 1) {
                                                dfd.resolve(args[0]);
                                            } else {
                                                dfd.resolve.apply(dfd, args);
                                            }
                                        }
                                    });
                                }
                            };

                            theDialog.settings = that.createCompositionSettings(instance, dialogContext);
                            dialogContext.addHost(theDialog);

                            dialogCount(dialogCount() + 1);
                            composition.compose(theDialog.host, theDialog.settings);
                        } else {
                            dfd.resolve(false);
                        }
                    });
                });
            }).promise();
        },
        /**
         * Shows a message box.
         * @method showMessage
         * @param {string} message The message to display in the dialog.
         * @param {string} [title] The title message.
         * @param {string[]} [options] The options to provide to the user.
         * @param {boolean} [autoclose] Automatically close the the message box when clicking outside?
         * @param {Object} [settings] Custom settings for this instance of the messsage box, used to change classes and styles.
         * @return {Promise} A promise that resolves when the message box is closed and returns the selected option.
         */
        showMessage: function (message, title, options, autoclose, settings) {
            if (system.isString(this.MessageBox)) {
                return dialog.show(this.MessageBox, [
                    message,
                    title || MessageBox.defaultTitle,
                    options || MessageBox.defaultOptions,
                    autoclose || false,
                    settings || {}
                ]);
            }

            return dialog.show(new this.MessageBox(message, title, options, autoclose, settings));
        },
        /**
         * Installs this module into Durandal; called by the framework. Adds `app.showDialog` and `app.showMessage` convenience methods.
         * @method install
         * @param {object} [config] Add a `messageBox` property to supply a custom message box constructor. Add a `messageBoxView` property to supply custom view markup for the built-in message box. You can also use messageBoxViewUrl to specify the view url.
         */
        install: function (config) {
            app.showDialog = function (obj, activationData, context) {
                return dialog.show(obj, activationData, context);
            };

            app.closeDialog = function () {
                return dialog.close.apply(dialog, arguments);
            };

            app.showMessage = function (message, title, options, autoclose, settings) {
                return dialog.showMessage(message, title, options, autoclose, settings);
            };

            if (config.messageBox) {
                dialog.MessageBox = config.messageBox;
            }

            if (config.messageBoxView) {
                dialog.MessageBox.prototype.getView = function () {
                    return viewEngine.processMarkup(config.messageBoxView);
                };
            }

            if (config.messageBoxViewUrl) {
                dialog.MessageBox.setViewUrl(config.messageBoxViewUrl);
            }
        }
    };

    /**
     * @class DialogContext
     */
    dialog.addContext('default', {
        blockoutOpacity: 0.2,
        removeDelay: 200,
        minYMargin: 5,
        minXMargin: 5,
        /**
         * In this function, you are expected to add a DOM element to the tree which will serve as the "host" for the modal's composed view. You must add a property called host to the modalWindow object which references the dom element. It is this host which is passed to the composition module.
         * @method addHost
         * @param {Dialog} theDialog The dialog model.
         */
        addHost: function (theDialog) {
            var body = $('body');
            var blockout = $('<div class="modalBlockout"></div>')
                .css({ 'z-index': dialog.getNextZIndex(), 'opacity': this.blockoutOpacity })
                .appendTo(body);

            var host = $('<div class="modalHost"></div>')
                .css({ 'z-index': dialog.getNextZIndex() })
                .appendTo(body);

            theDialog.host = host.get(0);
            theDialog.blockout = blockout.get(0);

            if (!dialog.isOpen()) {
                theDialog.oldBodyMarginRight = body.css("margin-right");
                theDialog.oldInlineMarginRight = body.get(0).style.marginRight;

                var html = $("html");
                var oldBodyOuterWidth = body.outerWidth(true);
                var oldScrollTop = html.scrollTop();
                $("html").css("overflow-y", "hidden");
                var newBodyOuterWidth = $("body").outerWidth(true);
                body.css("margin-right", (newBodyOuterWidth - oldBodyOuterWidth + parseInt(theDialog.oldBodyMarginRight, 10)) + "px");
                html.scrollTop(oldScrollTop); // necessary for Firefox
            }
        },
        /**
         * This function is expected to remove any DOM machinery associated with the specified dialog and do any other necessary cleanup.
         * @method removeHost
         * @param {Dialog} theDialog The dialog model.
         */
        removeHost: function (theDialog) {
            $(theDialog.host).css('opacity', 0);
            $(theDialog.blockout).css('opacity', 0);

            setTimeout(function () {
                ko.removeNode(theDialog.host);
                ko.removeNode(theDialog.blockout);
            }, this.removeDelay);

            if (!dialog.isOpen()) {
                var html = $("html");
                var oldScrollTop = html.scrollTop(); // necessary for Firefox.
                html.css("overflow-y", "").scrollTop(oldScrollTop);

                if (theDialog.oldInlineMarginRight) {
                    $("body").css("margin-right", theDialog.oldBodyMarginRight);
                } else {
                    $("body").css("margin-right", '');
                }
            }
        },
        attached: function (view) {
            //To prevent flickering in IE8, we set visibility to hidden first, and later restore it
            $(view).css("visibility", "hidden");
        },
        /**
         * This function is called after the modal is fully composed into the DOM, allowing your implementation to do any final modifications, such as positioning or animation. You can obtain the original dialog object by using `getDialog` on context.model.
         * @method compositionComplete
         * @param {DOMElement} child The dialog view.
         * @param {DOMElement} parent The parent view.
         * @param {object} context The composition context.
         */
        compositionComplete: function (child, parent, context) {
            var theDialog = dialog.getDialog(context.model);
            var $child = $(child);
            var loadables = $child.find("img").filter(function () {
                //Remove images with known width and height
                var $this = $(this);
                return !(this.style.width && this.style.height) && !($this.attr("width") && $this.attr("height"));
            });

            $child.data("predefinedWidth", $child.get(0).style.width);

            var setDialogPosition = function (childView, objDialog) {
                //Setting a short timeout is need in IE8, otherwise we could do this straight away
                setTimeout(function () {
                    var $childView = $(childView);

                    objDialog.context.reposition(childView);

                    $(objDialog.host).css('opacity', 1);
                    $childView.css("visibility", "visible");

                    $childView.find('.autofocus').first().focus();
                }, 1);
            };

            setDialogPosition(child, theDialog);
            loadables.load(function () {
                setDialogPosition(child, theDialog);
            });

            if ($child.hasClass('autoclose') || context.model.autoclose) {
                $(theDialog.blockout).click(function () {
                    theDialog.close();
                });
            }
        },
        /**
         * This function is called to reposition the model view.
         * @method reposition
         * @param {DOMElement} view The dialog view.
         */
        reposition: function (view) {
            var $view = $(view),
                $window = $(window);

            //We will clear and then set width for dialogs without width set 
            if (!$view.data("predefinedWidth")) {
                $view.css({ width: '' }); //Reset width
            }
			
			// clear the height
            $view.css({ height: '' });

            var width = $view.outerWidth(false),
                height = $view.outerHeight(false),
                windowHeight = $window.height() - 2 * this.minYMargin, //leave at least some pixels free
                windowWidth = $window.width() - 2 * this.minXMargin, //leave at least some pixels free
                constrainedHeight = Math.min(height, windowHeight),
                constrainedWidth = Math.min(width, windowWidth);

            $view.css({
                'margin-top': (-constrainedHeight / 2).toString() + 'px',
                'margin-left': (-constrainedWidth / 2).toString() + 'px'
            });

            if (height > windowHeight) {
                $view.css("overflow-y", "auto").outerHeight(windowHeight);
            } else {
                $view.css({
                    "overflow-y": "",
                    "height": ""
                });
            }

            if (width > windowWidth) {
                $view.css("overflow-x", "auto").outerWidth(windowWidth);
            } else {
                $view.css("overflow-x", "");

                if (!$view.data("predefinedWidth")) {
                    //Ensure the correct width after margin-left has been set
                    $view.outerWidth(constrainedWidth);
                } else {
                    $view.css("width", $view.data("predefinedWidth"));
                }
            }
        }
    });

    return dialog;
});

define('core/messageBox',["require", "exports", 'durandal/app', 'plugins/dialog'], function (require, exports, durandalApp, durandalDialog) {
    exports.ok = $.i18n.t('common.ok');
    exports.cancel = $.i18n.t('common.cancel');
    exports.yes = $.i18n.t('common.yes');
    exports.no = $.i18n.t('common.no');
    exports.save = $.i18n.t('common.save');
    exports.sync = $.i18n.t('common.sync');
    exports.revert = $.i18n.t('common.revert');
    exports.del = $.i18n.t('common.delete');
    exports.open = $.i18n.t('common.open');
    exports.remove = $.i18n.t('common.remove');
    exports.buttons = {
        okOnly: [exports.ok],
        okCancel: [exports.ok, exports.cancel],
        yesNo: [exports.yes, exports.no],
        yesCancel: [exports.yes, exports.cancel],
        yesNoCancel: [exports.yes, exports.no, exports.cancel],
        saveCancel: [exports.save, exports.cancel],
        saveRevertCancel: [exports.save, exports.revert, exports.cancel],
        saveDeleteCancel: [exports.save, exports.del, exports.cancel],
        openCancel: [exports.open, exports.cancel],
        removeCancel: [exports.remove, exports.cancel],
    };
    function show(titleResourceKey, messageResourceKey, buttons, messageFormatReplacements, titleFormatReplacements) {
        var message = $.i18n.t(messageResourceKey);
        if (messageFormatReplacements) {
            message = message.format.apply(message, messageFormatReplacements);
        }
        var title = $.i18n.t(titleResourceKey);
        if (titleFormatReplacements) {
            title = title.format.apply(title, titleFormatReplacements);
        }
        app.busyIndicator.isTempReady(true);
        return Q(durandalApp.showMessage(message, title, buttons)).then(function (value) {
            app.busyIndicator.isTempReady(false);
            return value;
        });
    }
    exports.show = show;
    var dialogExtended = false;
    if (!dialogExtended) {
        dialogExtended = true;
        durandalDialog.MessageBox['defaultSettings']['buttonClass'] = 'btn';
        var messageBoxPrototype = durandalDialog.MessageBox.prototype, originalGetView = messageBoxPrototype.getView;
        messageBoxPrototype.getView = function () {
            var view = originalGetView(), commands, self = this;
            $(view).on('keydown', function (event) {
                switch (event.which) {
                    case 89:
                        commands = [exports.yes];
                        break;
                    case 78:
                        commands = [exports.no];
                        break;
                    case 13:
                        commands = [exports.ok, exports.yes, exports.open, exports.save];
                        break;
                    case 27:
                        commands = [exports.cancel];
                        break;
                    case 83:
                        commands = [exports.save];
                        break;
                    case 82:
                        commands = [exports.remove, exports.revert];
                        break;
                    case 68:
                        commands = [exports.del];
                        break;
                    case 67:
                        commands = [exports.cancel];
                        break;
                    default:
                        return;
                }
                for (var i = 0; i < commands.length; i++) {
                    if (self.options.filter(function (option) { return option === commands[i]; }).length === 1) {
                        self.selectOption(commands[i]);
                        event.preventDefault();
                        return;
                    }
                }
            });
            var setFocus = sessionStorage.getItem('msgBoxSetFocus');
            if (setFocus != null && setFocus != undefined && setFocus == '1') {
                sessionStorage.removeItem('msgBoxSetFocus');
                setFocusToHeaderText(view);
            }
            return view;
        };
        messageBoxPrototype.activate = function () {
            app.modal = this;
        };
        messageBoxPrototype.deactivate = function () {
            app.modal = null;
        };
    }
    function setFocusToHeaderText(view) {
        var header = $(view).find('div.modal-header h3');
        if (header != null && header != undefined && header.length > 0) {
            header[0].setAttribute('tabindex', '0');
            header.addClass('autofocus');
            header[0].setAttribute('aria-label', 'There are multiple lines in this message.');
            header.focus(function (e) {
                $(e.target).css("border", "thin solid black");
                $(e.target)[0].setAttribute('aria-label', 'There are multiple lines in this message.' + $(e.target)[0].textContent);
            });
            header.blur(function (e) {
                $(e.target).css("border", "");
            });
        }
        var title = $(view).find('div.modal-body p');
        if (title != null && title != undefined && title.length > 0) {
            title[0].setAttribute('tabindex', '0');
            title.focus(function (e) {
                $(e.target).css("border", "thin solid black");
            });
            title.blur(function (e) {
                $(e.target).css("border", "");
            });
        }
    }
});

define('core/logger',["require", "exports", 'core/constants', 'core/util', 'core/messageBox', 'plugins/dialog'], function (require, exports, constants, util, messageBox, durandalDialog) {
    function initialize() {
        Q.onerror = unhandledExceptionHandler;
        var originalOnError = window.onerror;
        window.onerror = function (eventOrMessage, sourceOrUri, filenoOrLineNumber, columnNumber) {
            if (originalOnError)
                originalOnError.apply(window, arguments);
            if (typeof eventOrMessage === 'string' || eventOrMessage instanceof String)
                onErrorSignature2(eventOrMessage, sourceOrUri, filenoOrLineNumber, columnNumber);
            else
                onErrorSignature1(eventOrMessage, sourceOrUri, filenoOrLineNumber, columnNumber);
        };
    }
    exports.initialize = initialize;
    function logInfo(message) {
        var objInfo = {
            message: message,
            database: User.Current.Database,
            user: User.Current.UserId
        };
        var serialized = safeStringify(objInfo);
        Q($.ajax(constants.services.serviceBaseUrl + 'Log/Info', {
            data: serialized,
            contentType: 'text/plain',
            type: 'POST'
        })).fail(function (reason) {
            console.error('Failed to log');
        }).done();
    }
    exports.logInfo = logInfo;
    function logUserAction(message) {
        localforage.getItem('user-actions-history').then(function (currentData) {
            localforage.setItem('user-actions-history', new Date() + ' - ' + message + '\n' + currentData);
        });
    }
    exports.logUserAction = logUserAction;
    function onErrorSignature1(event, source, fileno, columnNumber) {
        unhandledExceptionHandler({ event: event, source: source, fileno: fileno, columnNumber: columnNumber });
    }
    function onErrorSignature2(message, uri, lineNumber, columnNumber) {
        unhandledExceptionHandler({ message: message, uri: uri, lineNumber: lineNumber, columnNumber: columnNumber });
    }
    var nextErrorIndex = 0;
    var errorMessagesShowing = 0;
    function unhandledExceptionHandler(reason) {
        if (reason.message === "SaveAssessmentTransactionRollbacked") {
            messageBox.show('Warning', 'common.timeoutWarning', messageBox.buttons.okOnly).done();
            return;
        }
        var serializedError, encodedError, message, detailsHeight = $(window).height() / 3, errorIndex = nextErrorIndex++, context = {
            url: window.location.href,
            version: app.longVersion,
            datetime: moment().format(),
            timezone: jstz.determine().name(),
            applicationLifetime: (moment().diff(moment(app.startDateTime), 'seconds') / 60).toFixed(1) + ' minutes',
            sessionErrors: errorIndex,
            userAgent: navigator.userAgent,
            instance: app.instanceId,
        };
        if (User.IsLoggedIn) {
            context.userId = User.Current.UserId;
            context.sqlServer = User.Current.SqlServer;
            context.database = User.Current.Database;
        }
        var reasonWithoutPassInfo = reason;
        var passwordIsInInfo = false;
        var serializedErrorWithPassword = '';
        if (reasonWithoutPassInfo['_retryState'] != null) {
            if (reasonWithoutPassInfo['_retryState']['options'] != null) {
                if (reasonWithoutPassInfo['_retryState']['options']['data'] != null) {
                    if (reasonWithoutPassInfo['_retryState']['options']['data']['Password'] != null) {
                        passwordIsInInfo = true;
                        context.exception = reason;
                        serializedErrorWithPassword = safeStringify(context);
                        delete reasonWithoutPassInfo['_retryState']['options']['data']['Password'];
                    }
                }
            }
        }
        context.exception = reasonWithoutPassInfo;
        try {
            serializedError = safeStringify(context);
        }
        catch (e) {
            serializedError = '[unable to serialize error]';
        }
        encodedError = htmlEncode(serializedError);
        message = '<pre id="error-' + errorIndex.toString() + '" style="max-height: ' + detailsHeight.toString() + 'px; overflow: auto; display: block;">' + encodedError + '</pre>' + '<button id="error-select-all-' + errorIndex.toString() + '" class="btn">Select All</button>';
        if (passwordIsInInfo) {
            serializedError = serializedErrorWithPassword;
        }
        Q($.ajax(constants.services.serviceBaseUrl + 'Log/Error', {
            data: serializedError,
            contentType: 'text/plain',
            type: 'POST'
        })).fail(function (reason) {
            if (util.isConnectionFailure(reason)) {
            }
        }).done();
        if (errorMessagesShowing > 2) {
            return;
        }
        errorMessagesShowing++;
        messageBox.show('common.error', 'common.errorMessage', messageBox.buttons.okOnly, [message]).finally(function () { return errorMessagesShowing--; }).done();
        $('#error-select-all-' + errorIndex.toString()).on('click', function (event) {
            if (/msie/i.test(navigator.userAgent)) {
                durandalDialog.showMessage('Select All');
                setTimeout(function () { return durandalDialog.close(app.modal); }, 10);
            }
            var element = document.getElementById('error-' + errorIndex.toString()), selection = window.getSelection(), range = document.createRange();
            range.selectNodeContents(element);
            selection.removeAllRanges();
            selection.addRange(range);
            selection.addRange(range);
        });
    }
    function safeStringify(obj) {
        var cache = [];
        return JSON.stringify(obj, function (key, value) {
            if (typeof value === 'object' && value !== null) {
                if (cache.indexOf(value) !== -1) {
                    return '[already serialized]';
                }
                if (cache.length > 2000) {
                    return '[object count exceeded]';
                }
                if (value.metadataStore) {
                    return '[skipped- has metadataStore property]';
                }
                if (value instanceof Error) {
                    var error = {};
                    Object.getOwnPropertyNames(value).forEach(function (key) {
                        error[key] = value[key];
                    });
                    return error;
                }
                cache.push(value);
            }
            return value;
        }, 4);
    }
});

define('assessmentTracker/mobileAssessmentTracker',["require", "exports", 'core/storage', 'entities/core'], function (require, exports, storage, core) {
    function SaveOfflineAssessment(assesskey, assessdata) {
        var data = { "mobileassessmentkey": assesskey, "mobileassessmentdata": assessdata };
        var settings = jQuery.ajaxSettings;
        settings.type = 'POST';
        settings.dataType = 'json';
        settings.contentType = 'application/json; charset=utf-8';
        settings.url = app.assessmentTrackerServer + '/MobileAssessmentTracker/api/AssessmentTracker';
        settings.processData = false;
        settings.data = JSON.stringify(data);
        $.ajax(settings);
    }
    exports.SaveOfflineAssessment = SaveOfflineAssessment;
    function getStartupAssessmentTrackerMenu() {
        var menu;
        var key;
        key = 'TrackOfflineAssessments';
        return Q(localforage.getItem(key).then(function (value) {
            if (value === null) {
                localforage.setItem(key, 'false');
                menu = "Start Offline Assessment Tracker";
                return menu;
            }
            else if (value === 'false') {
                menu = "Start Offline Assessment Tracker";
                return menu;
            }
            else if (value === 'true') {
                menu = "Stop Offline Assessment Tracker";
                return menu;
            }
        }));
    }
    exports.getStartupAssessmentTrackerMenu = getStartupAssessmentTrackerMenu;
    function getClickAssessmentTrackerMenu() {
        if (event.type == 'click') {
            var menu;
            var key;
            key = 'TrackOfflineAssessments';
            return Q(localforage.getItem(key).then(function (value) {
                if (value === 'false') {
                    localforage.setItem(key, 'true');
                    menu = "Stop Offline Assessment Tracker";
                    return menu;
                }
                else if (value === 'true') {
                    localforage.setItem(key, 'false');
                    menu = "Start Offline Assessment Tracker";
                    return menu;
                }
            }));
        }
    }
    exports.getClickAssessmentTrackerMenu = getClickAssessmentTrackerMenu;
    function storeOfflineAssesment(entityManager, lupdateDateTime) {
        var fullyQualifiedId = core.getFullyQualifiedId(entityManager.entity), json = entityManager.exportEntities(), status = entityManager.entity.entityAspect.entityState.toString();
        var offlineAssessmentKey;
        if (app.saveConfig.toUpperCase() === 'SAVELATEST') {
            offlineAssessmentKey = fullyQualifiedId + '_OfflineAssessmentTracker';
        }
        else if (app.saveConfig.toUpperCase() === 'SAVEALL') {
            offlineAssessmentKey = fullyQualifiedId + '_OfflineAssessmentTracker_' + lupdateDateTime.toLocaleString();
        }
        return storage.setItem(offlineAssessmentKey, json, core.storageOptions, lupdateDateTime, false, status);
    }
    exports.storeOfflineAssesment = storeOfflineAssesment;
    function trackOfflineAssessment() {
        var key;
        key = 'TrackOfflineAssessments';
        return Q(localforage.getItem(key).then(function (value) {
            if (value === 'true') {
                return true;
            }
            return false;
        })).then(function (value) {
            return value;
        });
    }
    exports.trackOfflineAssessment = trackOfflineAssessment;
    function getOfflineAssessmentKeys() {
        localforage.length().then(function (numberOfKeys) {
            return numberOfKeys;
        }).then(function (numKeys) {
            localforage.keys().then(function (keys) {
                var i = 0;
                for (i == 0; i < numKeys; i++) {
                    if (keys[i].indexOf('offlineassessmenttracker') > 0) {
                        getOfflineAssessment(keys[i]);
                    }
                }
            });
        });
        function getOfflineAssessment(assessmentKey) {
            var keyIndex = nthIndex(assessmentKey, '/', 3);
            var fullyQualifiedId = assessmentKey.substring(keyIndex + 1);
            storage.getItem(fullyQualifiedId, core.storageOptions, false).then(function (assessment) {
                return assessment;
            }).then(function (assess) {
                SaveOfflineAssessment(assessmentKey, assess.data);
                return assessmentKey;
            }).then(function (dkey) {
                if (app.deleteAfterSave) {
                    localforage.removeItem(dkey);
                }
            });
        }
        function nthIndex(str, pat, n) {
            var L = str.length, i = -1;
            while (n-- && i++ < L) {
                i = str.indexOf(pat, i);
                if (i < 0)
                    break;
            }
            return i;
        }
    }
    exports.getOfflineAssessmentKeys = getOfflineAssessmentKeys;
});

define('entities/softsave',["require", "exports", 'core/util', 'core/storage', 'entities/cache', 'entities/core', 'entities/keys', 'entities/registry', 'entities/sync', 'entities/url', 'core/logger', 'assessmentTracker/mobileAssessmentTracker'], function (require, exports, util, storage, cache, core, keys, registry, sync, url, logger, mtracker) {
    var SoftSaveManager = (function () {
        function SoftSaveManager(entityManager) {
            this.entityManager = entityManager;
            this.isTracking = false;
            this.entityChangedSubscriptionToken = this.entityManager.entityChanged.subscribe(this.handleEntityChanged.bind(this));
            if (!this.entityManager.hasChanges())
                this.softDelete();
        }
        SoftSaveManager.loadState = function () {
            var notificationInfos;
            return storage.getItem(SoftSaveManager.storageKey, SoftSaveManager.storageOptions).then(function (result) { return result.data; }).fail(function (reason) { return []; }).then(function (infos) { return Q.all(infos.map(function (info) { return storage.getItem(info.fullyQualifiedId, core.storageOptions, true).then(function (result) { return info; }, function (reason) { return null; }); })).then(function (infos) { return infos.filter(function (info) { return info !== null; }); }); }).then(function (notificationInfos) {
                notificationInfos = notificationInfos.filter(function (x) { return !breeze.EntityState.fromName(x.entityState).isDetached(); });
                SoftSaveManager.unsavedEntities(notificationInfos);
                notificationInfos.forEach(function (info) { return keys.add(info.typeName, info.id); });
                notificationInfos.forEach(function (notificationInfo) {
                    app.notifier.warning(notificationInfo);
                });
            });
        };
        SoftSaveManager.prototype.dispose = function () {
            this.entityManager.entityChanged.unsubscribe(this.entityChangedSubscriptionToken);
            clearTimeout(this.timeoutHandle);
            this.entityManager = null;
        };
        SoftSaveManager.prototype.handleEntityChanged = function (args) {
            if (!this.isTracking && this.entityManager.entity.entityAspect.entityState.isUnchangedOrModified()) {
                this.isTracking = true;
            }
            if (!this.isTracking)
                return;
            clearTimeout(this.timeoutHandle);
            if (args.entity.entityAspect.entityState.isDetached() && args.entityAction === breeze.EntityAction.EntityStateChange) {
                this.cacheOrRemoveEntityManager();
            }
            else {
                this.timeoutHandle = setTimeout(this.cacheOrRemoveEntityManager.bind(this), 1000);
            }
        };
        SoftSaveManager.prototype.cacheOrRemoveEntityManager = function () {
            if (this.entityManager.hasChanges())
                this.softSave(false).done();
            else
                this.softDelete().done();
        };
        SoftSaveManager.prototype.softSave = function (notify) {
            var _this = this;
            if (app.webIntake)
                return Q.resolve(null);
            return cache.store(this.entityManager, new Date()).then(function () {
                var logMessage = 'Soft SAVE.  Entity: ' + core.getFullyQualifiedId(_this.entityManager.entity);
                console.log(logMessage);
                logger.logUserAction(logMessage);
                var fullyQualifiedId = core.getFullyQualifiedId(_this.entityManager.entity), existingNotificationInfo = util.Arrays.firstOrDefault(SoftSaveManager.unsavedEntities(), function (n) { return equalsIgnoreCase(n.fullyQualifiedId, fullyQualifiedId); }), type = registry.getRootType(_this.entityManager.entity.entityType.name), entityState = _this.entityManager.entity.entityAspect.entityState.getName(), entityManagerState = entityState === breeze.EntityState.Unchanged.getName() ? breeze.EntityState.Modified.getName() : entityState, notificationInfo = {
                    fullyQualifiedId: fullyQualifiedId,
                    id: core.getEntityId(_this.entityManager.entity),
                    typeName: core.getBaseType(_this.entityManager.entity).name,
                    parentId: _this.entityManager.parentEntityManager ? core.getEntityId(_this.entityManager.parentEntityManager.entity) : null,
                    parentTypeName: _this.entityManager.parentEntityManager ? core.getBaseType(_this.entityManager.parentEntityManager.entity).name : null,
                    entityState: entityManagerState,
                    url: '#' + url.getFragment(_this.entityManager),
                    icon: type.icon,
                    singularName: type.singularName,
                    title: type.getTitle(_this.entityManager.entity),
                    timestamp: notify && existingNotificationInfo ? existingNotificationInfo.timestamp : new Date()
                };
                if (existingNotificationInfo) {
                    SoftSaveManager.unsavedEntities.remove(existingNotificationInfo);
                }
                SoftSaveManager.unsavedEntities.push(notificationInfo);
                if (notify) {
                    app.notifier.warning(notificationInfo);
                }
                return storage.setItem(SoftSaveManager.storageKey, SoftSaveManager.unsavedEntities(), SoftSaveManager.storageOptions, new Date());
            });
        };
        SoftSaveManager.prototype.softDelete = function (id) {
            var _this = this;
            var type = core.getBaseType(this.entityManager.entity).name;
            if (id === undefined) {
                return this.softDelete(this.entityManager.originalId).then(function () {
                    id = core.getEntityId(_this.entityManager.entity);
                    if (id === _this.entityManager.originalId) {
                        return;
                    }
                    return _this.softDelete(id);
                });
            }
            return SoftSaveManager.removeFromUnsavedEntitiesAndRemoveNotification(id, type).then(function () {
                if (core.isSyncing() || util.Arrays.any(sync.versions(), function (v) { return v.ID === id && equalsIgnoreCase(v.Type, type); }))
                    return cache.store(_this.entityManager, new Date());
                if (_this.entityManager.entity.entityType.name === 'MobilePreferenceModel:#Harmony.Ria.Personalization')
                    return cache.store(_this.entityManager, new Date());
                return cache.remove(_this.entityManager).then(function () {
                    var logMessage = 'Soft DELETE.  Entity: ' + core.getFullyQualifiedId(_this.entityManager.entity);
                    console.log(logMessage);
                    logger.logUserAction(logMessage);
                });
            });
        };
        SoftSaveManager.removeFromUnsavedEntitiesAndRemoveNotification = function (id, typeName) {
            var notificationInfo = util.Arrays.firstOrDefault(SoftSaveManager.unsavedEntities(), function (n) { return equalsIgnoreCase(n.fullyQualifiedId, core.composeFullyQualifiedId(typeName, id)); });
            if (notificationInfo === null)
                return Q.resolve(null);
            SoftSaveManager.unsavedEntities.remove(notificationInfo);
            return storage.setItem(SoftSaveManager.storageKey, SoftSaveManager.unsavedEntities(), SoftSaveManager.storageOptions, new Date()).then(function () {
                app.notifier.remove(notificationInfo);
                var logMessage = 'Soft REMOVE NOTIFICATION.  Entity: ' + typeName + '/' + id.toString(10);
                console.log(logMessage);
                logger.logUserAction(logMessage);
            });
        };
        SoftSaveManager.prototype.softSaveOfflineAssessment = function () {
            return mtracker.storeOfflineAssesment(this.entityManager, new Date());
        };
        SoftSaveManager.storageOptions = { global: false, hipaa: true };
        SoftSaveManager.storageKey = 'SoftSaveManager/Entities';
        SoftSaveManager.unsavedEntities = ko.observableArray([]);
        return SoftSaveManager;
    })();
    exports.SoftSaveManager = SoftSaveManager;
});

define('entities/repo',["require", "exports", 'entities/cache', 'entities/core', 'entities/registry', 'entities/softsave', 'entities/keys', 'entities/breeze', 'entities/url', 'core/messageBox', 'core/util', 'entities/api', 'entities/sync', 'assessmentTracker/mobileAssessmentTracker'], function (require, exports, cache, core, registry, softsave, keys, b, url, messageBox, util, entities, entitySync, mtracker) {
    var entityManagers = {};
    exports.allowSaveWithChanges = false;
    exports.getInstanceExceptions = {
        entityDoesNotExistOnServer: new Error('The entity does not exist on the server.'),
        unableToConnectAndEntityDoesNotExistInTheCache: new Error('The entity does not exist in the cache and the server could not be reached.'),
        entityNotAuthorized: new Error('You are not authorized to access this entity.'),
    };
    function getInstanceExceptionMessage(reason) {
        switch (reason) {
            case exports.getInstanceExceptions.unableToConnectAndEntityDoesNotExistInTheCache:
                return 'Unable to connect to the Harmony servers to load the record.';
            case exports.getInstanceExceptions.entityDoesNotExistOnServer:
                return 'The record no longer exists.';
            case exports.getInstanceExceptions.entityNotAuthorized:
                return 'You are not authorized to access this record.';
            default:
                return null;
        }
    }
    exports.getInstanceExceptionMessage = getInstanceExceptionMessage;
    function getInstance(typeName, id) {
        var type = registry.getRootType(typeName), fullyQualifiedId = core.composeFullyQualifiedId(type.name, id), entityQuery = type.loadById(id, new breeze.EntityQuery()), cachedCopyNotModified = new Error('entity in cache is not modified');
        function entityManagerFromCache(breezeEntityManager) {
            var entity = breezeEntityManager.getEntityByKey(type.name, id);
            if (entity.entityAspect.entityState.isAdded()) {
                entity.IsNew(true);
            }
            return new EntityManager(entity, breezeEntityManager, true);
        }
        if (entityManagers.hasOwnProperty(fullyQualifiedId)) {
            var inMemoryEntityManager = entityManagers[fullyQualifiedId];
            if (!inMemoryEntityManager.hasChanges() && moment().diff(moment(inMemoryEntityManager.lastRefresh), 'seconds') > 30 && !app.isOffline()) {
                return inMemoryEntityManager.refresh().then(function (serverCopyDeleted) {
                    if (serverCopyDeleted)
                        throw exports.getInstanceExceptions.entityDoesNotExistOnServer;
                    return inMemoryEntityManager;
                }, function (reason) {
                    if (util.isConnectionFailure(reason)) {
                        return Q.resolve(inMemoryEntityManager);
                    }
                    return Q.reject(reason);
                });
            }
            return Q.resolve(inMemoryEntityManager);
        }
        return b.createBreezeEntityManager(type.controllerName).then(function (breezeEntityManager) {
            return cache.retrieve(fullyQualifiedId).then(function (serializedEntity) {
                if (id < 0) {
                    keys.setExpectedKey(type.name, id);
                }
                breezeEntityManager.importEntities(serializedEntity.json);
                if (breezeEntityManager.hasChanges() || app.isOffline()) {
                    return entityManagerFromCache(breezeEntityManager);
                }
                throw cachedCopyNotModified;
            }).fail(function (reason) {
                var breezeEntityManagerForServer = breezeEntityManager.createEmptyCopy();
                return breezeEntityManagerForServer.executeQuery(entityQuery).then(function (queryResult) {
                    if (queryResult.results.length === 0) {
                        throw exports.getInstanceExceptions.entityDoesNotExistOnServer;
                    }
                    var entity = queryResult.results[0];
                    var entityManager = new EntityManager(entity, breezeEntityManagerForServer, false);
                    if (core.isSyncing()) {
                        return Q.resolve(entityManager);
                    }
                    return cache.retrieve(fullyQualifiedId, true).then(function (serializedEntity) { return cache.store(entityManager, serializedEntity.lupdateDateTime); }).then(function () { return entityManager; }).fail(function (reason) { return entityManager; });
                }).fail(function (reason) {
                    if (reason === exports.getInstanceExceptions.entityDoesNotExistOnServer)
                        throw reason;
                    if (reason.status && reason.status === 405) {
                        throw exports.getInstanceExceptions.entityNotAuthorized;
                    }
                    if (util.isConnectionFailure(reason)) {
                        if (breezeEntityManager.getEntityByKey(type.name, id)) {
                            return entityManagerFromCache(breezeEntityManager);
                        }
                        else {
                            throw exports.getInstanceExceptions.unableToConnectAndEntityDoesNotExistInTheCache;
                        }
                    }
                    throw reason;
                });
            });
        });
    }
    exports.getInstance = getInstance;
    function createInstance(typeName, config) {
        var type = registry.getRootType(typeName);
        return b.createBreezeEntityManager(type.controllerName).then(function (breezeEntityManager) {
            var entity = createInstanceInternal(type, breezeEntityManager, config);
            var entityManager = new EntityManager(entity, breezeEntityManager, false);
            return Q.resolve(entityManager);
        });
    }
    exports.createInstance = createInstance;
    function createInstanceInternal(type, breezeEntityManager, config) {
        var breezeEntityType = breezeEntityManager.metadataStore.getEntityType(type.name, false);
        config = config || {};
        var entity = breezeEntityManager.createEntity(type.name, config);
        entity.IsNew(true);
        if (type.initialize) {
            type.initialize(entity, createChildEntity.bind(this, breezeEntityManager));
        }
        return entity;
    }
    function createChildEntity(breezeEntityManager, parentEntity, navigationPropertyName, config) {
        var navigationProperty = parentEntity.entityType.getNavigationProperty(navigationPropertyName), type = registry.getType(navigationProperty.entityType.name), standardConfig = {};
        standardConfig[navigationProperty.inverse.foreignKeyNames[0]] = core.getEntityId(parentEntity);
        config = $.extend(config || {}, standardConfig);
        var entity = createInstanceInternal(type, breezeEntityManager, config);
        return entity;
    }
    exports.createChildEntity = createChildEntity;
    function getInstances(typeNames, ids) {
        var property, result = [];
        for (property in entityManagers) {
            if (entityManagers[property].type && entityManagers[property].type.name && typeNames.indexOf(entityManagers[property].type.name) >= 0)
                result.push(entityManagers[property]);
        }
        if (typeof ids === 'undefined')
            return result;
        return result.filter(function (em) { return ids.filter(function (id) { return core.getEntityId(em.entity) === id; }).length > 0; });
    }
    exports.getInstances = getInstances;
    function removeDisplayInstance(entity, typeName) {
        var deleteMetadata;
        var displayType;
        var rootType;
        displayType = registry.getDisplayType(typeName);
        var rootEntityType = displayType.rootEntityType;
        rootType = registry.getRootType(rootEntityType);
        deleteMetadata = displayType.deleteMetadata;
        if (displayType.getKey === undefined)
            throw new Error('Argument \'type.getKey\' is required to delete an entity. Change your module type registration code');
        if (deleteMetadata === undefined || deleteMetadata === null)
            throw new Error('Argument \'type.deleteMetadata\' is required to delete an entity. Change your module type registration code');
        if (rootType.deleteById === undefined)
            throw new Error('Argument \'type.deleteById\' is required to delete an entity. Change your module type registration code');
        var deleteOperation = {
            titleKey: '',
            promptKey: '',
            promptReplacements: [],
            titleReplacements: [],
            typeName: rootType.name,
            id: displayType.getKey(entity),
            fullyQualifiedId: core.composeFullyQualifiedId(rootType.name, displayType.getKey(entity)),
            deleteById: rootType.deleteById,
            entityTitle: displayType.getTitle(entity),
            isAdded: !!entity['isUnsaved']
        };
        getdeletePromptMetadata(deleteOperation, deleteMetadata, entity);
        return removeInstanceInternal(deleteOperation);
    }
    exports.removeDisplayInstance = removeDisplayInstance;
    function removeRootInstance(entity, typeName) {
        var deleteMetadata, rootType;
        rootType = registry.getRootType(typeName);
        deleteMetadata = rootType.deleteMetadata;
        if (deleteMetadata === undefined || deleteMetadata === null)
            throw new Error('Argument \'type.deleteMetadata\' is required to delete an entity. Change your module type registration code');
        if (rootType.deleteById === undefined)
            throw new Error('Argument \'type.deleteById\' is required to delete an entity. Change your module type registration code');
        var deleteOperation = {
            titleKey: '',
            promptKey: '',
            promptReplacements: [],
            titleReplacements: [],
            typeName: core.getBaseType(entity).name,
            id: core.getEntityId(entity),
            fullyQualifiedId: core.composeFullyQualifiedId(core.getBaseType(entity).name, core.getEntityId(entity)),
            deleteById: rootType.deleteById,
            entityTitle: rootType.getTitle(entity),
            isAdded: entity.entityAspect.entityState.isAdded()
        };
        getdeletePromptMetadata(deleteOperation, deleteMetadata, entity);
        return removeInstanceInternal(deleteOperation);
    }
    exports.removeRootInstance = removeRootInstance;
    function removeLocalRootInstance(id, typeName) {
        var fullyQualifiedId = core.composeFullyQualifiedId(typeName, id), children = softsave.SoftSaveManager.unsavedEntities().filter(function (x) { return x.parentId === id && x.parentTypeName === typeName; }), promise = Q.resolve(null);
        children.forEach(function (i) {
            promise = promise.then(function () { return removeLocalRootInstance(i.id, i.typeName); });
        });
        promise = promise.then(function () {
            if (entityManagers.hasOwnProperty(fullyQualifiedId)) {
                delete entityManagers[fullyQualifiedId];
            }
            return cache.removeById(fullyQualifiedId).then(function () {
                softsave.SoftSaveManager.removeFromUnsavedEntitiesAndRemoveNotification(id, typeName).then(function () {
                    var version = util.Arrays.firstOrDefault(core.versions(), function (ev) { return ev.ID === id && ev.Type === typeName; });
                    if (!version)
                        return;
                    return core.updateVersions(core.versions().filter(function (ev) { return ev !== version; }));
                });
            });
        });
        return promise;
    }
    exports.removeLocalRootInstance = removeLocalRootInstance;
    function getdeletePromptMetadata(deleteOperation, deleteMetadata, entity) {
        deleteOperation.titleKey = 'common.deleteTitle';
        if (deleteMetadata.titleKey !== undefined) {
            deleteOperation.titleKey = deleteMetadata.titleKey;
        }
        deleteOperation.titleReplacements = [deleteOperation.entityTitle];
        if (deleteMetadata.titleReplacements !== undefined) {
            deleteOperation.titleReplacements = deleteMetadata.titleReplacements(entity);
        }
        deleteOperation.promptKey = 'common.deletePrompt';
        if (deleteMetadata.promptKey !== undefined) {
            deleteOperation.promptKey = deleteMetadata.promptKey;
        }
        deleteOperation.promptReplacements = [];
        if (deleteMetadata.promptReplacements !== undefined) {
            deleteOperation.promptReplacements = deleteMetadata.promptReplacements(entity);
        }
    }
    function removeInstanceInternal(deleteOperation) {
        var deferred = Q.defer();
        messageBox.show(deleteOperation.titleKey, deleteOperation.promptKey, messageBox.buttons.yesCancel, deleteOperation.promptReplacements, deleteOperation.titleReplacements).then(function (result) {
            if (result !== messageBox.yes) {
                deferred.resolve({ isCanceled: true });
                return;
            }
            app.busyIndicator.setBusy($.t('common.deleting'));
            return Q.fcall(function () {
                if (deleteOperation.isAdded)
                    return Q.resolve(null);
                return deleteOperation.deleteById(deleteOperation.id);
            }).then(function () { return removeLocalRootInstance(deleteOperation.id, deleteOperation.typeName); }).then(function () {
                deferred.resolve({ isCanceled: false });
                var prompt = $.i18n.t('common.successfulDelete');
                var message = prompt.format.call(prompt, [deleteOperation.entityTitle]);
                app.statusBar.success(message, 2000);
            }).fail(function (reason) {
                if (util.isConnectionFailure(reason)) {
                    messageBox.show('common.delete', 'common.unableToConnect', messageBox.buttons.okOnly).then(function () { return deferred.resolve({ isCanceled: true }); });
                    return;
                }
                var domainException = util.getDomainException(reason);
                if (domainException !== null) {
                    messageBox.show('common.delete', 'common.validationErrorsPreventedDelete', messageBox.buttons.okOnly, [domainException.ExceptionMessage]).then(function () { return deferred.resolve({ isCanceled: true }); });
                    return;
                }
                deferred.resolve({ isCanceled: false });
                return Q.reject(reason);
            }).finally(function () { return app.busyIndicator.setReady(); });
        }).done();
        return deferred.promise;
    }
    function getUnsavedEntities(typeName, parentTypeName, parentId) {
        var promises = [], type = registry.getRootType(typeName), breezeEntityManager;
        softsave.SoftSaveManager.unsavedEntities().filter(function (x) { return x.parentTypeName === parentTypeName && x.parentId === parentId && x.typeName === typeName; }).forEach(function (info) {
            promises.push(cache.retrieve(info.fullyQualifiedId).then(function (serializedEntity) { return ({ id: info.id, timestamp: info.timestamp, serializedEntity: serializedEntity }); }));
        });
        return b.createBreezeEntityManager(type.controllerName).then(function (em) {
            breezeEntityManager = em;
            return Q.all(promises);
        }).then(function (items) {
            for (var i = 0; i < items.length; i++) {
                var entity, item = items[i];
                if (item.id < 0) {
                    keys.setExpectedKey(typeName, item.id);
                }
                breezeEntityManager.importEntities(item.serializedEntity.json);
                var entity = breezeEntityManager.getEntityByKey(typeName, item.id);
            }
            return breezeEntityManager.getEntities().filter(function (e) { return core.getBaseType(e).name === typeName; });
        });
    }
    exports.getUnsavedEntities = getUnsavedEntities;
    function saveAll() {
        exports.allowSaveWithChanges = true;
        var promise = Q.resolve(null);
        app.busyIndicator.setBusy("Saving...");
        app.notifier.messages().map(function (x) { return x.notificationInfo; }).forEach(function (info) {
            promise = promise.then(function () { return saveInternal(info); });
        });
        promise = promise.fail(handleSaveChangesFail);
        promise.then(function () {
            var deferred = Q.defer();
            Q.fcall(function () { return entitySync.sync(); }).finally(function () {
                deferred.resolve(null);
            }).done();
            return deferred.promise;
        }).then(function () {
            mtracker.getOfflineAssessmentKeys();
        }).finally(function () {
            app.busyIndicator.setReady();
        }).done();
    }
    exports.saveAll = saveAll;
    function saveInternal(info) {
        var promise = Q.resolve(null), parentEntityManager = null;
        if (info.parentTypeName) {
            promise = entities.getInstance(info.parentTypeName, info.parentId).then(function (em) { return parentEntityManager = em; });
        }
        return promise.then(function () { return entities.getInstance(info.typeName, info.id); }).then(function (entityManager) {
            entityManager.parentEntityManager = parentEntityManager;
            if (entityManager.hasChanges())
                return entityManager.saveChanges(true).fail(function (reason) {
                    if (entities.isConcurrencyException(reason))
                        return;
                    return Q.reject(reason);
                });
            return Q.resolve(null);
        });
    }
    exports.saveInternal = saveInternal;
    function handleSaveChangesFail(reason, durandalRouter) {
        var entityErrors = reason.entityErrors, messageSubstitutions = [], entityManager;
        if (util.isConnectionFailure(reason)) {
            return messageBox.show('common.save', 'common.saveFailedUnableToConnect', messageBox.buttons.okOnly);
        }
        if (!entityErrors) {
            return Q.reject(reason);
        }
        entityManager = reason.sourceEntityManager;
        messageSubstitutions.push(entityManager.type.getTitle(entityManager.entity));
        messageSubstitutions.push(entityErrors.map(function (x) { return '<li>' + x.errorMessage + '</li>'; }).join());
        return messageBox.show('common.save', 'common.validationErrorsPreventedSave', messageBox.buttons.openCancel, messageSubstitutions).then(function (button) {
            if (button !== messageBox.open)
                return;
            durandalRouter.navigate('#' + entities.getFragment(entityManager));
        });
    }
    exports.handleSaveChangesFail = handleSaveChangesFail;
    var EntityManager = (function () {
        function EntityManager(entity, breezeEntityManager, fromCache) {
            var _this = this;
            this.entity = entity;
            this.breezeEntityManager = breezeEntityManager;
            this.originalId = core.getEntityId(entity);
            if (fromCache)
                this.lastRefresh = breeze.DataType.DateTime.defaultValue;
            else
                this.lastRefresh = new Date();
            this.type = registry.getRootType(entity.entityType.name);
            var cacheKey = core.getFullyQualifiedId(this.entity);
            entityManagers[cacheKey] = this;
            this.hasChanges = ko.observable(breezeEntityManager.hasChanges());
            this.isSavingChanges = ko.observable(false);
            this.rejectedChanges = new breeze.core.Event('rejectedChanges', this);
            this.entityChanged = breezeEntityManager.entityChanged;
            this.validationErrorsChanged = breezeEntityManager.validationErrorsChanged;
            this.executeQuery = this.breezeEntityManager.executeQuery.bind(this.breezeEntityManager);
            this.getChanges = this.breezeEntityManager.getChanges.bind(this.breezeEntityManager);
            this.entityChangedSubscription = breezeEntityManager.entityChanged.subscribe(this.onEntityChanged.bind(this));
            this.hasChangesChangedSubscription = this.breezeEntityManager.hasChangesChanged.subscribe(function (changeArgs) {
                _this.hasChanges(changeArgs.hasChanges);
            });
            this.softSaveManager = new softsave.SoftSaveManager(this);
            this.softSaveManager.isTracking = this.entity.entityAspect.entityState.isUnchangedOrModified();
            this.createChildEntity = createChildEntity.bind(this, this.breezeEntityManager);
        }
        EntityManager.prototype.notifyOpenedForEdit = function (cacheImmediately) {
            if (this.entity.entityAspect.entityState.isAdded() && !this.softSaveManager.isTracking) {
                this.softSaveManager.isTracking = true;
                if (cacheImmediately)
                    this.softSaveManager.softSave(false);
            }
        };
        EntityManager.prototype.exportEntities = function () {
            var json = this.breezeEntityManager.exportEntities(null, false);
            return json;
        };
        EntityManager.prototype.importEntities = function (jsonExported) {
            this.breezeEntityManager.importEntities(jsonExported);
        };
        EntityManager.prototype.addEntity = function (entity) {
            this.breezeEntityManager.addEntity(entity);
        };
        EntityManager.prototype.saveChanges = function (rejectConnectionFailure) {
            var _this = this;
            var promise = Q.resolve(null), saveResult = { softSave: true }, title = this.type.getTitle(this.entity), hadChanges = this.breezeEntityManager.hasChanges(), self = this, currentId = core.getEntityId(this.entity);
            function enhanceFailReason(reason) {
                if (!reason.entityErrors)
                    return;
                if (reason.sourceEntityManager)
                    return;
                reason.sourceEntityManager = self;
            }
            this.isSavingChanges(true);
            app.busyIndicator.setBusy($.i18n.t('common.saving'));
            if (this.parentEntityManager && this.parentEntityManager.hasChanges()) {
                promise = promise.then(function () { return _this.parentEntityManager.saveChanges(rejectConnectionFailure); });
            }
            if (this.type.beforeSave) {
                promise = promise.then(function () { return _this.type.beforeSave.apply(_this, [_this]); });
            }
            if (app.isOffline() && !app.webIntake) {
                promise = promise.then(function () {
                    return _this.softSaveManager.softSave(true).then(function () {
                        var message = ''.format.call($.i18n.t('common.entityWasSavedToDeviceStorage'), title);
                        app.statusBar.status(message, 'alert-warning', 'glyphicon-floppy-remove', 5000);
                        self.isSavingChanges(false);
                        self.lastSaveFailedDueToConnectionFailure = true;
                    }).then(function () {
                        var trackOffline = mtracker.trackOfflineAssessment();
                        return trackOffline;
                    }).then(function (data) {
                        if (data) {
                            _this.softSaveManager.softSaveOfflineAssessment();
                        }
                    });
                }).then(function () {
                    var deferred = Q.defer();
                    Q.all(registry.saveChangesHandlers.map(function (h) { return h(saveResult); })).finally(function () { return deferred.resolve(null); }).done();
                    return deferred.promise;
                });
            }
            else {
                promise = promise.then(function () { return _this.breezeEntityManager.saveChanges(undefined, new breeze.SaveOptions({ allowConcurrentSaves: true })).then(function () { return _this.softSaveManager.softDelete(_this.originalId); }).then(function (breezeSaveResult) {
                    url.synchronize(_this.entity.entityType, currentId, core.getEntityId(_this.entity));
                    saveResult.breezeSaveResult = breezeSaveResult;
                    saveResult.softSave = false;
                    _this.lastRefresh = new Date();
                    if (hadChanges) {
                        var message = ''.format.call($.i18n.t('common.entityWasSavedToTheDatabase'), title);
                        app.statusBar.status(message, 'alert-success', 'glyphicon-floppy-saved', 5000);
                    }
                }).fail(function (reason) {
                    var isConnectionFailure = util.isConnectionFailure(reason);
                    _this.lastSaveFailedDueToConnectionFailure = isConnectionFailure;
                    if (isConnectionFailure && !rejectConnectionFailure) {
                        return _this.softSaveManager.softSave(true).then(function () {
                            var message = ''.format.call($.i18n.t('common.entityWasSavedToDeviceStorage'), title);
                            app.statusBar.status(message, 'alert-warning', 'glyphicon-floppy-remove', 5000);
                        });
                    }
                    if (core.isConcurrencyException(reason)) {
                        return _this.recoverFromConcurrencyException(reason).then(function () { return Q.reject(reason); });
                    }
                    enhanceFailReason(reason);
                    return Q.reject(reason);
                }).then(function () {
                    var deferred = Q.defer();
                    Q.all(registry.saveChangesHandlers.map(function (h) { return h(saveResult); })).finally(function () {
                        if (!app.webIntake) {
                            entitySync.sync().then(function () { return deferred.resolve(null); });
                        }
                        else {
                            deferred.resolve(null);
                        }
                    }).done();
                    return deferred.promise;
                }); });
            }
            if (self.type.afterSave) {
                promise = promise.then(function () {
                    var deferred = Q.defer();
                    if (self.type.afterSave)
                        Q.fcall(function () { return self.type.afterSave.apply(self, [self, saveResult]); }).finally(function () { return deferred.resolve(null); }).done();
                    return deferred.promise;
                });
            }
            return promise.then(function () { return saveResult; }).finally(function () {
                app.busyIndicator.setReady();
                self.isSavingChanges(false);
            });
        };
        EntityManager.prototype.rejectChanges = function () {
            if (this.entity.entityAspect.entityState.isAdded()) {
                this.softSaveManager.isTracking = false;
                this.softSaveManager.softDelete();
            }
            this.breezeEntityManager.rejectChanges();
            this.rejectedChanges.publish(null);
        };
        EntityManager.prototype.promptToFinalizeChanges = function (messageBoxButtons) {
            var self = this;
            if (this.isSavingChanges()) {
                var isSavingChangesSubscription = this.isSavingChanges.subscribe(function (v) {
                    if (self.isSavingChanges())
                        return Q.resolve(false);
                    isSavingChangesSubscription.dispose();
                    return self.promptToFinalizeChanges();
                });
            }
            if (!this.hasChanges())
                return Q.resolve(null);
            var deferred = Q.defer();
            var saveChangesThenResolveDeferred = function () {
                self.saveChanges().then(deferred.resolve).fail(function (reason) {
                    deferred.reject(reason);
                    if (!reason.entityErrors && !core.isConcurrencyException(reason))
                        return Q.reject(reason);
                }).done();
            };
            if (this.lastSaveFailedDueToConnectionFailure) {
                saveChangesThenResolveDeferred();
                return deferred.promise;
            }
            var buttons = [];
            if (messageBoxButtons)
                buttons = messageBoxButtons;
            else
                buttons = this.entity.entityAspect.entityState.isAdded() ? messageBox.buttons.saveDeleteCancel : messageBox.buttons.saveRevertCancel;
            messageBox.show('common.promptToFinalizeChangesTitle', 'common.promptToFinalizeChangesMessage', buttons, [self.type.getTitle(self.entity)]).then(function (messageBoxValue) {
                if (messageBoxValue === messageBox.revert || messageBoxValue === messageBox.del) {
                    self.rejectChanges();
                    deferred.resolve(null);
                    return;
                }
                if (messageBoxValue === messageBox.save) {
                    saveChangesThenResolveDeferred();
                    return;
                }
                deferred.reject(null);
            });
            return deferred.promise;
        };
        EntityManager.prototype.canUserRead = function () {
            return true;
        };
        EntityManager.prototype.onEntityChanged = function (data) {
            this.lastSaveFailedDueToConnectionFailure = false;
            var message = 'Entity Changed.  Entity: ' + (data.entity ? core.getFullyQualifiedId(data.entity) : '?') + ';  EntityAction: ' + data.entityAction.getName() + '; ';
            if (data.entityAction === breeze.EntityAction.PropertyChange) {
                var pcArgs = data.args;
                message += 'PropertyName: ' + pcArgs.propertyName + '; Old Value: ' + (pcArgs.oldValue ? pcArgs.oldValue.toString() : 'null') + '; New Value: ' + (pcArgs.newValue ? pcArgs.newValue.toString() : 'null') + ';';
            }
            if (data.entityAction === breeze.EntityAction.EntityStateChange) {
                message += 'New State: ' + data.entity.entityAspect.entityState.getName() + ';';
            }
        };
        EntityManager.prototype.recoverFromConcurrencyException = function (reason) {
            var _this = this;
            return this.refresh().then(function (serverCopyDeleted) {
                var messageFormat = 'common.conflictingEditMessage';
                reason.serverCopyDeleted = serverCopyDeleted;
                if (serverCopyDeleted)
                    messageFormat = 'common.conflictingDeleteMessage';
                return messageBox.show('common.conflictingEdit', messageFormat, messageBox.buttons.okOnly, [_this.type.getTitle(_this.entity)]);
            });
        };
        EntityManager.prototype.refresh = function () {
            var _this = this;
            var entityQuery = this.type.loadById(core.getEntityId(this.entity), new breeze.EntityQuery()).using(breeze.MergeStrategy.OverwriteChanges);
            this.breezeEntityManager.rejectChanges();
            return this.breezeEntityManager.executeQuery(entityQuery).then(function (queryResult) {
                if (queryResult.results.length === 0) {
                    return removeLocalRootInstance(core.getEntityId(_this.entity), core.getBaseType(_this.entity).name).then(function () { return true; });
                }
                _this.lastRefresh = new Date();
                return Q.resolve(false);
            });
        };
        return EntityManager;
    })();
});

define('entities/snapshot',["require", "exports"], function (require, exports) {
    var Snapshot = (function () {
        function Snapshot(entity) {
            this.entity = entity;
            this.snapshot = {};
            var dataProperties = entity.entityType.dataProperties, dataProperty, navigationProperties = entity.entityType.navigationProperties, navigationProperty, entityCollection, childSnapshots, i, j;
            this.snapshotEntityState = entity.entityAspect.entityState;
            if (this.snapshotEntityState !== breeze.EntityState.Added && this.snapshotEntityState !== breeze.EntityState.Unchanged && this.snapshotEntityState !== breeze.EntityState.Modified) {
                this.dispose();
                throw new Error('The EntityState must be Added, Unchanged or Modified.  Detached and Deleted are not allowed.');
            }
            for (i = 0; i < dataProperties.length; i++) {
                dataProperty = dataProperties[i];
                this.snapshot[dataProperty.name] = entity[dataProperty.name]();
            }
            for (i = 0; i < navigationProperties.length; i++) {
                navigationProperty = navigationProperties[i];
                if (navigationProperty.isScalar) {
                    continue;
                }
                entityCollection = entity[navigationProperty.name]();
                childSnapshots = [];
                this.snapshot[navigationProperty.name] = childSnapshots;
                for (var j = 0; j < entityCollection.length; j++) {
                    childSnapshots.push(new Snapshot(entityCollection[j]));
                }
            }
        }
        Snapshot.prototype.restore = function () {
            var dataProperties = this.entity.entityType.dataProperties, dataProperty, navigationProperties = this.entity.entityType.navigationProperties, navigationProperty, entityCollection, clonedEntityCollection, childSnapshots, i, j;
            for (i = 0; i < navigationProperties.length; i++) {
                navigationProperty = navigationProperties[i];
                if (navigationProperty.isScalar) {
                    continue;
                }
                entityCollection = this.entity[navigationProperty.name]();
                childSnapshots = this.snapshot[navigationProperty.name];
                for (var j = 0; j < childSnapshots.length; j++) {
                    childSnapshots[j].restore();
                }
                clonedEntityCollection = entityCollection.slice(0);
                for (var j = 0; j < clonedEntityCollection.length; j++) {
                    if (childSnapshots.filter(function (s) { return s.entity.entityAspect.getKey().values[0] === clonedEntityCollection[j].entityAspect.getKey().values[0]; }).length === 0) {
                        clonedEntityCollection[j].entityAspect.setDeleted();
                    }
                }
            }
            for (i = 0; i < dataProperties.length; i++) {
                dataProperty = dataProperties[i];
                if (this.entity[dataProperty.name]() !== this.snapshot[dataProperty.name]) {
                    this.entity[dataProperty.name](this.snapshot[dataProperty.name]);
                }
            }
            if (this.snapshotEntityState.isUnchanged() && !this.entity.entityAspect.entityState.isUnchanged()) {
                this.entity.entityAspect.rejectChanges();
            }
        };
        Snapshot.prototype.dispose = function () {
            this.snapshot = null;
            this.snapshotEntityState = null;
            this.entity = null;
        };
        return Snapshot;
    })();
    return Snapshot;
});

define('entities/changeTracker',["require", "exports", 'core/util'], function (require, exports, util) {
    var ChangeTracker = (function () {
        function ChangeTracker(entityManager) {
            this.entityManager = entityManager;
            this.changedEntities = [];
            this.entityChangedSubscription = entityManager.entityChanged.subscribe(this.onEntityChanged.bind(this));
        }
        ChangeTracker.prototype.getChangedEntities = function () {
            return this.changedEntities.slice(0);
        };
        ChangeTracker.prototype.reset = function () {
            this.changedEntities = [];
        };
        ChangeTracker.prototype.onEntityChanged = function (data) {
            if (data.entityAction === breeze.EntityAction.PropertyChange) {
                if (util.Arrays.any(this.changedEntities, function (x) { return x === data.entity; }))
                    return;
                this.changedEntities.push(data.entity);
            }
            else if (data.entityAction === breeze.EntityAction.EntityStateChange && data.entity.entityAspect.entityState.isUnchanged()) {
                this.changedEntities = this.changedEntities.filter(function (x) { return x !== data.entity; });
            }
        };
        ChangeTracker.prototype.dispose = function () {
            if (this.entityManager !== null) {
                this.entityManager.entityChanged.unsubscribe(this.entityChangedSubscription);
                this.entityManager = null;
                this.changedEntities = null;
            }
        };
        return ChangeTracker;
    })();
    return ChangeTracker;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('entities/api',["require", "exports", 'core/constants', 'core/util', 'entities/core', 'entities/registry', 'entities/url', 'entities/breeze', 'entities/repo', 'entities/snapshot', 'entities/changeTracker'], function (require, exports, constants, util, core, registry, url, b, repo, snapshot, changeTracker) {
    exports.composeFullyQualifiedId = core.composeFullyQualifiedId;
    exports.convertToShortName = core.convertToShortName;
    exports.getBaseType = core.getBaseType;
    exports.getEntityId = core.getEntityId;
    exports.getEntityIdProperty = core.getEntityIdProperty;
    exports.getFullyQualifiedId = core.getFullyQualifiedId;
    exports.isConcurrencyException = core.isConcurrencyException;
    exports.getDotNetTypeName = core.getDotNetTypeName;
    exports.getCrudOperation = core.getCrudOperation;
    ;
    ;
    ;
    ;
    ;
    ;
    ;
    ;
    ;
    exports.convertToLongTypeName = registry.convertToLongTypeName;
    exports.getMetadataStoreInitializer = registry.getMetadataStoreInitializer;
    exports.getRootType = registry.getRootType;
    exports.getDisplayType = registry.getDisplayType;
    exports.getType = registry.getType;
    exports.registerMetadataStoreInitializer = registry.registerMetadataStoreInitializer;
    exports.registerRootType = registry.registerRootType;
    exports.registerDisplayType = registry.registerDisplayType;
    exports.registerType = registry.registerType;
    exports.registerEntityTypeCtor = registry.registerEntityTypeCtor;
    function registerSaveChangesHandler(handler) {
        registry.saveChangesHandlers.push(handler);
    }
    exports.registerSaveChangesHandler = registerSaveChangesHandler;
    exports.getFragment = url.getFragment;
    exports.parseFragment = url.parseFragment;
    exports.EntityAction = url.EntityAction;
    exports.createBreezeEntityManager = b.createBreezeEntityManager;
    exports.createChildEntity = repo.createChildEntity;
    exports.createInstance = repo.createInstance;
    exports.getInstance = repo.getInstance;
    exports.getInstanceExceptions = repo.getInstanceExceptions;
    exports.getInstanceExceptionMessage = repo.getInstanceExceptionMessage;
    exports.getInstances = repo.getInstances;
    exports.removeDisplayInstance = repo.removeDisplayInstance;
    exports.removeRootInstance = repo.removeRootInstance;
    exports.removeLocalRootInstance = repo.removeLocalRootInstance;
    exports.getUnsavedEntities = repo.getUnsavedEntities;
    var Snapshot = (function (_super) {
        __extends(Snapshot, _super);
        function Snapshot() {
            _super.apply(this, arguments);
        }
        return Snapshot;
    })(snapshot);
    exports.Snapshot = Snapshot;
    var ChangeTracker = (function (_super) {
        __extends(ChangeTracker, _super);
        function ChangeTracker() {
            _super.apply(this, arguments);
        }
        return ChangeTracker;
    })(changeTracker);
    exports.ChangeTracker = ChangeTracker;
    exports.entityTypes = {
        ConsumerAssessmentResponse: 'ConsumerAssessmentResponse:#Server.Domain',
        ConsumerAssessment: 'ConsumerAssessment:#Server.Domain',
        Chapter: 'Chapter:#Server.Domain',
        CONTACT: 'CONTACT:#Server.Domain',
        DEMOGRAPHIC: 'DEMOGRAPHIC:#Server.Domain',
        Group: 'Group:#Server.Domain',
        HISScreenQuestionCondition: 'HISScreenQuestionCondition:#Server.Domain',
        Incident: 'Incident:#Server.Domain',
        IncidentAssessmentResponse: 'IncidentAssessmentResponse:#Server.Domain',
        IncidentAssessment: 'IncidentAssessment:#Server.Domain',
        InquiryAssessmentResponse: 'InquiryAssessmentResponse:#Server.Domain',
        InquiryAssessment: 'InquiryAssessment:#Server.Domain',
        INQUIRY: 'INQUIRY:#Server.Domain',
        Medication: 'Medication:#Server.Domain',
        AssessmentRelation: 'AssessmentRelation:#Server.Domain',
        Role: 'Role:#Server.Domain',
        SCREENDESIGN: 'SCREENDESIGN:#Server.Domain',
        ScreenLookupChain: 'ScreenLookupChain:#Server.Domain',
        SCREENLOOKUP: 'SCREENLOOKUP:#Server.Domain',
        SCREENQUESTION: 'SCREENQUESTION:#Server.Domain',
        UserRole: 'UserRole:#Server.Domain',
        User: 'User:#Server.Domain',
        VendorAssessmentResponse: 'VendorAssessmentResponse:#Server.Domain',
        VendorAssessment: 'VendorAssessment:#Server.Domain',
        Vendor: 'Vendor:#Server.Domain',
        VENDORSWORKER: 'VENDORSWORKER:#Server.Domain',
        WORKER: 'WORKER:#Server.Domain',
        vw_WH_ConsumerFilter: 'vw_WH_ConsumerFilter:#Server.Domain',
        vw_WH_IncidentFilter: 'vw_WH_IncidentFilter:#Server.Domain',
        vw_WH_InquiryFilter: 'vw_WH_InquiryFilter:#Server.Domain',
        vw_WH_ConsumerAssessmentFilter: 'vw_WH_ConsumerAssessmentFilter:#Server.Domain',
        vw_WH_IncidentReviewFilter: 'vw_WH_IncidentReviewFilter:#Server.Domain',
        vw_WH_InquiryDocumentationFilter: 'vw_WH_InquiryDocumentationFilter:#Server.Domain',
        vw_WH_ProviderAssessmentsFilter: 'vw_WH_ProviderAssessmentsFilter:#Server.Domain'
    };
    exports.displayTypes = {
        assessmentListItem: 'AssessmentListItem:#Server.Domain',
    };
    exports.validators = {
        date: {
            dateValid: new breeze.Validator('dateValid', function (value, context) { return value === null || value.getTime() >= constants.date.min.getTime() && value.getTime() <= constants.date.max.getTime(); }, { messageTemplate: '%displayName% must be between %min% and %max%', min: moment(constants.date.min).format('M/D/YYYY'), max: moment(constants.date.max).format('M/D/YYYY') }),
            onOrBeforeToday: new breeze.Validator('dateOnOrBeforeToday', function (value, context) { return value === null || value.getTime() <= util.getDate().getTime(); }, { messageTemplate: '%displayName% must be on or before today.' }),
            onOrAfterToday: new breeze.Validator('dateOnOrAfterToday', function (value, context) { return value === null || value.getTime() >= util.getDate().getTime(); }, { messageTemplate: '%displayName% must be on or after today.' }),
        },
    };
});

define('core/lookups',["require", "exports", 'core/constants', 'core/util', 'core/storage'], function (require, exports, constants, util, storage) {
    var storageOptions = { global: true, hipaa: false }, lookups;
    exports.vendors;
    exports.workers;
    exports.relationships;
    exports.medications;
    exports.agcyPrograms;
    exports.srvcPrograms;
    exports.lawEnforcementAgency;
    exports.placeBySelection;
    function bootstrap() {
        if (app.webIntake) {
            return Q.all([bootstrapLookups(), bootstrapVendors(), bootstrapWorkers(), bootstrapRelationships(), bootstrapMedications(), bootstrapLawEnforcementAgencies()]);
        }
        else {
            return Q.all([bootstrapLookups(), bootstrapVendors(), bootstrapWorkers(), bootstrapRelationships(), bootstrapMedications(), bootstrapAgencyPrograms(), bootstrapServiceProviderPrograms()]);
        }
    }
    exports.bootstrap = bootstrap;
    function bootstrapLookups() {
        return Q($.get(constants.services.serviceBaseUrl + 'Lookups/Lookups')).then(function (items) {
            lookups = util.Arrays.toIndex(util.Arrays.groupBy(items, function (x) { return x.LookupName.toLowerCase(); }), function (x) { return x.key; }, function (x) { return x; });
            security.openDispositions = getLookupInternal('dispositioncodes').filter(function (x) { return equalsIgnoreCase(x.Description, 'open') || equalsIgnoreCase(x.SecondaryID, 'open'); }).map(function (x) { return x.Description; });
            security.openEDispositions = getLookupInternal('edispositioncodes').filter(function (x) { return equalsIgnoreCase(x.Description, 'open') || equalsIgnoreCase(x.SecondaryID, 'open'); }).map(function (x) { return x.Description; });
            security.completeStatuses = getLookupInternal('statuscodes').filter(function (x) { return equalsIgnoreCase(x.Description, 'complete') || equalsIgnoreCase(x.SecondaryID, 'complete'); }).map(function (x) { return x.Description; });
            storage.setItem('Lookups/Lookups', items, storageOptions).done();
        }).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return storage.getItem('Lookups/Lookups', storageOptions).then(function (result) {
                lookups = util.Arrays.toIndex(util.Arrays.groupBy(result.data, function (x) { return x.LookupName.toLowerCase(); }), function (x) { return x.key; }, function (x) { return x; });
                security.openDispositions = getLookupInternal('dispositioncodes').filter(function (x) { return equalsIgnoreCase(x.Description, 'open') || equalsIgnoreCase(x.SecondaryID, 'open'); }).map(function (x) { return x.Description; });
                security.openEDispositions = getLookupInternal('edispositioncodes').filter(function (x) { return equalsIgnoreCase(x.Description, 'open') || equalsIgnoreCase(x.SecondaryID, 'open'); }).map(function (x) { return x.Description; });
                security.completeStatuses = getLookupInternal('statuscodes').filter(function (x) { return equalsIgnoreCase(x.Description, 'complete') || equalsIgnoreCase(x.SecondaryID, 'complete'); }).map(function (x) { return x.Description; });
            });
        });
    }
    function bootstrapMedications() {
        return Q($.get(constants.services.serviceBaseUrl + 'Lookups/Medications')).then(function (items) {
            exports.medications = items;
            storage.setItem('Lookups/Medications', items, storageOptions).done();
        }).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return storage.getItem('Lookups/Medications', storageOptions).then(function (result) {
                exports.medications = result.data;
            });
        });
    }
    function bootstrapVendors() {
        return Q($.get(constants.services.serviceBaseUrl + 'Lookups/Vendors')).then(function (items) {
            exports.vendors = items;
            storage.setItem('Lookups/Vendors', items, storageOptions).done();
        }).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return storage.getItem('Lookups/Vendors', storageOptions).then(function (result) {
                exports.vendors = result.data;
            });
        });
    }
    function bootstrapWorkers() {
        return Q($.get(constants.services.serviceBaseUrl + 'Lookups/Workers')).then(function (items) {
            exports.workers = items;
            storage.setItem('Lookups/Workers', items, storageOptions).done();
        }).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return storage.getItem('Lookups/Workers', storageOptions).then(function (result) {
                exports.workers = result.data;
            });
        });
    }
    function bootstrapRelationships() {
        return Q($.get(constants.services.serviceBaseUrl + 'Lookups/Relationships')).then(function (items) {
            exports.relationships = items;
            storage.setItem('Lookups/Relationships', items, storageOptions).done();
        }).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return storage.getItem('Lookups/Relationships', storageOptions).then(function (result) {
                exports.relationships = result.data;
            });
        });
    }
    function bootstrapPlaceBySelection(storeData) {
        var queryString = '';
        for (var i = 0; i < storeData.length; i++) {
            if (queryString == '')
                queryString = '[' + i + '].id=' + storeData[i]["id"] + '&' + '[' + i + '].value=' + storeData[i]["value"];
            else
                queryString = queryString + '&[' + i + '].id=' + storeData[i]["id"] + '&' + '[' + i + '].value=' + storeData[i]["value"];
        }
        return Q($.get(constants.services.serviceBaseUrl + 'Lookups/FetchPlacesBySelection?' + queryString)).then(function (items) {
            exports.placeBySelection = items;
        }).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return [];
        });
    }
    exports.bootstrapPlaceBySelection = bootstrapPlaceBySelection;
    function bootstrapAgencyPrograms() {
        return Q($.get(constants.services.serviceBaseUrl + 'Consumers/Agency')).then(function (items) {
            exports.agcyPrograms = items;
            storage.setItem('Consumers/Agency', items, storageOptions).done();
        }).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return storage.getItem('Consumers/Agency', storageOptions).then(function (result) {
                exports.agcyPrograms = result.data;
            });
        });
    }
    function bootstrapServiceProviderPrograms() {
        return Q($.get(constants.services.serviceBaseUrl + 'Consumers/ServiceProvider')).then(function (items) {
            exports.srvcPrograms = items;
            storage.setItem('Consumers/ServiceProvider', items, storageOptions).done();
        }).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return storage.getItem('Consumers/ServiceProvider', storageOptions).then(function (result) {
                exports.srvcPrograms = result.data;
            });
        });
    }
    function bootstrapLawEnforcementAgencies() {
        return Q($.get(constants.services.serviceBaseUrl + 'Lookups/LawEnforcementAgencies')).then(function (items) {
            exports.lawEnforcementAgency = items;
            storage.setItem('Lookups/LawEnforcementAgencies', items, storageOptions).done();
        }).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return storage.getItem('Lookups/LawEnforcementAgencies', storageOptions).then(function (result) {
                exports.lawEnforcementAgency = result.data;
            });
        });
    }
    function diagnosisSearch(codeType, query) {
        return Q($.get(constants.services.serviceBaseUrl + 'Lookups/DiagnosisSearch?' + $.param({ codeType: codeType, query: query }))).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return [];
        });
    }
    exports.diagnosisSearch = diagnosisSearch;
    function getLookupByClientSideControlID(pageName, clientSideControlID, currentValue) {
        var lookupName = security.getFieldControlPropertyValueByClientSideControlID(pageName, clientSideControlID, security.FieldControlPropertyName.LookupIDDesc);
        return getLookupInternal(lookupName, currentValue);
    }
    exports.getLookupByClientSideControlID = getLookupByClientSideControlID;
    function getLookup(pageName, dbFieldName, currentValue, fallbackLookupName) {
        var lookupName = security.getFieldControlPropertyValue(pageName, dbFieldName, security.FieldControlPropertyName.LookupIDDesc);
        if (lookupName || fallbackLookupName)
            return getLookupInternal(lookupName || fallbackLookupName, currentValue).filter(function (a) { return a.IsActive || equalsIgnoreCase(a.Description, currentValue); }).sort(function (a, b) { return util.stringComparisonOrdinalIgnoreCase(a.Description, b.Description); }).sort(function (a, b) { return (a.SortOrder || 0) - (b.SortOrder || 0); });
        return [];
    }
    exports.getLookup = getLookup;
    function getLookupInternal(lookupName, currentValue) {
        var items, item;
        if (currentValue === undefined) {
            currentValue = '';
        }
        items = lookups[lookupName.toLowerCase()].filter(function (x) { return x.IsActive || equalsIgnoreCase(x.Description, currentValue); });
        items = JSON.parse(JSON.stringify(items));
        if (!isNullOrEmpty(currentValue) && !util.Arrays.any(items, function (x) { return x.Description === currentValue; })) {
            item = util.Arrays.firstOrDefault(items, function (x) { return equalsIgnoreCase(x.Description, currentValue); });
            if (item) {
                item.Description = currentValue;
            }
            else {
                items.push({ LookupName: lookupName, LookupCode: -99, Description: currentValue, SecondaryID: '', SelectR: true, IsActive: true, SortOrder: 9999999 });
            }
        }
        return items;
    }
    exports.countries = [
        'Afghanistan',
        'Albania',
        'Algeria',
        'Andorra',
        'Angola',
        'Antigua',
        'Argentina',
        'Armenia',
        'Australia',
        'Austria',
        'Azerbaijan',
        'Bahamas',
        'Bahrain',
        'Bangladesh',
        'Barbados',
        'Belarus',
        'Belgium',
        'Belize',
        'Benin',
        'Bhutan',
        'Bolivia',
        'Bosnia',
        'Botswana',
        'Brazil',
        'Brunei',
        'Bulgaria',
        'Burkina',
        'Burundi',
        'Cambodia',
        'Cameroon',
        'Canada',
        'Cape Verde',
        'Chad',
        'Chile',
        'China',
        'Colombia',
        'Comoros',
        'Congo',
        'Costa Rica',
        'Croatia',
        'Cuba',
        'Cyprus',
        'Czech Republic',
        'Denmark',
        'Djibouti',
        'Dominica',
        'Dominican Republic',
        'Ecuador',
        'Egypt',
        'El Salvador',
        'Equatorial Guinea',
        'Eritrea',
        'Estonia',
        'Ethiopia',
        'Fiji',
        'Finland',
        'France',
        'Gabon',
        'Georgia',
        'Germany',
        'Ghana',
        'Greece',
        'Grenada',
        'Guatemala',
        'Guinea',
        'Guinea-Bissau',
        'Guyana',
        'Haiti',
        'Honduras',
        'Hungary',
        'Iceland',
        'India',
        'Indonesia',
        'Iran',
        'Iraq',
        'Ireland',
        'Israel',
        'Italy',
        'Jamaica',
        'Japan',
        'Jordan',
        'Kazakhstan',
        'Kenya',
        'Kiribati',
        'Korea, North',
        'Korea, South',
        'Kuwait',
        'Kyrgyzstan',
        'Laos',
        'Latvia',
        'Lebanon',
        'Lesotho',
        'Liberia',
        'Libya',
        'Liechtenstein',
        'Lithuania',
        'Luxembourg',
        'Macedonia',
        'Madagascar',
        'Malawi',
        'Malaysia',
        'Maldives',
        'Mali',
        'Malta',
        'Marshall Islands',
        'Mauritania',
        'Mauritius',
        'Mexico',
        'Moldova',
        'Monaco',
        'Mongolia',
        'Morocco',
        'Mozambique',
        'Myanmar',
        'Namibia',
        'Nauru',
        'Nepal',
        'Netherlands',
        'New Zealand',
        'Nicaragua',
        'Niger',
        'Nigeria',
        'Norway',
        'Oman',
        'Pakistan',
        'Palau',
        'Panama',
        'Papua New Guinea',
        'Paraguay',
        'Peru',
        'Philippines',
        'Poland',
        'Portugal',
        'Qatar',
        'Romania',
        'Russia',
        'Rwanda',
        'Saint Kitts and Nevis',
        'Saint Lucia',
        'Samoa',
        'San Marino',
        'Sao Tome and Principe',
        'Saudi Arabia',
        'Senegal',
        'Seychelles',
        'Sierra Leone',
        'Singapore',
        'Slovakia',
        'Slovenia',
        'Solomon Islands',
        'Somalia',
        'South Africa',
        'Spain',
        'Sri Lanka',
        'Sudan',
        'Suriname',
        'Swaziland',
        'Sweden',
        'Switzerland',
        'Syria',
        'Taiwan',
        'Tajikistan',
        'Tanzania',
        'Thailand',
        'Togo',
        'Tonga',
        'Trinidad and Tobago',
        'Tunisia',
        'Turkey',
        'Turkmenistan',
        'Tuvalu',
        'Uganda',
        'Ukraine',
        'United Arab Emirates',
        'United Kingdom',
        'United States',
        'Uruguay',
        'Uzbekistan',
        'Vanuatu',
        'Vatican City',
        'Venezuela',
        'Vietnam',
        'Western Sahara',
        'Yemen',
        'Yugoslavia',
        'Zambia',
        'Zimbabwe',
    ];
    ;
    exports.states = [
        { abbreviation: 'AK', name: 'Alaska' },
        { abbreviation: 'AL', name: 'Alabama' },
        { abbreviation: 'AR', name: 'Arkansas' },
        { abbreviation: 'AZ', name: 'Arizona' },
        { abbreviation: 'CA', name: 'California ' },
        { abbreviation: 'CO', name: 'Colorado ' },
        { abbreviation: 'CT', name: 'Connecticut' },
        { abbreviation: 'DC', name: 'District of Columbia' },
        { abbreviation: 'DE', name: 'Delaware' },
        { abbreviation: 'FL', name: 'Florida' },
        { abbreviation: 'GA', name: 'Georgia' },
        { abbreviation: 'HI', name: 'Hawaii' },
        { abbreviation: 'IA', name: 'Iowa' },
        { abbreviation: 'ID', name: 'Idaho' },
        { abbreviation: 'IL', name: 'Illinois' },
        { abbreviation: 'IN', name: 'Indiana' },
        { abbreviation: 'KS', name: 'Kansas' },
        { abbreviation: 'KY', name: 'Kentucky' },
        { abbreviation: 'LA', name: 'Louisiana' },
        { abbreviation: 'MA', name: 'Massachusetts' },
        { abbreviation: 'MD', name: 'Maryland' },
        { abbreviation: 'ME', name: 'Maine' },
        { abbreviation: 'MI', name: 'Michigan' },
        { abbreviation: 'MN', name: 'Minnesota' },
        { abbreviation: 'MO', name: 'Missouri' },
        { abbreviation: 'MS', name: 'Mississippi' },
        { abbreviation: 'MT', name: 'Montana' },
        { abbreviation: 'NC', name: 'North Carolina' },
        { abbreviation: 'ND', name: 'North Dakota' },
        { abbreviation: 'NE', name: 'Nebraska' },
        { abbreviation: 'NH', name: 'New Hampshire' },
        { abbreviation: 'NJ', name: 'New Jersey' },
        { abbreviation: 'NM', name: 'New Mexico' },
        { abbreviation: 'NV', name: 'Nevada' },
        { abbreviation: 'NY', name: 'New York' },
        { abbreviation: 'OH', name: 'Ohio' },
        { abbreviation: 'OK', name: 'Oklahoma' },
        { abbreviation: 'OR', name: 'Oregon' },
        { abbreviation: 'PA', name: 'Pennsylvania' },
        { abbreviation: 'RI', name: 'Rhode Island' },
        { abbreviation: 'SC', name: 'South Carolina' },
        { abbreviation: 'SD', name: 'South Dakota' },
        { abbreviation: 'TN', name: 'Tennessee' },
        { abbreviation: 'TX', name: 'Texas' },
        { abbreviation: 'UT', name: 'Utah' },
        { abbreviation: 'VA', name: 'Virginia' },
        { abbreviation: 'VT', name: 'Vermont' },
        { abbreviation: 'WA', name: 'Washington' },
        { abbreviation: 'WI', name: 'Wisconsin' },
        { abbreviation: 'WV', name: 'West Virginia' },
        { abbreviation: 'WY', name: 'Wyoming' },
    ];
});

define('security/loginHistory',["require", "exports", 'core/storage'], function (require, exports, storage) {
    var storageOptions = { global: true, hipaa: false };
    function getOfflineUsers() {
        return storage.getItem('login-history', storageOptions).fail(function (reason) { return { data: [] }; }).then(function (result) { return result.data; });
    }
    exports.getOfflineUsers = getOfflineUsers;
    function update() {
        return getOfflineUsers().then(function (userInfos) {
            var u = { UserId: User.Current.UserId, MemberID: User.Current.MemberID, SqlServer: User.Current.SqlServer, Database: User.Current.Database, UserStamp: User.Current.UserStamp, DefaultFundCode: User.Current.DefaultFundCode, CreateDateTime: new Date() };
            userInfos = userInfos.filter(function (x) { return !(equalsIgnoreCase(x.SqlServer, u.SqlServer) && equalsIgnoreCase(x.Database, u.Database) && equalsIgnoreCase(x.UserId, u.UserId)); });
            userInfos.unshift(u);
            return storage.setItem('login-history', userInfos, storageOptions);
        });
    }
    exports.update = update;
});

define('assessments/scales',["require", "exports"], function (require, exports) {
    exports.keys = {
        ctlDropDownList: 'ctlDropDownList',
        ctlTextbox: 'ctlTextbox',
        ctlCheckbox: 'ctlCheckbox',
        ctlHeader: 'ctlHeader',
        ctlInstructionalText: 'ctlInstructionalText',
        ctlMultiSelectionListBox: 'ctlMultiSelectionListBox',
        ctlMultiSelectionListBoxWithNeeds: 'ctlMultiSelectionListBoxWithNeeds',
        ctlDateCalendar: 'ctlDateCalendar',
        ctlLookupDropDown: 'ctlLookupDropDown',
        ctlNumericTextbox: 'ctlNumericTextbox',
        ctlCurrencyTextbox: 'ctlCurrencyTextbox',
        ctlCalculatedField: 'ctlCalculatedField',
        ctlDemographicDataLookup: 'ctlDemographicDataLookup',
        ctlEnrollmentDataLookup: 'ctlEnrollmentDataLookup',
        ctlIndicatorField: 'ctlIndicatorField',
        ctlNumericIndicatorField: 'ctlNumericIndicatorField',
        ctlDropDownListWithNeeds: 'ctlDropDownListWithNeeds',
        ctlCheckboxWithNeeds: 'ctlCheckboxWithNeeds',
        ctlPhoneTextbox: 'ctlPhoneTextbox',
        ctlRadioButtonList: 'ctlRadioButtonList',
        ctlTimeControl: 'ctlTimeControl',
        ctlDecimalTextbox: 'ctlDecimalTextbox',
        ctlCommentLookup: 'ctlCommentLookup',
        ctlDiagCodeSearchLookUp: 'ctlDiagCodeSearchLookUp',
        ctlRawScoreField: 'ctlRawScoreField',
        ctlRichText: 'ctlRichText',
        ctlLikert: 'ctlLikert',
        ctlSSNTextbox: 'ctlSSNTextbox',
        ctlEmailTextbox: 'ctlEmailTextbox',
        ctlLineSpace: 'ctlLineSpace',
        ctlMedicationDataForm: 'ctlMedicationDataForm',
        ctlRelationDataForm: 'ctlRelationDataForm',
        ctlFiles: 'ctlFiles',
        ctlCommentIndicatorField: 'ctlCommentIndicatorField',
        ctlDecimalIndicatorField: 'ctlDecimalIndicatorField',
        ctlDateIndicatorField: 'ctlDateIndicatorField',
        ctlScreenDesignGridFieldControl: 'ctlScreenDesignGridFieldControl',
        ctlPlacesControl: 'ctlPlacesControl',
        ctlCopyAddressFrom: 'ctlCopyAddressFrom',
    };
    exports.names = {
        ctlDropDownList: 'Single-Select',
        ctlTextbox: 'Text',
        ctlCheckbox: 'Yes/No',
        ctlHeader: 'Header',
        ctlMultiSelectionListBox: 'Multi-Select',
        ctlMultiSelectionListBoxWithNeeds: 'Multi-Select (with needs)',
        ctlDateCalendar: 'Date',
        ctlLookupDropDown: 'Single-Select',
        ctlNumericTextbox: 'Number',
        ctlCurrencyTextbox: 'Currency',
        ctlCalculatedField: 'Calculated',
        ctlDemographicDataLookup: 'Single-Select',
        ctlEnrollmentDataLookup: 'Single-Select',
        ctlIndicatorField: 'Indicator',
        ctlDropDownListWithNeeds: 'Single-Select (with needs)',
        ctlCheckboxWithNeeds: 'Yes/No (with needs)',
        ctlPhoneTextbox: 'Phone',
        ctlRadioButtonList: 'Single-Select',
        ctlTimeControl: 'Time',
        ctlDecimalTextbox: 'Decimal',
        ctlCommentLookup: 'Single-Select',
        ctlDiagCodeSearchLookUp: 'Diagnosis Code',
        ctlRawScoreField: 'Raw Score',
        ctlRichText: 'Rich Text',
        ctlLikert: 'Rating',
        ctlSSNTextbox: 'SSN',
        ctlEmailTextbox: 'Email',
        ctlLineSpace: 'Line Space',
        ctlMedicationDataForm: 'Medications',
        ctlRelationDataForm: 'Relations',
        ctlFiles: 'Files',
        ctlCommentIndicatorField: 'Comment Indicator',
        ctlDecimalIndicatorField: 'Decimal Indicator',
        ctlDateIndicatorField: 'Date Indicator',
        ctlCopyAddressFrom: 'Copy Address From'
    };
    exports.DemographicField = {
        ADDRESSTYPE: 'lblADDRESSTYPE',
        AGE: 'lblAGE',
        ALIAS: 'lblALIAS',
        CELLPHONE: 'lblCELLPHONE',
        CITIZENSHIP: 'lblCITIZENSHIP',
        CITY: 'lblCITY',
        DescriptiveAddress: 'lblDescriptiveAddress',
        DOB: 'lblDOB',
        EMAIL: 'lblEMAIL',
        ETHNICITYLOOKUP: 'lblETHNICITYLOOKUP',
        FAMILYSIZE: 'lblFAMILYSIZE',
        FIRSTNAME: 'lblFIRSTNAME',
        GENDER: 'lblGENDER',
        GENDERIDENTITY: 'lblGenderIdentity',
        PHONE: 'lblPHONE',
        LASTNAME: 'lblLASTNAME',
        CURMARSTATUS: 'lblCURMARSTATUS',
        SECID: 'lblSECID',
        MedicareID: 'lblMedicareID',
        MIDDLENAME: 'lblMIDDLENAME',
        PLANGUAGE: 'lblPLANGUAGE',
        RACE: 'lblRACE',
        REFERRALSOURCE: 'lblREFERRALSOURCE',
        RESCOUNTY: 'lblRESCOUNTY',
        RESIDENCETYPE: 'lblRESIDENCETYPE',
        SALUTATION: 'lblSALUTATION',
        SSN: 'lblSSN',
        STATE: 'lblSTATE',
        STREET: 'lblSTREET',
        STREET2: 'lblSTREET2',
        Suffix: 'lblSuffix',
        VeteranStatus: 'lblVeteranStatus',
        WORKPHONE: 'lblWORKPHONE',
        ZIPCODE: 'lblZIPCODE',
        StudentWithADisability: 'lblStudentWithADisability',
        IndividualWithADisability: 'lblIndividualWithADisability',
        PrimaryDisabilityType: 'lblPrimaryDisabilityType',
        PrimaryDisabilitySource: 'lblPrimaryDisabilitySource',
        SecondaryDisabilityType: 'lblSecondaryDisabilityType',
        SecondaryDisabilitySource: 'lblSecondaryDisabilitySource',
        SignificanceOfDisability: 'lblSignificanceOfDisability',
        DegreeOfVisualImpairment: 'lblDegreeOfVisualImpairment',
        MajorCauseOfVisualImpairment: 'lblMajorCauseOfVisualImpairment',
        OtherAgeRelatedImpairments: 'lblOtherAgeRelatedImpairments',
        MultiRace: 'lblMultiRace',
        BelowPovertyLevel: 'lblBelowPovertyLevel'
    };
    exports.EnrollmentField = {
        ADMITDATE: 'lblADMITDATE',
        DateOfEligibilityDetermination: 'lblDateOfEligibilityDetermination',
        EligibilityDeterminationExtension: 'lblEligibilityDeterminationExtension',
        MonthlyPublicSupportAtApplication: 'lblMonthlyPublicSupportAtApplication',
        MedicalInsuranceCoverageAtApplication: 'lblMedicalInsuranceCoverageAtApplication',
        ReferralSource: 'lblReferralSource',
    };
    exports.DemographicSyncMode = {
        DoNotSyncData: 'DoNotSyncData',
        SyncData: 'SyncData',
    };
});

define('history/history',["require", "exports", 'core/storage', 'entities/api', 'entities/sync'], function (require, exports, storage, entities, entitySync) {
    var storageOptions = { hipaa: true, global: false };
    var storageKey = 'history';
    var previousItem = null;
    function push(entityManager) {
        var item = {
            typeName: entities.getBaseType(entityManager.entity).name,
            id: entities.getEntityId(entityManager.entity),
            title: entityManager.type.getTitle(entityManager.entity),
            url: '#' + entities.getFragment(entityManager)
        };
        item.timestamp = new Date();
        if (previousItem !== null && previousItem.typeName === item.typeName && previousItem.id === item.id && moment(item.timestamp).diff(moment(previousItem.timestamp), 'minutes') < 20) {
            return Q.resolve(null);
        }
        previousItem = item;
        var history;
        return storage.getItem(storageKey, storageOptions).then(function (result) { return history = result.data; }).fail(function (reason) { return history = []; }).then(function () {
            history.unshift(item);
            history.slice(0, 100);
            return storage.setItem(storageKey, history, storageOptions);
        });
    }
    exports.push = push;
    exports.days = [];
    exports.filteredDays = ko.observableArray();
    exports.hasHistory = ko.observable(false);
    exports.searchString = ko.observable('');
    exports.hasResults = ko.computed(function () { return exports.filteredDays().length > 0; });
    exports.showNoResultsMessage = ko.observable(false);
    function widenSearch() {
        return true;
    }
    exports.widenSearch = widenSearch;
    var throttledSearchString = ko.computed(function () {
        return exports.searchString();
    }).extend({ throttle: 500 });
    exports.searchString.subscribe(function (value) {
        exports.showNoResultsMessage(false);
    });
    throttledSearchString.subscribe(function (value) {
        filterDays();
    });
    function filterDays() {
        var s = exports.searchString().toLowerCase().trim();
        if (s === '') {
            exports.filteredDays(exports.days);
            return;
        }
        var filtered = exports.days.map(function (v, i, a) {
            return {
                description: v.description,
                history: v.history.filter(function (h) { return h.searchText.indexOf(s) >= 0; })
            };
        });
        filtered = filtered.filter(function (d) { return d.history.length > 0; });
        exports.showNoResultsMessage(filtered.length === 0 && s.length > 0);
        exports.filteredDays(filtered);
    }
    exports.filterDays = filterDays;
    function activate() {
        var _this = this;
        return storage.getItem(storageKey, storageOptions).then(function (result) { return result.data; }).fail(function (reason) { return []; }).then(function (items) {
            var day, item, current = moment().add('days', 1), today = moment().startOf('day'), itemDay, diff, description, type, parentType, me = _this;
            exports.days = [];
            items.forEach(function (item) {
                itemDay = moment(item.timestamp).startOf('day');
                if (itemDay.diff(current, 'days') !== 0) {
                    current = itemDay;
                    diff = itemDay.diff(today, 'days');
                    if (diff === 0)
                        description = 'Today - ';
                    else if (diff === -1)
                        description = 'Yesterday - ';
                    else
                        description = '';
                    description = description + moment(item.timestamp).format('dddd, MMMM Do YYYY');
                    day = { description: description, history: [] };
                    exports.days.push(day);
                }
                type = entities.getRootType(item.typeName);
                item.icon = type.icon;
                item.singularName = type.singularName;
                item.time = moment(item.timestamp).format('h:mm A');
                item.searchText = (item.title || '').toLowerCase() + '|' + item.singularName.toLocaleLowerCase() + '|' + moment(item.timestamp).format('l') + '|' + moment(item.timestamp).format('dddd, MMMM Do YYYY').toLowerCase();
                item.IsAvailableOffline = ko.computed(function () {
                    return entitySync.versions().filter(function (v) { return v.ID === item.id; }).length > 0;
                }, me);
                day.history.push(item);
            });
            exports.hasHistory(exports.days.length > 0);
            filterDays();
        });
    }
    exports.activate = activate;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * This module is based on Backbone's core history support. It abstracts away the low level details of working with browser history and url changes in order to provide a solid foundation for a router.
 * @module history
 * @requires system
 * @requires jquery
 */
define('plugins/history',['durandal/system', 'jquery'], function (system, $) {
    // Cached regex for stripping a leading hash/slash and trailing space.
    var routeStripper = /^[#\/]|\s+$/g;

    // Cached regex for stripping leading and trailing slashes.
    var rootStripper = /^\/+|\/+$/g;

    // Cached regex for detecting MSIE.
    var isExplorer = /msie [\w.]+/;

    // Cached regex for removing a trailing slash.
    var trailingSlash = /\/$/;

    // Update the hash location, either replacing the current entry, or adding
    // a new one to the browser history.
    function updateHash(location, fragment, replace) {
        if (replace) {
            var href = location.href.replace(/(javascript:|#).*$/, '');

            if (history.history.replaceState) {
                history.history.replaceState({}, document.title, href + '#' + fragment); // using history.replaceState instead of location.replace to work around chrom bug
            } else {
                location.replace(href + '#' + fragment);
            }
        } else {
            // Some browsers require that `hash` contains a leading #.
            location.hash = '#' + fragment;
        }
    };

    /**
     * @class HistoryModule
     * @static
     */
    var history = {
        /**
         * The setTimeout interval used when the browser does not support hash change events.
         * @property {string} interval
         * @default 50
         */
        interval: 50,
        /**
         * Indicates whether or not the history module is actively tracking history.
         * @property {string} active
         */
        active: false
    };
    
    // Ensure that `History` can be used outside of the browser.
    if (typeof window !== 'undefined') {
        history.location = window.location;
        history.history = window.history;
    }

    /**
     * Gets the true hash value. Cannot use location.hash directly due to a bug in Firefox where location.hash will always be decoded.
     * @method getHash
     * @param {string} [window] The optional window instance
     * @return {string} The hash.
     */
    history.getHash = function(window) {
        var match = (window || history).location.href.match(/#(.*)$/);
        return match ? match[1] : '';
    };
    
    /**
     * Get the cross-browser normalized URL fragment, either from the URL, the hash, or the override.
     * @method getFragment
     * @param {string} fragment The fragment.
     * @param {boolean} forcePushState Should we force push state?
     * @return {string} he fragment.
     */
    history.getFragment = function(fragment, forcePushState) {
        if (fragment == null) {
            if (history._hasPushState || !history._wantsHashChange || forcePushState) {
                fragment = history.location.pathname + history.location.search;
                var root = history.root.replace(trailingSlash, '');
                if (!fragment.indexOf(root)) {
                    fragment = fragment.substr(root.length);
                }
            } else {
                fragment = history.getHash();
            }
        }
        
        return fragment.replace(routeStripper, '');
    };

    /**
     * Activate the hash change handling, returning `true` if the current URL matches an existing route, and `false` otherwise.
     * @method activate
     * @param {HistoryOptions} options.
     * @return {boolean|undefined} Returns true/false from loading the url unless the silent option was selected.
     */
    history.activate = function(options) {
        if (history.active) {
            system.error("History has already been activated.");
        }

        history.active = true;

        // Figure out the initial configuration. Do we need an iframe?
        // Is pushState desired ... is it available?
        history.options = system.extend({}, { root: '/' }, history.options, options);
        history.root = history.options.root;
        history._wantsHashChange = history.options.hashChange !== false;
        history._wantsPushState = !!history.options.pushState;
        history._hasPushState = !!(history.options.pushState && history.history && history.history.pushState);

        var fragment = history.getFragment();
        var docMode = document.documentMode;
        var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));

        // Normalize root to always include a leading and trailing slash.
        history.root = ('/' + history.root + '/').replace(rootStripper, '/');

        if (oldIE && history._wantsHashChange) {
            history.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
            history.navigate(fragment, false);
        }

        // Depending on whether we're using pushState or hashes, and whether
        // 'onhashchange' is supported, determine how we check the URL state.
        if (history._hasPushState) {
            $(window).on('popstate', history.checkUrl);
        } else if (history._wantsHashChange && ('onhashchange' in window) && !oldIE) {
            $(window).on('hashchange', history.checkUrl);
        } else if (history._wantsHashChange) {
            history._checkUrlInterval = setInterval(history.checkUrl, history.interval);
        }

        // Determine if we need to change the base url, for a pushState link
        // opened by a non-pushState browser.
        history.fragment = fragment;
        var loc = history.location;
        var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === history.root;

        // Transition from hashChange to pushState or vice versa if both are requested.
        if (history._wantsHashChange && history._wantsPushState) {
            // If we've started off with a route from a `pushState`-enabled
            // browser, but we're currently in a browser that doesn't support it...
            if (!history._hasPushState && !atRoot) {
                history.fragment = history.getFragment(null, true);
                history.location.replace(history.root + history.location.search + '#' + history.fragment);
                // Return immediately as browser will do redirect to new url
                return true;

            // Or if we've started out with a hash-based route, but we're currently
            // in a browser where it could be `pushState`-based instead...
            } else if (history._hasPushState && atRoot && loc.hash) {
                this.fragment = history.getHash().replace(routeStripper, '');
                this.history.replaceState({}, document.title, history.root + history.fragment + loc.search);
            }
        }

        if (!history.options.silent) {
            return history.loadUrl(options.startRoute);
        }
    };

    /**
     * Disable history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers.
     * @method deactivate
     */
    history.deactivate = function() {
        $(window).off('popstate', history.checkUrl).off('hashchange', history.checkUrl);
        clearInterval(history._checkUrlInterval);
        history.active = false;
    };

    /**
     * Checks the current URL to see if it has changed, and if it has, calls `loadUrl`, normalizing across the hidden iframe.
     * @method checkUrl
     * @return {boolean} Returns true/false from loading the url.
     */
    history.checkUrl = function() {
        var current = history.getFragment();
        if (current === history.fragment && history.iframe) {
            current = history.getFragment(history.getHash(history.iframe));
        }

        if (current === history.fragment) {
            return false;
        }

        if (history.iframe) {
            history.navigate(current, false);
        }
        
        history.loadUrl();
    };
    
    /**
     * Attempts to load the current URL fragment. A pass-through to options.routeHandler.
     * @method loadUrl
     * @return {boolean} Returns true/false from the route handler.
     */
    history.loadUrl = function(fragmentOverride) {
        var fragment = history.fragment = history.getFragment(fragmentOverride);

        return history.options.routeHandler ?
            history.options.routeHandler(fragment) :
            false;
    };

    /**
     * Save a fragment into the hash history, or replace the URL state if the
     * 'replace' option is passed. You are responsible for properly URL-encoding
     * the fragment in advance.
     * The options object can contain `trigger: false` if you wish to not have the
     * route callback be fired, or `replace: true`, if
     * you wish to modify the current URL without adding an entry to the history.
     * @method navigate
     * @param {string} fragment The url fragment to navigate to.
     * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default.
     * @return {boolean} Returns true/false from loading the url.
     */
    history.navigate = function(fragment, options) {
        if (!history.active) {
            return false;
        }

        if(options === undefined) {
            options = {
                trigger: true
            };
        }else if(system.isBoolean(options)) {
            options = {
                trigger: options
            };
        }

        fragment = history.getFragment(fragment || '');

        if (history.fragment === fragment) {
            return;
        }

        history.fragment = fragment;

        var url = history.root + fragment;

        // Don't include a trailing slash on the root.
        if(fragment === '' && url !== '/') {
            url = url.slice(0, -1);
        }

        // If pushState is available, we use it to set the fragment as a real URL.
        if (history._hasPushState) {
            history.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);

            // If hash changes haven't been explicitly disabled, update the hash
            // fragment to store history.
        } else if (history._wantsHashChange) {
            updateHash(history.location, fragment, options.replace);
            
            if (history.iframe && (fragment !== history.getFragment(history.getHash(history.iframe)))) {
                // Opening and closing the iframe tricks IE7 and earlier to push a
                // history entry on hash-tag change.  When replace is true, we don't
                // want history.
                if (!options.replace) {
                    history.iframe.document.open().close();
                }
                
                updateHash(history.iframe.location, fragment, options.replace);
            }

            // If you've told us that you explicitly don't want fallback hashchange-
            // based history, then `navigate` becomes a page refresh.
        } else {
            return history.location.assign(url);
        }

        if (options.trigger) {
            return history.loadUrl(fragment);
        }
    };

    /**
     * Navigates back in the browser history.
     * @method navigateBack
     */
    history.navigateBack = function() {
        history.history.back();
    };

    /**
     * @class HistoryOptions
     * @static
     */

    /**
     * The function that will be called back when the fragment changes.
     * @property {function} routeHandler
     */

    /**
     * The url root used to extract the fragment when using push state.
     * @property {string} root
     */

    /**
     * Use hash change when present.
     * @property {boolean} hashChange
     * @default true
     */

    /**
     * Use push state when present.
     * @property {boolean} pushState
     * @default false
     */

    /**
     * Prevents loading of the current url when activating history.
     * @property {boolean} silent
     * @default false
     */

    return history;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * Connects the history module's url and history tracking support to Durandal's activation and composition engine allowing you to easily build navigation-style applications.
 * @module router
 * @requires system
 * @requires app
 * @requires activator
 * @requires events
 * @requires composition
 * @requires history
 * @requires knockout
 * @requires jquery
 */
define('plugins/router',['durandal/system', 'durandal/app', 'durandal/activator', 'durandal/events', 'durandal/composition', 'plugins/history', 'knockout', 'jquery'], function(system, app, activator, events, composition, history, ko, $) {
    var optionalParam = /\((.*?)\)/g;
    var namedParam = /(\(\?)?:\w+/g;
    var splatParam = /\*\w+/g;
    var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
    var startDeferred, rootRouter;
    var trailingSlash = /\/$/;
    var routesAreCaseSensitive = false;
    var lastUrl = '/', lastTryUrl = '/';

    function routeStringToRegExp(routeString) {
        routeString = routeString.replace(escapeRegExp, '\\$&')
            .replace(optionalParam, '(?:$1)?')
            .replace(namedParam, function(match, optional) {
                return optional ? match : '([^\/]+)';
            })
            .replace(splatParam, '(.*?)');

        return new RegExp('^' + routeString + '$', routesAreCaseSensitive ? undefined : 'i');
    }

    function stripParametersFromRoute(route) {
        var colonIndex = route.indexOf(':');
        var length = colonIndex > 0 ? colonIndex - 1 : route.length;
        return route.substring(0, length);
    }

    function endsWith(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    }

    function compareArrays(first, second) {
        if (!first || !second){
            return false;
        }

        if (first.length != second.length) {
            return false;
        }

        for (var i = 0, len = first.length; i < len; i++) {
            if (first[i] != second[i]) {
                return false;
            }
        }

        return true;
    }

    function reconstructUrl(instruction){
        if(!instruction.queryString){
            return instruction.fragment;
        }

        return instruction.fragment + '?' + instruction.queryString;
    }

    /**
     * @class Router
     * @uses Events
     */

    /**
     * Triggered when the navigation logic has completed.
     * @event router:navigation:complete
     * @param {object} instance The activated instance.
     * @param {object} instruction The routing instruction.
     * @param {Router} router The router.
     */

    /**
     * Triggered when the navigation has been cancelled.
     * @event router:navigation:cancelled
     * @param {object} instance The activated instance.
     * @param {object} instruction The routing instruction.
     * @param {Router} router The router.
     */

    /**
     * Triggered when navigation begins.
     * @event router:navigation:processing
     * @param {object} instruction The routing instruction.
     * @param {Router} router The router.
     */

    /**
     * Triggered right before a route is activated.
     * @event router:route:activating
     * @param {object} instance The activated instance.
     * @param {object} instruction The routing instruction.
     * @param {Router} router The router.
     */

    /**
     * Triggered right before a route is configured.
     * @event router:route:before-config
     * @param {object} config The route config.
     * @param {Router} router The router.
     */

    /**
     * Triggered just after a route is configured.
     * @event router:route:after-config
     * @param {object} config The route config.
     * @param {Router} router The router.
     */

    /**
     * Triggered when the view for the activated instance is attached.
     * @event router:navigation:attached
     * @param {object} instance The activated instance.
     * @param {object} instruction The routing instruction.
     * @param {Router} router The router.
     */

    /**
     * Triggered when the composition that the activated instance participates in is complete.
     * @event router:navigation:composition-complete
     * @param {object} instance The activated instance.
     * @param {object} instruction The routing instruction.
     * @param {Router} router The router.
     */

    /**
     * Triggered when the router does not find a matching route.
     * @event router:route:not-found
     * @param {string} fragment The url fragment.
     * @param {Router} router The router.
     */

    var createRouter = function() {
        var queue = [],
            isProcessing = ko.observable(false),
            currentActivation,
            currentInstruction,
            activeItem = activator.create();

        var router = {
            /**
             * The route handlers that are registered. Each handler consists of a `routePattern` and a `callback`.
             * @property {object[]} handlers
             */
            handlers: [],
            /**
             * The route configs that are registered.
             * @property {object[]} routes
             */
            routes: [],
            /**
             * The route configurations that have been designated as displayable in a nav ui (nav:true).
             * @property {KnockoutObservableArray} navigationModel
             */
            navigationModel: ko.observableArray([]),
            /**
             * The active item/screen based on the current navigation state.
             * @property {Activator} activeItem
             */
            activeItem: activeItem,
            /**
             * Indicates that the router (or a child router) is currently in the process of navigating.
             * @property {KnockoutComputed} isNavigating
             */
            isNavigating: ko.computed(function() {
                var current = activeItem();
                var processing = isProcessing();
                var currentRouterIsProcesing = current
                    && current.router
                    && current.router != router
                    && current.router.isNavigating() ? true : false;
                return  processing || currentRouterIsProcesing;
            }),
            /**
             * An observable surfacing the active routing instruction that is currently being processed or has recently finished processing.
             * The instruction object has `config`, `fragment`, `queryString`, `params` and `queryParams` properties.
             * @property {KnockoutObservable} activeInstruction
             */
            activeInstruction:ko.observable(null),
            __router__:true
        };

        events.includeIn(router);

        activeItem.settings.areSameItem = function (currentItem, newItem, currentActivationData, newActivationData) {
            if (currentItem == newItem) {
                return compareArrays(currentActivationData, newActivationData);
            }

            return false;
        };

        activeItem.settings.findChildActivator = function(item) {
            if (item && item.router && item.router.parent == router) {
                return item.router.activeItem;
            }

            return null;
        };

        function hasChildRouter(instance, parentRouter) {
            return instance.router && instance.router.parent == parentRouter;
        }

        function setCurrentInstructionRouteIsActive(flag) {
            if (currentInstruction && currentInstruction.config.isActive) {
                currentInstruction.config.isActive(flag);
            }
        }

        function completeNavigation(instance, instruction, mode) {
            system.log('Navigation Complete', instance, instruction);

            var fromModuleId = system.getModuleId(currentActivation);
            if (fromModuleId) {
                router.trigger('router:navigation:from:' + fromModuleId);
            }

            currentActivation = instance;

            setCurrentInstructionRouteIsActive(false);
            currentInstruction = instruction;
            setCurrentInstructionRouteIsActive(true);

            var toModuleId = system.getModuleId(currentActivation);
            if (toModuleId) {
                router.trigger('router:navigation:to:' + toModuleId);
            }

            if (!hasChildRouter(instance, router)) {
                router.updateDocumentTitle(instance, instruction);
            }

            switch (mode) {
                case 'rootRouter':
                    lastUrl = reconstructUrl(currentInstruction);
                    break;
                case 'rootRouterWithChild':
                    lastTryUrl = reconstructUrl(currentInstruction);
                    break;
                case 'lastChildRouter':
                    lastUrl = lastTryUrl;
                    break;
            }

            rootRouter.explicitNavigation = false;
            rootRouter.navigatingBack = false;

            router.trigger('router:navigation:complete', instance, instruction, router);
        }

        function cancelNavigation(instance, instruction) {
            system.log('Navigation Cancelled');

            router.activeInstruction(currentInstruction);

            router.navigate(lastUrl, false);

            isProcessing(false);
            rootRouter.explicitNavigation = false;
            rootRouter.navigatingBack = false;
            router.trigger('router:navigation:cancelled', instance, instruction, router);
        }

        function redirect(url) {
            system.log('Navigation Redirecting');

            isProcessing(false);
            rootRouter.explicitNavigation = false;
            rootRouter.navigatingBack = false;
            router.navigate(url, { trigger: true, replace: true });
        }

        function activateRoute(activator, instance, instruction) {
            rootRouter.navigatingBack = !rootRouter.explicitNavigation && currentActivation != instruction.fragment;
            router.trigger('router:route:activating', instance, instruction, router);

            var options = {
                canDeactivate: !router.parent
            };

            activator.activateItem(instance, instruction.params, options).then(function(succeeded) {
                if (succeeded) {
                    var previousActivation = currentActivation;
                    var withChild = hasChildRouter(instance, router);
                    var mode = '';

                    if (router.parent) {
                        if(!withChild) {
                            mode = 'lastChildRouter';
                        }
                    } else {
                        if (withChild) {
                            mode = 'rootRouterWithChild';
                        } else {
                            mode = 'rootRouter';
                        }
                    }

                    completeNavigation(instance, instruction, mode);

                    if (withChild) {
                        instance.router.trigger('router:route:before-child-routes', instance, instruction, router);

                        var fullFragment = instruction.fragment;
                        if (instruction.queryString) {
                            fullFragment += "?" + instruction.queryString;
                        }

                        instance.router.loadUrl(fullFragment);
                    }

                    if (previousActivation == instance) {
                        router.attached();
                        router.compositionComplete();
                    }
                } else if(activator.settings.lifecycleData && activator.settings.lifecycleData.redirect){
                    redirect(activator.settings.lifecycleData.redirect);
                }else{
                    cancelNavigation(instance, instruction);
                }

                if (startDeferred) {
                    startDeferred.resolve();
                    startDeferred = null;
                }
            }).fail(function(err){
                system.error(err);
            });
        }

        /**
         * Inspects routes and modules before activation. Can be used to protect access by cancelling navigation or redirecting.
         * @method guardRoute
         * @param {object} instance The module instance that is about to be activated by the router.
         * @param {object} instruction The route instruction. The instruction object has config, fragment, queryString, params and queryParams properties.
         * @return {Promise|Boolean|String} If a boolean, determines whether or not the route should activate or be cancelled. If a string, causes a redirect to the specified route. Can also be a promise for either of these value types.
         */
        function handleGuardedRoute(activator, instance, instruction) {
            var resultOrPromise = router.guardRoute(instance, instruction);
            if (resultOrPromise || resultOrPromise === '') {
                if (resultOrPromise.then) {
                    resultOrPromise.then(function(result) {
                        if (result) {
                            if (system.isString(result)) {
                                redirect(result);
                            } else {
                                activateRoute(activator, instance, instruction);
                            }
                        } else {
                            cancelNavigation(instance, instruction);
                        }
                    });
                } else {
                    if (system.isString(resultOrPromise)) {
                        redirect(resultOrPromise);
                    } else {
                        activateRoute(activator, instance, instruction);
                    }
                }
            } else {
                cancelNavigation(instance, instruction);
            }
        }

        function ensureActivation(activator, instance, instruction) {
            if (router.guardRoute) {
                handleGuardedRoute(activator, instance, instruction);
            } else {
                activateRoute(activator, instance, instruction);
            }
        }

        function canReuseCurrentActivation(instruction) {
            return currentInstruction
                && currentInstruction.config.moduleId == instruction.config.moduleId
                && currentActivation
                && ((currentActivation.canReuseForRoute && currentActivation.canReuseForRoute.apply(currentActivation, instruction.params))
                || (!currentActivation.canReuseForRoute && currentActivation.router && currentActivation.router.loadUrl));
        }

        function dequeueInstruction() {
            if (isProcessing()) {
                return;
            }

            var instruction = queue.shift();
            queue = [];

            if (!instruction) {
                return;
            }

            isProcessing(true);
            router.activeInstruction(instruction);
            router.trigger('router:navigation:processing', instruction, router);

            if (canReuseCurrentActivation(instruction)) {
                var tempActivator = activator.create();
                tempActivator.forceActiveItem(currentActivation); //enforce lifecycle without re-compose
                tempActivator.settings.areSameItem = activeItem.settings.areSameItem;
                tempActivator.settings.findChildActivator = activeItem.settings.findChildActivator;
                ensureActivation(tempActivator, currentActivation, instruction);
            } else if(!instruction.config.moduleId) {
                ensureActivation(activeItem, {
                    viewUrl:instruction.config.viewUrl,
                    canReuseForRoute:function() {
                        return true;
                    }
                }, instruction);
            } else {
                system.acquire(instruction.config.moduleId).then(function(m) {
                    var instance = system.resolveObject(m);

                    if(instruction.config.viewUrl) {
                        instance.viewUrl = instruction.config.viewUrl;
                    }

                    ensureActivation(activeItem, instance, instruction);
                }).fail(function(err) {
                    cancelNavigation(null, instruction);
                    system.error('Failed to load routed module (' + instruction.config.moduleId + '). Details: ' + err.message, err);
                });
            }
        }

        function queueInstruction(instruction) {
            queue.unshift(instruction);
            dequeueInstruction();
        }

        // Given a route, and a URL fragment that it matches, return the array of
        // extracted decoded parameters. Empty or unmatched parameters will be
        // treated as `null` to normalize cross-browser behavior.
        function createParams(routePattern, fragment, queryString) {
            var params = routePattern.exec(fragment).slice(1);

            for (var i = 0; i < params.length; i++) {
                var current = params[i];
                params[i] = current ? decodeURIComponent(current) : null;
            }

            var queryParams = router.parseQueryString(queryString);
            if (queryParams) {
                params.push(queryParams);
            }

            return {
                params:params,
                queryParams:queryParams
            };
        }

        function configureRoute(config){
            router.trigger('router:route:before-config', config, router);

            if (!system.isRegExp(config.route)) {
                config.title = config.title || router.convertRouteToTitle(config.route);

                if (!config.viewUrl) {
                    config.moduleId = config.moduleId || router.convertRouteToModuleId(config.route);
                }

                config.hash = config.hash || router.convertRouteToHash(config.route);

                if (config.hasChildRoutes) {
                    config.route = config.route + '*childRoutes';
                }

                config.routePattern = routeStringToRegExp(config.route);
            }else{
                config.routePattern = config.route;
            }

            config.isActive = config.isActive || ko.observable(false);
            router.trigger('router:route:after-config', config, router);
            router.routes.push(config);

            router.route(config.routePattern, function(fragment, queryString) {
                var paramInfo = createParams(config.routePattern, fragment, queryString);
                queueInstruction({
                    fragment: fragment,
                    queryString:queryString,
                    config: config,
                    params: paramInfo.params,
                    queryParams:paramInfo.queryParams
                });
            });
        };

        function mapRoute(config) {
            if(system.isArray(config.route)){
                var isActive = config.isActive || ko.observable(false);

                for(var i = 0, length = config.route.length; i < length; i++){
                    var current = system.extend({}, config);

                    current.route = config.route[i];
                    current.isActive = isActive;

                    if(i > 0){
                        delete current.nav;
                    }

                    configureRoute(current);
                }
            }else{
                configureRoute(config);
            }

            return router;
        }

        /**
         * Parses a query string into an object.
         * @method parseQueryString
         * @param {string} queryString The query string to parse.
         * @return {object} An object keyed according to the query string parameters.
         */
        router.parseQueryString = function (queryString) {
            var queryObject, pairs;

            if (!queryString) {
                return null;
            }

            pairs = queryString.split('&');

            if (pairs.length == 0) {
                return null;
            }

            queryObject = {};

            for (var i = 0; i < pairs.length; i++) {
                var pair = pairs[i];
                if (pair === '') {
                    continue;
                }

                var sp = pair.indexOf("="),
                    key = sp === -1 ? pair : pair.substr(0, sp),
                    value = sp === -1 ? null : decodeURIComponent(pair.substr(sp + 1).replace(/\+/g, ' '));

                var existing = queryObject[key];

                if (existing) {
                    if (system.isArray(existing)) {
                        existing.push(value);
                    } else {
                        queryObject[key] = [existing, value];
                    }
                }
                else {
                    queryObject[key] = value;
                }
            }

            return queryObject;
        };

        /**
         * Add a route to be tested when the url fragment changes.
         * @method route
         * @param {RegEx} routePattern The route pattern to test against.
         * @param {function} callback The callback to execute when the route pattern is matched.
         */
        router.route = function(routePattern, callback) {
            router.handlers.push({ routePattern: routePattern, callback: callback });
        };

        /**
         * Attempt to load the specified URL fragment. If a route succeeds with a match, returns `true`. If no defined routes matches the fragment, returns `false`.
         * @method loadUrl
         * @param {string} fragment The URL fragment to find a match for.
         * @return {boolean} True if a match was found, false otherwise.
         */
        router.loadUrl = function(fragment) {
            var handlers = router.handlers,
                queryString = null,
                coreFragment = fragment,
                queryIndex = fragment.indexOf('?');

            if (queryIndex != -1) {
                coreFragment = fragment.substring(0, queryIndex);
                queryString = fragment.substr(queryIndex + 1);
            }

            if(router.relativeToParentRouter){
                var instruction = this.parent.activeInstruction();
				coreFragment = queryIndex == -1 ? instruction.params.join('/') : instruction.params.slice(0, -1).join('/');

                if(coreFragment && coreFragment.charAt(0) == '/'){
                    coreFragment = coreFragment.substr(1);
                }

                if(!coreFragment){
                    coreFragment = '';
                }

                coreFragment = coreFragment.replace('//', '/').replace('//', '/');
            }

            coreFragment = coreFragment.replace(trailingSlash, '');

            for (var i = 0; i < handlers.length; i++) {
                var current = handlers[i];
                if (current.routePattern.test(coreFragment)) {
                    current.callback(coreFragment, queryString);
                    return true;
                }
            }

            system.log('Route Not Found', fragment, currentInstruction);
            router.trigger('router:route:not-found', fragment, router);

            if (router.parent) {
                lastUrl = lastTryUrl;
            }

            history.navigate(lastUrl, { trigger:false, replace:true });

            rootRouter.explicitNavigation = false;
            rootRouter.navigatingBack = false;

            return false;
        };

        var titleSubscription;
        function setTitle(value) {
            var appTitle = ko.unwrap(app.title);

            if (appTitle) {
                document.title = value + " | " + appTitle;
            } else {
                document.title = value;
            }
        }

        // Allow observable to be used for app.title
        if(ko.isObservable(app.title)) {
            app.title.subscribe(function () {
                var instruction = router.activeInstruction();
                var title = instruction != null ? ko.unwrap(instruction.config.title) : '';
                setTitle(title);
            });
        }

        /**
         * Updates the document title based on the activated module instance, the routing instruction and the app.title.
         * @method updateDocumentTitle
         * @param {object} instance The activated module.
         * @param {object} instruction The routing instruction associated with the action. It has a `config` property that references the original route mapping config.
         */
        router.updateDocumentTitle = function (instance, instruction) {
            var appTitle = ko.unwrap(app.title),
                title = instruction.config.title;

            if (titleSubscription) {
                titleSubscription.dispose();
            }

            if (title) {
                if (ko.isObservable(title)) {
                    titleSubscription = title.subscribe(setTitle);
                    setTitle(title());
                } else {
                    setTitle(title);
                }
            } else if (appTitle) {
                document.title = appTitle;
            }
        };

        /**
         * Save a fragment into the hash history, or replace the URL state if the
         * 'replace' option is passed. You are responsible for properly URL-encoding
         * the fragment in advance.
         * The options object can contain `trigger: false` if you wish to not have the
         * route callback be fired, or `replace: true`, if
         * you wish to modify the current URL without adding an entry to the history.
         * @method navigate
         * @param {string} fragment The url fragment to navigate to.
         * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default.
         * @return {boolean} Returns true/false from loading the url.
         */
        router.navigate = function(fragment, options) {
            if(fragment && fragment.indexOf('://') != -1) {
                window.location.href = fragment;
                return true;
            }

            if(options === undefined || (system.isBoolean(options) && options) || (system.isObject(options) && options.trigger)) {
                rootRouter.explicitNavigation = true;
            }

            if ((system.isBoolean(options) && !options) || (options && options.trigger != undefined && !options.trigger)) {
                lastUrl = fragment;
            }

            return history.navigate(fragment, options);
        };

        /**
         * Navigates back in the browser history.
         * @method navigateBack
         */
        router.navigateBack = function() {
            history.navigateBack();
        };

        router.attached = function() {
            router.trigger('router:navigation:attached', currentActivation, currentInstruction, router);
        };

        router.compositionComplete = function(){
            isProcessing(false);
            router.trigger('router:navigation:composition-complete', currentActivation, currentInstruction, router);
            dequeueInstruction();
        };

        /**
         * Converts a route to a hash suitable for binding to a link's href.
         * @method convertRouteToHash
         * @param {string} route
         * @return {string} The hash.
         */
        router.convertRouteToHash = function(route) {
            route = route.replace(/\*.*$/, '');

            if(router.relativeToParentRouter){
                var instruction = router.parent.activeInstruction(),
                    hash = route ? instruction.config.hash + '/' + route : instruction.config.hash;

                if(history._hasPushState){
                    hash = '/' + hash;
                }

                hash = hash.replace('//', '/').replace('//', '/');
                return hash;
            }

            if(history._hasPushState){
                return route;
            }

            return "#" + route;
        };

        /**
         * Converts a route to a module id. This is only called if no module id is supplied as part of the route mapping.
         * @method convertRouteToModuleId
         * @param {string} route
         * @return {string} The module id.
         */
        router.convertRouteToModuleId = function(route) {
            return stripParametersFromRoute(route);
        };

        /**
         * Converts a route to a displayable title. This is only called if no title is specified as part of the route mapping.
         * @method convertRouteToTitle
         * @param {string} route
         * @return {string} The title.
         */
        router.convertRouteToTitle = function(route) {
            var value = stripParametersFromRoute(route);
            return value.substring(0, 1).toUpperCase() + value.substring(1);
        };

        /**
         * Maps route patterns to modules.
         * @method map
         * @param {string|object|object[]} route A route, config or array of configs.
         * @param {object} [config] The config for the specified route.
         * @chainable
         * @example
         router.map([
         { route: '', title:'Home', moduleId: 'homeScreen', nav: true },
         { route: 'customer/:id', moduleId: 'customerDetails'}
         ]);
         */
        router.map = function(route, config) {
            if (system.isArray(route)) {
                for (var i = 0; i < route.length; i++) {
                    router.map(route[i]);
                }

                return router;
            }

            if (system.isString(route) || system.isRegExp(route)) {
                if (!config) {
                    config = {};
                } else if (system.isString(config)) {
                    config = { moduleId: config };
                }

                config.route = route;
            } else {
                config = route;
            }

            return mapRoute(config);
        };

        /**
         * Builds an observable array designed to bind a navigation UI to. The model will exist in the `navigationModel` property.
         * @method buildNavigationModel
         * @param {number} defaultOrder The default order to use for navigation visible routes that don't specify an order. The default is 100 and each successive route will be one more than that.
         * @chainable
         */
        router.buildNavigationModel = function(defaultOrder) {
            var nav = [], routes = router.routes;
            var fallbackOrder = defaultOrder || 100;

            for (var i = 0; i < routes.length; i++) {
                var current = routes[i];

                if (current.nav) {
                    if (!system.isNumber(current.nav)) {
                        current.nav = ++fallbackOrder;
                    }

                    nav.push(current);
                }
            }

            nav.sort(function(a, b) { return a.nav - b.nav; });
            router.navigationModel(nav);

            return router;
        };

        /**
         * Configures how the router will handle unknown routes.
         * @method mapUnknownRoutes
         * @param {string|function} [config] If not supplied, then the router will map routes to modules with the same name.
         * If a string is supplied, it represents the module id to route all unknown routes to.
         * Finally, if config is a function, it will be called back with the route instruction containing the route info. The function can then modify the instruction by adding a moduleId and the router will take over from there.
         * @param {string} [replaceRoute] If config is a module id, then you can optionally provide a route to replace the url with.
         * @chainable
         */
        router.mapUnknownRoutes = function(config, replaceRoute) {
            var catchAllRoute = "*catchall";
            var catchAllPattern = routeStringToRegExp(catchAllRoute);

            router.route(catchAllPattern, function (fragment, queryString) {
                var paramInfo = createParams(catchAllPattern, fragment, queryString);
                var instruction = {
                    fragment: fragment,
                    queryString: queryString,
                    config: {
                        route: catchAllRoute,
                        routePattern: catchAllPattern
                    },
                    params: paramInfo.params,
                    queryParams: paramInfo.queryParams
                };

                if (!config) {
                    instruction.config.moduleId = fragment;
                } else if (system.isString(config)) {
                    instruction.config.moduleId = config;
                    if(replaceRoute){
                        history.navigate(replaceRoute, { trigger:false, replace:true });
                    }
                } else if (system.isFunction(config)) {
                    var result = config(instruction);
                    if (result && result.then) {
                        result.then(function() {
                            router.trigger('router:route:before-config', instruction.config, router);
                            router.trigger('router:route:after-config', instruction.config, router);
                            queueInstruction(instruction);
                        });
                        return;
                    }
                } else {
                    instruction.config = config;
                    instruction.config.route = catchAllRoute;
                    instruction.config.routePattern = catchAllPattern;
                }

                router.trigger('router:route:before-config', instruction.config, router);
                router.trigger('router:route:after-config', instruction.config, router);
                queueInstruction(instruction);
            });

            return router;
        };

        /**
         * Resets the router by removing handlers, routes, event handlers and previously configured options.
         * @method reset
         * @chainable
         */
        router.reset = function() {
            currentInstruction = currentActivation = undefined;
            router.handlers = [];
            router.routes = [];
            router.off();
            delete router.options;
            return router;
        };

        /**
         * Makes all configured routes and/or module ids relative to a certain base url.
         * @method makeRelative
         * @param {string|object} settings If string, the value is used as the base for routes and module ids. If an object, you can specify `route` and `moduleId` separately. In place of specifying route, you can set `fromParent:true` to make routes automatically relative to the parent router's active route.
         * @chainable
         */
        router.makeRelative = function(settings){
            if(system.isString(settings)){
                settings = {
                    moduleId:settings,
                    route:settings
                };
            }

            if(settings.moduleId && !endsWith(settings.moduleId, '/')){
                settings.moduleId += '/';
            }

            if(settings.route && !endsWith(settings.route, '/')){
                settings.route += '/';
            }

            if(settings.fromParent){
                router.relativeToParentRouter = true;
            }

            router.on('router:route:before-config').then(function(config){
                if(settings.moduleId){
                    config.moduleId = settings.moduleId + config.moduleId;
                }

                if(settings.route){
                    if(config.route === ''){
                        config.route = settings.route.substring(0, settings.route.length - 1);
                    }else{
                        config.route = settings.route + config.route;
                    }
                }
            });

            if (settings.dynamicHash) {
                router.on('router:route:after-config').then(function (config) {
                    config.routePattern = routeStringToRegExp(config.route ? settings.dynamicHash + '/' + config.route : settings.dynamicHash);
                    config.dynamicHash = config.dynamicHash || ko.observable(config.hash);
                });

                router.on('router:route:before-child-routes').then(function(instance, instruction, parentRouter) {
                    var childRouter = instance.router;

                    for(var i = 0; i < childRouter.routes.length; i++) {
                        var route = childRouter.routes[i];
                        var params = instruction.params.slice(0);

                        route.hash = childRouter.convertRouteToHash(route.route)
                            .replace(namedParam, function(match) {
                                return params.length > 0 ? params.shift() : match;
                            });

                        route.dynamicHash(route.hash);
                    }
                });
            }

            return router;
        };

        /**
         * Creates a child router.
         * @method createChildRouter
         * @return {Router} The child router.
         */
        router.createChildRouter = function() {
            var childRouter = createRouter();
            childRouter.parent = router;
            return childRouter;
        };

        return router;
    };

    /**
     * @class RouterModule
     * @extends Router
     * @static
     */
    rootRouter = createRouter();
    rootRouter.explicitNavigation = false;
    rootRouter.navigatingBack = false;

    /**
     * Makes the RegExp generated for routes case sensitive, rather than the default of case insensitive.
     * @method makeRoutesCaseSensitive
     */
    rootRouter.makeRoutesCaseSensitive = function(){
        routesAreCaseSensitive = true;
    };

    /**
     * Verify that the target is the current window
     * @method targetIsThisWindow
     * @return {boolean} True if the event's target is the current window, false otherwise.
     */
    rootRouter.targetIsThisWindow = function(event) {
        var targetWindow = $(event.target).attr('target');

        if (!targetWindow ||
            targetWindow === window.name ||
            targetWindow === '_self' ||
            (targetWindow === 'top' && window === window.top)) { return true; }

        return false;
    };

    /**
     * Activates the router and the underlying history tracking mechanism.
     * @method activate
     * @return {Promise} A promise that resolves when the router is ready.
     */
    rootRouter.activate = function(options) {
        return system.defer(function(dfd) {
            startDeferred = dfd;
            rootRouter.options = system.extend({ routeHandler: rootRouter.loadUrl }, rootRouter.options, options);

            history.activate(rootRouter.options);

            if(history._hasPushState){
                var routes = rootRouter.routes,
                    i = routes.length;

                while(i--){
                    var current = routes[i];
                    current.hash = current.hash.replace('#', '/');
                }
            }

            var rootStripper = rootRouter.options.root && new RegExp("^" + rootRouter.options.root + "/");

            $(document).delegate("a", 'click', function(evt){
                
                // ignore default prevented since these are not supposed to behave like links anyway
                if(evt.isDefaultPrevented()){
                    return;
                }

                if(history._hasPushState){
                    if(!evt.altKey && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && rootRouter.targetIsThisWindow(evt)){
                        var href = $(this).attr("href");

                        // Ensure the protocol is not part of URL, meaning its relative.
                        // Stop the event bubbling to ensure the link will not cause a page refresh.
                        if (href != null && !(href.charAt(0) === "#" || /^[a-z]+:/i.test(href))) {
                            rootRouter.explicitNavigation = true;
                            evt.preventDefault();

                            if (rootStripper) {
                                href = href.replace(rootStripper, "");
                            }

                            history.navigate(href);
                        }
                    }
                }else{
                    rootRouter.explicitNavigation = true;
                }
            });

            if(history.options.silent && startDeferred){
                startDeferred.resolve();
                startDeferred = null;
            }
        }).promise();
    };

    /**
     * Deactivate current items and turn history listening off.
     * @method deactivate
     */
    rootRouter.deactivate = function() {
        rootRouter.activeItem(null);
        history.deactivate();
    };

    /**
     * Installs the router's custom ko binding handler.
     * @method install
     */
    rootRouter.install = function(){
        ko.bindingHandlers.router = {
            init: function() {
                return { controlsDescendantBindings: true };
            },
            update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                var settings = ko.utils.unwrapObservable(valueAccessor()) || {};

                if (settings.__router__) {
                    settings = {
                        model:settings.activeItem(),
                        attached:settings.attached,
                        compositionComplete:settings.compositionComplete,
                        activate: false
                    };
                } else {
                    var theRouter = ko.utils.unwrapObservable(settings.router || viewModel.router) || rootRouter;
                    settings.model = theRouter.activeItem();
                    settings.attached = theRouter.attached;
                    settings.compositionComplete = theRouter.compositionComplete;
                    settings.activate = false;
                }

                composition.compose(element, settings, bindingContext);
            }
        };

        ko.virtualElements.allowedBindings.router = true;
    };

    return rootRouter;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('core/viewmodels',["require", "exports", 'plugins/dialog', 'entities/api', 'history/history', 'plugins/router', 'core/util', 'durandal/app', 'core/messageBox', 'plugins/router', 'entities/repo'], function (require, exports, dialog, entities, hist, router, util, durandal, messageBox, durandalRouter, repo) {
    var Command = (function () {
        function Command(execute, canExecute, isActive) {
            this.execute = execute;
            this.canExecute = canExecute;
            this.isActive = isActive;
            if (typeof canExecute === 'undefined') {
                this.canExecute = function () { return true; };
            }
            if (typeof isActive === 'undefined') {
                this.isActive = function () { return true; };
            }
        }
        return Command;
    })();
    exports.Command = Command;
    var CommandCollection = (function () {
        function CommandCollection() {
            this.commandArray = [];
            this.commandIndex = {};
        }
        CommandCollection.prototype.add = function (key, command) {
            if (this.commandIndex[key]) {
                throw new Error('key already exists: ' + key);
            }
            this.commandIndex[key] = command;
            this.commandArray.push(command);
        };
        CommandCollection.prototype.getByKey = function (key) {
            var command = this.commandIndex[key];
            if (command) {
                return command;
            }
            return null;
        };
        CommandCollection.prototype.items = function () {
            return this.commandArray.slice(0);
        };
        return CommandCollection;
    })();
    exports.CommandCollection = CommandCollection;
    var ViewModelBase = (function () {
        function ViewModelBase() {
            this.commands = new CommandCollection();
        }
        ViewModelBase.prototype.activate = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i - 0] = arguments[_i];
            }
            return Q.resolve(null);
        };
        ViewModelBase.prototype.binding = function (view) {
            this.view = view;
        };
        ViewModelBase.prototype.detached = function (view, parent) {
            this.dispose();
        };
        ViewModelBase.prototype.dispose = function () {
            this.view = null;
        };
        return ViewModelBase;
    })();
    exports.ViewModelBase = ViewModelBase;
    var ModalViewModelBase = (function (_super) {
        __extends(ModalViewModelBase, _super);
        function ModalViewModelBase() {
            _super.call(this);
            this.createCommands();
        }
        ModalViewModelBase.prototype.createCommands = function () {
            this.commands.add('submit', new Command(this.submit.bind(this)));
            this.commands.add('cancel', new Command(this.cancel.bind(this)));
        };
        ModalViewModelBase.prototype.activate = function () {
            var _this = this;
            return _super.prototype.activate.call(this).then(function () { return app.modal = _this; });
        };
        ModalViewModelBase.prototype.deactivate = function () {
            app.modal = null;
        };
        ModalViewModelBase.prototype.cancel = function () {
            dialog.close(this, false);
        };
        ModalViewModelBase.prototype.submit = function () {
            dialog.close(this, true);
        };
        return ModalViewModelBase;
    })(ViewModelBase);
    exports.ModalViewModelBase = ModalViewModelBase;
    function addCommandBarAndValidationSummaryResizeTracking(view) {
        var $commandBar = $('div.command-bar:first', view), $validationSummary = $('div.validation-summary:first', view), $content = $('div.content:first', view);
        if ($validationSummary.length === 0 || $content.length === 0 || $commandBar.length === 0) {
            return;
        }
        var handleResize = function (event) {
            var $commandBarTop = $commandBar.position().top;
            var $commandBarOuterHeight = $commandBar.outerHeight();
            $validationSummary.css({ top: ($commandBarTop + $commandBarOuterHeight).toString() + 'px' });
            var $validationSummaryOuterHeight = 0;
            if ($validationSummary[0].children[0]["style"].display !== "none") {
                $validationSummaryOuterHeight = $validationSummary.outerHeight();
            }
            $content.css({ top: ($commandBarTop + $commandBarOuterHeight + $validationSummaryOuterHeight).toString() + 'px' });
        };
        $commandBar.bind('resize', handleResize);
        $validationSummary.bind('resize', handleResize);
    }
    function removeCommandBarAndValidationSummaryResizeTracking(view) {
        var $commandBar = $('div.command-bar:first', view), $validationSummary = $('div.validation-summary:first', view);
        if ($commandBar.length > 0) {
            $commandBar.unbind();
        }
        if ($validationSummary.length > 0) {
            $validationSummary.unbind();
        }
    }
    exports.removeCommandBarAndValidationSummaryResizeTracking = removeCommandBarAndValidationSummaryResizeTracking;
    var EntityCollectionViewModel = (function (_super) {
        __extends(EntityCollectionViewModel, _super);
        function EntityCollectionViewModel(entityManager, parentEntity, navigationPropertyName, entityViewModelConstructor) {
            var _this = this;
            _super.call(this);
            this.entityManager = entityManager;
            this.parentEntity = parentEntity;
            this.navigationPropertyName = navigationPropertyName;
            this.entityViewModelConstructor = entityViewModelConstructor;
            this.uncommittedEntity = ko.observable(null);
            var breezeType = parentEntity.entityType.getNavigationProperty(navigationPropertyName);
            this.type = entities.getType(breezeType.name);
            this.entityCollection = parentEntity[navigationPropertyName];
            var me = this;
            this.entities = ko.computed(function () { return _this.entityCollection().filter(function (x) { return x !== me.uncommittedEntity(); }); });
        }
        EntityCollectionViewModel.prototype.add = function (vm, event) {
            var _this = this;
            var entity = this.entityManager.createChildEntity(this.parentEntity, this.navigationPropertyName);
            this.uncommittedEntity(entity);
            var dialogViewModel = (new this.entityViewModelConstructor(entity, true));
            durandal.showDialog(dialogViewModel).then(function (dialogResult) {
                if (!dialogResult) {
                    _this.remove(entity, null);
                }
                _this.uncommittedEntity(null);
                if (event)
                    $(event.target).focus();
                if (dialogViewModel.addNextPressed)
                    _this.add(vm, event);
            });
        };
        EntityCollectionViewModel.prototype.open = function (entity, event) {
            var snapshot = new entities.Snapshot(entity);
            durandal.showDialog(new this.entityViewModelConstructor(entity, false)).then(function (dialogResult) {
                if (!dialogResult) {
                    snapshot.restore();
                }
                snapshot.dispose();
                if (event)
                    $(event.target).focus();
            });
        };
        EntityCollectionViewModel.prototype.remove = function (entity, event) {
            entity.entityAspect.setDeleted();
        };
        return EntityCollectionViewModel;
    })(ViewModelBase);
    exports.EntityCollectionViewModel = EntityCollectionViewModel;
    var EntityViewModel = (function (_super) {
        __extends(EntityViewModel, _super);
        function EntityViewModel() {
            _super.apply(this, arguments);
            this.propertyMetadata = {};
            this.validationErrors = ko.observableArray();
            this.isReadOnly = ko.observable(false);
            this.isDetailReadOnly = ko.observable(false);
            this.isAdd = false;
            this.addNextPressed = false;
            this.filterValidationErrorsByType = function (type) {
                return ko.computed(function () {
                    return this.validationErrors().filter(function (v) { return v.context && v.context.type && v.context.type === type; });
                }, this)();
            };
        }
        EntityViewModel.prototype.activate = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i - 0] = arguments[_i];
            }
            return _super.prototype.activate.apply(this, args);
        };
        EntityViewModel.prototype.initialize = function (entity, isAdd, isParentReadOnly) {
            this.entity = entity;
            this.isAdd = isAdd;
            this.isParentReadOnly = isParentReadOnly;
            try {
                this.type = entities.getDisplayType(entity.entityType.name);
            }
            catch (e) {
            }
            if (this.type == undefined)
                this.type = entities.getType(entity.entityType.name);
            this.entityId = entities.getEntityId(this.entity);
            this.propertyChangedSubscription = entity.entityAspect.propertyChanged.subscribe(this.onPropertyChanged.bind(this));
            this.entityValidationErrorsChangedSubscription = entity.entityAspect.validationErrorsChanged.subscribe(this.onEntityValidationErrorsChanged.bind(this));
            this.setIsReadOnly();
            this.createPropertyMetadata();
        };
        EntityViewModel.prototype.createPropertyMetadata = function () {
            var _this = this;
            var properties, property, i, visible, enabled, entityCrudOperation = entities.getCrudOperation(this.entity);
            properties = util.recurse(this.entity.entityType, function (entityType) { return entityType.baseEntityType; }).map(function (entityType) { return entityType.dataProperties; }).reduce(function (a, b) { return a.concat(b); });
            for (i = 0; i < properties.length; i++) {
                property = properties[i];
                visible = true;
                enabled = true;
                this.propertyMetadata[property.name] = {
                    visible: ko.observable(visible),
                    enable: ko.computed(function () { return enabled && !_this.isDetailReadOnly(); }, this)
                };
            }
        };
        EntityViewModel.prototype.onEntityValidationErrorsChanged = function (args) {
            console.log('entity validation errors changed.');
        };
        EntityViewModel.prototype.validate = function () {
            var isValid = this.entity.entityAspect.validateEntity();
            this.validationErrors(this.entity.entityAspect.getValidationErrors());
            return isValid;
        };
        EntityViewModel.prototype.onPropertyChanged = function (data) {
            if (this.validationErrors().length > 0) {
                this.validationErrors([]);
                this.entity.entityAspect.clearValidationErrors();
            }
        };
        EntityViewModel.prototype.dispose = function () {
            if (this.entity === null)
                return;
            if (typeof this.propertyChangedSubscription !== 'undefined') {
                this.entity.entityAspect.propertyChanged.unsubscribe(this.propertyChangedSubscription);
            }
            this.entity.IsNew(this.entity.entityAspect.entityState.isAdded());
            this.entity = null;
            this.type = null;
            _super.prototype.dispose.call(this);
        };
        EntityViewModel.prototype.setIsReadOnly = function () {
            var isBusinessRuleRestricted = this.type.getIsReadOnly && this.type.getIsReadOnly(this.entity);
            this.isReadOnly(isBusinessRuleRestricted || this.isParentReadOnly);
            this.isDetailReadOnly(isBusinessRuleRestricted || this.isParentReadOnly);
        };
        return EntityViewModel;
    })(ViewModelBase);
    exports.EntityViewModel = EntityViewModel;
    var ModalEntityViewModel = (function (_super) {
        __extends(ModalEntityViewModel, _super);
        function ModalEntityViewModel(entity, isAdd, isParentReadOnly) {
            _super.call(this);
            this.initialize(entity, isAdd, isParentReadOnly);
        }
        ModalEntityViewModel.prototype.activate = function () {
            var _this = this;
            return _super.prototype.activate.call(this).then(function () {
                app.modal = _this;
                _this.createCommands();
            });
        };
        ModalEntityViewModel.prototype.createCommands = function () {
            this.commands.add('submit', new Command(this.submit.bind(this)));
            this.commands.add('cancel', new Command(this.cancel.bind(this)));
        };
        ModalEntityViewModel.prototype.deactivate = function () {
            app.modal = null;
        };
        ModalEntityViewModel.prototype.submit = function () {
            this.submitInternal(false);
        };
        ModalEntityViewModel.prototype.addNext = function () {
            this.submitInternal(true);
        };
        ModalEntityViewModel.prototype.cancel = function () {
            dialog.close(this, false);
        };
        ModalEntityViewModel.prototype.submitInternal = function (addNext) {
            if (this.validate()) {
                this.addNextPressed = addNext;
                dialog.close(this, true);
            }
        };
        return ModalEntityViewModel;
    })(EntityViewModel);
    exports.ModalEntityViewModel = ModalEntityViewModel;
    var RootEntityViewModel = (function (_super) {
        __extends(RootEntityViewModel, _super);
        function RootEntityViewModel() {
            _super.apply(this, arguments);
            this.allowDeactivateWithChanges = false;
            this.wasPreviouslyReverted = false;
            this.isClosing = false;
        }
        RootEntityViewModel.prototype.canActivate = function (entityManager) {
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            return true;
        };
        RootEntityViewModel.prototype.activate = function (entityManager) {
            var _this = this;
            var args = [];
            for (var _i = 1; _i < arguments.length; _i++) {
                args[_i - 1] = arguments[_i];
            }
            var promise;
            var deferred = Q.defer();
            var self = this;
            var em = entityManager || this.entityManager;
            this.entityManager = entityManager = em;
            this.parentEntityManager = entityManager.parentEntityManager || null;
            if (entityManager.parentEntityManager) {
                entityManager.entity['ownerTitle'] = this.parentEntityManager.type.getTitle(this.parentEntityManager.entity);
            }
            this.initialize(entityManager.entity, entityManager.entity.entityAspect.entityState.isAdded(), false);
            this.canSave = ko.computed(function () {
                return self.entityManager && self.entityManager.hasChanges() && !self.entityManager.isSavingChanges();
            });
            this.canRevert = ko.computed(function () {
                return _this.canSave() && !self.entity.entityAspect.entityState.isAdded();
            });
            this.canSaveAndClose = this.canSave;
            this.canClose = ko.observable(true);
            this.canRemove = ko.observable(true);
            this.showRemove = ko.observable(this.type.deleteMetadata !== undefined && this.type.deleteMetadata !== null);
            this.canPrint = ko.observable(false);
            this.showPrint = ko.observable(false);
            this.createCommands();
            this.entityChangedSubscription = this.entityManager.entityChanged.subscribe(this.onEntityChanged.bind(this));
            this.entityManagerValidationErrorsChangedSubscription = this.entityManager.validationErrorsChanged.subscribe(this.onEntityManagerValidationErrorsChanged.bind(this));
            promise = _super.prototype.activate.call(this);
            if ('beforeFinishActivate' in this) {
                promise = promise.then(function () { return _this['beforeFinishActivate'].apply(_this); });
            }
            promise.then(function () { return deferred.resolve(null); }).fail(function (reason) { return deferred.reject(reason); });
            if ('afterActivated' in this) {
                promise = promise.then(function () { return _this['afterActivated'].apply(_this); });
            }
            if (entityManager.entity.entityAspect.entityState.isUnchangedOrModified()) {
                promise = promise.then(function () { return hist.push(entityManager); });
            }
            promise.fail(function (reason) {
                if (reason === app.activationCancelledException)
                    return;
                return Q.reject(reason);
            }).done();
            this.type = entities.getRootType(this.entity.entityType.name);
            return deferred.promise;
        };
        RootEntityViewModel.prototype.createCommands = function () {
            this.commands.add('save', new Command(this.save.bind(this), this.canSave.bind(this)));
            this.commands.add('saveAndClose', new Command(this.saveAndClose.bind(this), this.canSaveAndClose.bind(this)));
            this.commands.add('close', new Command(this.close.bind(this), this.canClose.bind(this)));
            this.commands.add('print', new Command(this.print.bind(this), this.canPrint.bind(this)));
            this.commands.add('revert', new Command(this.revert.bind(this), this.canRevert.bind(this)));
            this.commands.add('remove', new Command(this.remove.bind(this), this.canRemove.bind(this)));
        };
        RootEntityViewModel.prototype.getTitle = function () {
            return this.type.getTitle(this.entity);
        };
        RootEntityViewModel.prototype.save = function () {
            var _this = this;
            var promise = Q.resolve(null), deferred = Q.defer(), wasAdded = this.entity.entityAspect.entityState.isAdded();
            if (!this.validate()) {
                app.statusBar.warning($.i18n.t('common.validationErrorsWarningMessage'), 10000);
                return Q.reject('invalid');
            }
            if ('beforeSave' in this) {
                promise = promise.then(function () { return _this['beforeSave'].apply(_this); });
            }
            var self = this;
            if (this.wasPreviouslyReverted) {
                self.entityManager.entity.DateTimeStamp(new Date());
            }
            promise.then(function () { return self.entityManager.saveChanges(); }).then(function (saveResult) {
                if (wasAdded) {
                    hist.push(self.entityManager).done();
                }
                var promise = Q.resolve(null);
                promise = promise.then(function () { return deferred.resolve(saveResult); });
                if ('afterSave' in _this) {
                    promise = promise.then(function () { return _this['afterSave'].apply(_this); });
                }
                promise.done();
            }).fail(function (reason) {
                var entityErrors = reason.entityErrors, messageSubstitutions = [];
                if (entityErrors) {
                    if (reason.sourceEntityManager && reason.sourceEntityManager !== _this.entityManager) {
                        messageSubstitutions.push(_this.entityManager.parentEntityManager.type.getTitle(_this.entityManager.parentEntityManager.entity));
                        messageSubstitutions.push(entityErrors.map(function (x) { return '<li>' + x.errorMessage + '</li>'; }).join());
                        messageBox.show('common.save', 'common.validationErrorsPreventedSave', messageBox.buttons.openCancel, messageSubstitutions).then(function (button) {
                            if (button !== messageBox.open)
                                return;
                            _this.allowDeactivateWithChanges = true;
                            durandalRouter.navigate('#' + entities.getFragment(_this.entityManager.parentEntityManager));
                        });
                    }
                    else {
                        entityErrors.forEach(function (validationError) { return self.validationErrors.push(validationError); });
                    }
                }
                if (entities.isConcurrencyException(reason)) {
                    _this.close();
                }
                deferred.reject(reason);
                if (!entityErrors && !entities.isConcurrencyException(reason))
                    return Q.reject(reason);
            }).done();
            return deferred.promise;
        };
        RootEntityViewModel.prototype.saveAndClose = function () {
            this.isClosing = true;
            return this.save().then(this.close.bind(this));
        };
        RootEntityViewModel.prototype.close = function () {
            if (!this.validate()) {
                app.statusBar.warning($.i18n.t('common.validationErrorsWarningMessage'), 10000);
                return Q.reject('invalid');
            }
            this.isClosing = true;
            if ('beforeClose' in this) {
                return Q.resolve(this['beforeClose'].apply(this)).then(this.navigateBack.bind(this));
            }
            this.navigateBack();
            return Q.resolve(null);
        };
        RootEntityViewModel.prototype.navigateBack = function () {
            router['explicitNavigation'] = false;
            router.navigateBack();
        };
        RootEntityViewModel.prototype.print = function () {
            if (!this.canPrint())
                return;
            router.navigate('#' + entities.getFragment(this.entityManager, 3 /* Print */));
        };
        RootEntityViewModel.prototype.revert = function () {
            if (!this.canRevert())
                return;
            this.entityManager.rejectChanges();
            if ('afterRevert' in this) {
                this['afterRevert']();
            }
            this.wasPreviouslyReverted = true;
        };
        RootEntityViewModel.prototype.remove = function () {
            var _this = this;
            if (!this.canRemove())
                return;
            if (!this.canRemove())
                return;
            this.revert();
            entities.removeRootInstance(this.entity, this.type.name).then(function (result) {
                if (result.isCanceled)
                    return;
                _this.allowDeactivateWithChanges = true;
                _this.close();
            }).done();
        };
        RootEntityViewModel.prototype.onEntityChanged = function (data) {
            this.canSave.valueHasMutated();
            if (this.entity.hasOwnProperty('DateTimeStamp')) {
                this.entity.DateTimeStamp(new Date());
            }
            if ('afterEntityChanged' in this) {
                this['afterEntityChanged'](data);
            }
        };
        RootEntityViewModel.prototype.onEntityManagerValidationErrorsChanged = function (args) {
            console.log('entity manager validation errors changed.');
        };
        RootEntityViewModel.prototype.canDeactivate = function () {
            var deferred = Q.defer();
            this.allowDeactivateWithChanges = (repo.allowSaveWithChanges) ? repo.allowSaveWithChanges : this.allowDeactivateWithChanges;
            if (this.allowDeactivateWithChanges) {
                this.allowDeactivateWithChanges = false;
                return Q.resolve(true);
            }
            this.entityManager.promptToFinalizeChanges().then(function () { return deferred.resolve(true); }).fail(function () { return deferred.resolve(false); }).done();
            return deferred.promise;
        };
        RootEntityViewModel.prototype.compositionComplete = function (child, parent, settings) {
            addCommandBarAndValidationSummaryResizeTracking(this.view);
        };
        RootEntityViewModel.prototype.dispose = function () {
            removeCommandBarAndValidationSummaryResizeTracking(this.view);
            if (typeof this.entityChangedSubscription !== 'undefined' && this.entityManager !== null) {
                this.entityManager.entityChanged.unsubscribe(this.entityChangedSubscription);
            }
            this.entityManager = null;
            _super.prototype.dispose.call(this);
        };
        return RootEntityViewModel;
    })(EntityViewModel);
    exports.RootEntityViewModel = RootEntityViewModel;
    var BusyIndicator = (function () {
        function BusyIndicator() {
            var _this = this;
            this.message = ko.observable('');
            this.isTempReady = ko.observable(false);
            this.isBusyInternal = ko.observable(false);
            this.lastFocusedElement = null;
            this.isBusy = ko.computed(function () { return _this.isBusyInternal() && !_this.isTempReady(); }, this);
            this.loaderContentPanel = $('div.loader div.loader-content-panel:first');
            this.loaderContentPanel.on('keydown', function (ev) { return ev.which !== 9 || !_this.isBusy(); });
        }
        BusyIndicator.prototype.setBusy = function (message) {
            this.message(message);
            this.isBusyInternal(true);
            var x;
            this.lastFocusedElement = document.activeElement;
            this.loaderContentPanel[0].tabIndex = -1;
            this.loaderContentPanel.focus();
        };
        BusyIndicator.prototype.setBusyLoading = function () {
            this.setBusy($.i18n.t('common.loading'));
        };
        BusyIndicator.prototype.setReady = function () {
            this.loaderContentPanel.removeAttr("tabindex");
            if (this.lastFocusedElement) {
                $(this.lastFocusedElement).focus();
            }
            this.lastFocusedElement = null;
            this.isBusyInternal(false);
            this.message('');
        };
        return BusyIndicator;
    })();
    exports.BusyIndicator = BusyIndicator;
    var StatusBar = (function () {
        function StatusBar() {
            this.hasStatus = ko.observable(false);
            this.message = ko.observable('');
            this.statusClass = ko.observable('alert-info');
            this.iconClass = ko.observable('glyphicon-ok');
        }
        StatusBar.prototype.info = function (message, timeout) {
            this.status(message, 'alert-info', 'glyphicon-info-sign', timeout);
        };
        StatusBar.prototype.success = function (message, timeout, glyphicon) {
            this.status(message, 'alert-success', 'glyphicon-ok', timeout);
        };
        StatusBar.prototype.warning = function (message, timeout) {
            this.status(message, 'alert-warning', 'glyphicon-warning-sign', timeout);
        };
        StatusBar.prototype.danger = function (message, timeout) {
            this.status(message, 'alert-danger', 'glyphicon-exclamation-sign', timeout);
        };
        StatusBar.prototype.download = function (message, timeout) {
            this.status(message, 'alert-info', 'glyphicon-cloud-download', timeout);
        };
        StatusBar.prototype.clear = function () {
            this.hasStatus(false);
        };
        StatusBar.prototype.status = function (message, statusClass, iconClass, timeout) {
            var _this = this;
            clearTimeout(this.timeoutHandle);
            this.statusClass(statusClass);
            this.iconClass(iconClass);
            this.message(message);
            this.hasStatus(true);
            if (timeout) {
                this.timeoutHandle = setTimeout(function () { return _this.clear(); }, timeout);
            }
        };
        return StatusBar;
    })();
    exports.StatusBar = StatusBar;
    var Notifier = (function () {
        function Notifier() {
            this.messages = ko.observableArray([]);
            this.statusClass = ko.observable('alert-info');
            this.iconClass = ko.observable('glyphicon-ok');
            this.count = ko.observable(0);
        }
        Notifier.prototype.info = function (notificationInfo) {
            this.notify(0 /* Info */, notificationInfo);
        };
        Notifier.prototype.warning = function (notificationInfo) {
            this.notify(1 /* Warning */, notificationInfo);
        };
        Notifier.prototype.danger = function (notificationInfo) {
            this.notify(2 /* Danger */, notificationInfo);
        };
        Notifier.prototype.remove = function (notificationInfo) {
            var item = util.Arrays.firstOrDefault(this.messages(), function (n) { return equalsIgnoreCase(n.notificationInfo.fullyQualifiedId, notificationInfo.fullyQualifiedId); });
            if (item === null)
                return;
            this.messages.remove(item);
            this.count(this.messages().length);
        };
        Notifier.prototype.notify = function (type, notificationInfo) {
            this.remove(notificationInfo);
            var item = {
                type: type,
                notificationInfo: notificationInfo
            };
            this.messages.push(item);
            this.count(this.messages().length);
        };
        Notifier.prototype.clear = function () {
            this.messages.destroyAll();
        };
        return Notifier;
    })();
    exports.Notifier = Notifier;
    (function (NotificationType) {
        NotificationType[NotificationType["Info"] = 0] = "Info";
        NotificationType[NotificationType["Warning"] = 1] = "Warning";
        NotificationType[NotificationType["Danger"] = 2] = "Danger";
    })(exports.NotificationType || (exports.NotificationType = {}));
    var NotificationType = exports.NotificationType;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/assessment-base',["require", "exports", 'core/viewmodels', 'core/lookups'], function (require, exports, viewmodels, lookups) {
    var AssessmentBase = (function (_super) {
        __extends(AssessmentBase, _super);
        function AssessmentBase() {
            _super.apply(this, arguments);
            this.selectedScreenDesign = ko.observable(null);
            this.enableScreenDesignDropdown = false;
            this.detailsModel = {};
            this.skSaiAssessmentId = 2655;
        }
        AssessmentBase.prototype.beforeFinishActivate = function () {
            var _this = this;
            this.screenDesigns = security.getScreenDesignHeaders(this.type.pageName).filter(function (sd) { return sd.ACTIVE !== 0 || sd.SCREENDESIGNID === _this.entity.ScreenDesignID(); });
            this.detailsModel = {
                Status: this.entity.Status,
                Review: this.entity.Review || ko.observable(''),
                ReviewDate: this.entity.ReviewDate || this.entity['DocDate'],
                FundCode: this.entity.FundCode,
                Program: this.entity.Program || ko.observable(''),
                Agency: this.entity.Agency,
                ServiceProvider: this.entity.ServiceProvider
            };
            if (this.entity.Review) {
                this.reviewTypes = lookups.getLookup(this.type.pageName, 'review', this.entity.Review()).map(function (x) { return x.Description; });
            }
            else {
                this.reviewTypes = [null];
            }
            var consumer = this.entityManager.parentEntityManager.entity;
            this.fundCodes = security.getConsumerFundCodes(consumer);
            if (!isNullOrEmpty(this.entity.FundCode()) && this.fundCodes.length > 0 && this.fundCodes.filter(function (f) { return equalsIgnoreCase(f, _this.entity.FundCode()); }).length === 0) {
                if (this.entity.entityAspect.entityState.isUnchanged()) {
                    this.fundCodes.push(this.entity.FundCode());
                }
                else {
                    this.entity.FundCode(this.fundCodes[0] || null);
                }
            }
            var allStatuses = lookups.getLookup(this.type.pageName, 'status', this.entity.Status()).map(function (x) { return x.Description; });
            this.statuses = ko.computed(function () {
                var currentSelectedScreenDesignId = _this.selectedScreenDesign();
                if (currentSelectedScreenDesignId !== undefined && currentSelectedScreenDesignId !== null && currentSelectedScreenDesignId.SCREENDESIGNID === _this.skSaiAssessmentId && !security.hasPermission(security.Permission.Supervisor)) {
                    var filteredStatuses = allStatuses.filter(function (x) { return x !== security.completeStatuses[0]; });
                    return filteredStatuses;
                }
                return allStatuses;
            });
            this.programs = ko.computed(function () {
                if (!isNullOrEmpty(_this.detailsModel.FundCode()) && consumer.Programs) {
                    return consumer.Programs().filter(function (p) { return equalsIgnoreCase(p.FundCode(), _this.detailsModel.FundCode()); }).map(function (p) { return ({ Agency: p.Agency(), VendorID: p.VendorID() }); });
                }
                return [];
            });
            if (!app.webIntake) {
                var allAgencyPrograms = lookups.agcyPrograms;
                this.agencyPrograms = ko.computed(function () {
                    if (!isNullOrEmpty(_this.detailsModel.FundCode())) {
                        var filteredAgencies = allAgencyPrograms.filter(function (c) { return c.FundCode === _this.detailsModel.FundCode(); });
                        return filteredAgencies;
                    }
                });
                var allserviceProviders = lookups.srvcPrograms;
                this.serviceProviders = ko.computed(function () {
                    if (!isNullOrEmpty(_this.detailsModel.FundCode())) {
                        var filteredServiceProviders = allserviceProviders.filter(function (c) { return c.FundCode === _this.detailsModel.FundCode(); });
                        return filteredServiceProviders;
                    }
                });
            }
            return Q.resolve(null);
        };
        return AssessmentBase;
    })(viewmodels.RootEntityViewModel);
    return AssessmentBase;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/base',["require", "exports", 'core/lookups', 'durandal/app', 'core/viewmodels', 'core/util', 'assessments/scales', 'entities/snapshot'], function (require, exports, lookups, durandal, viewmodels, util, scales, Snapshot) {
    var ActivationArgsBase = (function () {
        function ActivationArgsBase(question) {
            this.question = question;
        }
        return ActivationArgsBase;
    })();
    exports.ActivationArgsBase = ActivationArgsBase;
    var QuestionActivationArgs = (function (_super) {
        __extends(QuestionActivationArgs, _super);
        function QuestionActivationArgs(question, assessment, isReadOnly, entityManager, fillStrResponse) {
            _super.call(this, question);
            this.question = question;
            this.assessment = assessment;
            this.isReadOnly = isReadOnly;
            this.entityManager = entityManager;
            this.fillStrResponse = fillStrResponse;
        }
        return QuestionActivationArgs;
    })(ActivationArgsBase);
    exports.QuestionActivationArgs = QuestionActivationArgs;
    var QuestionOrIndicatorBase = (function (_super) {
        __extends(QuestionOrIndicatorBase, _super);
        function QuestionOrIndicatorBase(args) {
            var _this = this;
            _super.call(this);
            this.args = args;
            this.hasError = ko.observable(false);
            var q = args.question;
            this.inputId = 'input-' + q.SCREENSCALEID.toString();
            this.isSkipped = ko.observable(!q.Show);
            this.initiallySkipped = ko.observable(this.isSkipped());
            this.isSkipped.subscribe(function (isSkipped) {
                if (isSkipped) {
                    q.Show = 0;
                }
                else {
                    q.Show = 1;
                    _this.initiallySkipped(true);
                    if (!isNullOrEmpty(q.DefaultValue) && _this['reset']) {
                        _this['reset']();
                    }
                }
            });
            var required = (q.REQUIRED == -1) ? true : false;
            this.isRequired = ko.observable(required);
            this.isRequired.subscribe(function (isRequired) {
                if (isRequired) {
                    q.REQUIRED = 0;
                }
                else {
                    q.REQUIRED = -1;
                }
            });
            this.padHeight = 0;
            this.properties = JSON.stringify({
                ACTIVE: q.ACTIVE,
                ANSWERSIZE: q.ANSWERSIZE,
                AppType: q.AppType,
                BEGINLEGEND: q.BEGINLEGEND,
                CheckedScale: q.CheckedScale,
                CheckedScaleNeedCodeID: q.CheckedScaleNeedCodeID,
                CONTROLSCREENSCALE: q.CONTROLSCREENSCALE,
                DATETIMESTAMP: q.DATETIMESTAMP,
                DefaultValue: q.DefaultValue,
                DemographicLookupField: q.DemographicLookupField,
                EnrollmentLookupField: q.EnrollmentLookupField,
                ENDLEGEND: q.ENDLEGEND,
                FONTCOLOR: q.FONTCOLOR,
                FONTSIZE: q.FONTSIZE,
                FONTSTYLE: q.FONTSTYLE,
                HEADERCOLOR: q.HEADERCOLOR,
                HEIGHTSCALE: q.HEIGHTSCALE,
                HELPLINE: q.HELPLINE,
                PLACESECTION: q.PLACESECTION,
                PLACEFIELD: q.PLACEFIELD,
                HIGHERLOWERLINK: q.HIGHERLOWERLINK,
                HIGHVALUE: q.HIGHVALUE,
                INCLUDEINSCORE: q.INCLUDEINSCORE,
                LINKSCREENSCALEID: q.LINKSCREENSCALEID,
                LINKVALUE: q.LINKVALUE,
                LOWVALUE: q.LOWVALUE,
                NUMBUTTONS: q.NUMBUTTONS,
                QUESTIONID: q.QUESTIONID,
                ReadOnlyState: q.ReadOnlyState,
                REQUIRED: q.REQUIRED,
                SCREENCOLUMN: q.SCREENCOLUMN,
                SCREENDESIGNID: q.SCREENDESIGNID,
                SCREENSCALE: q.SCREENSCALE,
                SCREENSCALEID: q.SCREENSCALEID,
                SCREENSORTORDER: q.SCREENSORTORDER,
                SECONDARYCODE: q.SECONDARYCODE,
                Show: q.Show,
                SyncBackToDemographics: q.SyncBackToDemographics,
                SyncBackToEnrollments: q.SyncBackToEnrollments,
                TEXTALIGNMENT: q.TEXTALIGNMENT,
                UnCheckedScale: q.UnCheckedScale,
                UnCheckedScaleNeedCodeID: q.UnCheckedScaleNeedCodeID,
                UserStamp: q.UserStamp,
                WIDTHSCALE: q.WIDTHSCALE,
                WrapControl: q.WrapControl,
            }, null, '  ');
        }
        return QuestionOrIndicatorBase;
    })(viewmodels.ViewModelBase);
    exports.QuestionOrIndicatorBase = QuestionOrIndicatorBase;
    var QuestionBase = (function (_super) {
        __extends(QuestionBase, _super);
        function QuestionBase(args) {
            _super.call(this, args);
            this.args = args;
            this.isReadOnly = args.isReadOnly;
            var sDesign = security.getScreenDesignHeaders('ConsumerAssessments');
            this.screenDesignIsReadOnly = (!util.Arrays.any(sDesign, function (s) { return s.SCREENDESIGNID === args.question.SCREENDESIGNID; }));
            this.isLinked = args.question.CONTROLSCREENSCALE === (scales.keys.ctlDemographicDataLookup || scales.keys.ctlEnrollmentDataLookup);
            this.isAnswered = ko.observable(false);
            this.placeholder = 'Enter response...';
            this.label = this.args.question.SCREENSCALE;
            this.reset();
        }
        QuestionBase.prototype.reset = function () {
            this.response = null;
            this.response = this.getResponse(!this.args.isReadOnly);
            this.isAnswered(this.response !== undefined && this.response !== null && this.response.isAnswered());
        };
        QuestionBase.prototype.skip = function () {
            if (this.isSkipped()) {
                return;
            }
            this.isSkipped(true);
            if (this.response) {
                if (this.args.question.CONTROLSCREENSCALE !== scales.keys.ctlHeader && this.args.question.CONTROLSCREENSCALE !== scales.keys.ctlLineSpace) {
                }
                else {
                    this.response.SecID(null);
                }
            }
            this.reset();
        };
        QuestionBase.prototype.getResponse = function (createIfMissing) {
            if (this.response)
                return this.response;
            var scaleId = this.args.question.SCREENSCALEID;
            var matches = this.args.entityManager.entity.Responses().filter(function (r) { return r.ScaleID() === scaleId; });
            if (matches.length > 0)
                this.response = matches[0];
            if (this.response)
                return this.response;
            if (!createIfMissing)
                return null;
            this.response = this.args.entityManager.createChildEntity(this.args.entityManager.entity, 'Responses', {
                ScaleID: scaleId,
                QuestionID: this.args.question.QUESTIONID,
                Scale: this.args.question.SCREENSCALE,
                DateTimeStamp: new Date(),
                UserStamp: User.Current.UserStamp
            });
            return this.response;
        };
        QuestionBase.prototype.getResponseValue = function () {
            var response = this.getResponse(false);
            if (response)
                return response.Item();
            return null;
        };
        QuestionBase.prototype.setResponseValue = function (value, secondaryValue) {
            var isEmpty = typeof value === "undefined" || value === null || value.length === 0;
            var response = this.getResponse(!isEmpty);
            response.Item(value);
            response.SecID(secondaryValue);
            this.isAnswered(typeof response !== "undefined" && response !== null && response.isAnswered());
            var firstFocus = sessionStorage.getItem('IsFirstFocus');
            if ((firstFocus == null || firstFocus == undefined) && (document.activeElement == null || document.activeElement == undefined || document.activeElement.id != this.inputId)) {
                $('#' + this.inputId).focus();
                sessionStorage.setItem('IsFirstFocus', '1');
            }
        };
        QuestionBase.prototype.applyValueFromHistory = function (historyItem) {
        };
        return QuestionBase;
    })(QuestionOrIndicatorBase);
    exports.QuestionBase = QuestionBase;
    var IndicatorBase = (function (_super) {
        __extends(IndicatorBase, _super);
        function IndicatorBase(args) {
            var _this = this;
            this.value = ko.observable(null);
            this.isAnswered = ko.computed(function () { return !isNullOrEmpty(_this.value()); }, this);
            _super.call(this, args);
        }
        IndicatorBase.prototype.reset = function () {
            _super.prototype.reset.call(this);
            if (this.valueSubscription) {
                this.valueSubscription.dispose();
            }
            this.value(_super.prototype.getResponseValue.call(this));
            this.valueSubscription = this.value.subscribe(_super.prototype.setResponseValue, this);
        };
        return IndicatorBase;
    })(QuestionBase);
    exports.IndicatorBase = IndicatorBase;
    var LegacyIndicatorBase = (function (_super) {
        __extends(LegacyIndicatorBase, _super);
        function LegacyIndicatorBase() {
            _super.apply(this, arguments);
        }
        return LegacyIndicatorBase;
    })(IndicatorBase);
    exports.LegacyIndicatorBase = LegacyIndicatorBase;
    var ChoiceQuestionBase = (function (_super) {
        __extends(ChoiceQuestionBase, _super);
        function ChoiceQuestionBase() {
            _super.apply(this, arguments);
        }
        ChoiceQuestionBase.prototype.buildLookup = function () {
            var _this = this;
            var i;
            if (this.args.question.CONTROLSCREENSCALE === scales.keys.ctlCheckbox || this.args.question.CONTROLSCREENSCALE === scales.keys.ctlCheckboxWithNeeds) {
                this.lookup = [
                    { SORTORDER: 0, SCREENLOOKUPID: 0, SCREENLOOKUP1: 'Yes', NeedCodeID: null, SECONDARYVALUE: null, ValueID: null },
                    { SORTORDER: 1, SCREENLOOKUPID: 1, SCREENLOOKUP1: 'No', NeedCodeID: null, SECONDARYVALUE: null, ValueID: null },
                ];
            }
            else if (this.args.question.CONTROLSCREENSCALE === scales.keys.ctlLikert) {
                this.lookup = [];
                i = this.args.question.NUMBUTTONS;
                while (i--) {
                    this.lookup.push({ SORTORDER: 1, SCREENLOOKUPID: i, SCREENLOOKUP1: i.toString(), NeedCodeID: null, SECONDARYVALUE: null, ValueID: null });
                }
            }
            else if (this.args.question.CONTROLSCREENSCALE === scales.keys.ctlDemographicDataLookup) {
                this.lookup = lookups.getLookupByClientSideControlID('Demographics', this.args.question.DemographicLookupField).map(function (x) { return { SORTORDER: x.SortOrder, SCREENLOOKUPID: x.LookupCode, SCREENLOOKUP1: x.Description, NeedCodeID: null, SECONDARYVALUE: x.SecondaryID, ValueID: null }; });
            }
            else if (this.args.question.CONTROLSCREENSCALE === scales.keys.ctlEnrollmentDataLookup) {
                this.lookup = lookups.getLookupByClientSideControlID('Enrollments', this.args.question.EnrollmentLookupField).map(function (x) { return { SORTORDER: x.SortOrder, SCREENLOOKUPID: x.LookupCode, SCREENLOOKUP1: x.Description, NeedCodeID: null, SECONDARYVALUE: x.SecondaryID, ValueID: null }; });
            }
            else {
                this.lookup = this.args.question.SCREENLOOKUPS;
            }
            this.columnClass = 'col-md-4';
            if (util.Arrays.all(this.lookup, function (x) { return x.SCREENLOOKUP1.length <= 10; })) {
                this.columnClass += ' h-auto-width';
            }
            this.choices = this.lookup.sort(function (a, b) { return a.SORTORDER - b.SORTORDER; }).map(function (c, i) { return new ChoiceModel(c, _this.args.question.SCREENSCALEID); });
        };
        ChoiceQuestionBase.prototype.getChoiceByScreenLookupID = function (screenLookupID) {
            if (!this.lookup)
                this.buildLookup();
            var id = parseInt(screenLookupID, 10);
            if (isNaN(id))
                return null;
            var filtered = this.lookup.filter(function (c) { return c.SCREENLOOKUPID === id; });
            if (filtered.length === 0)
                return null;
            return filtered[0];
        };
        ChoiceQuestionBase.prototype.getChoiceByScreenLookupValue = function (screenLookup) {
            if (!this.lookup)
                this.buildLookup();
            var filtered = this.lookup.filter(function (c) { return c.SCREENLOOKUP1.trim() === screenLookup; });
            if (filtered.length === 0)
                return null;
            return filtered[0];
        };
        ChoiceQuestionBase.prototype.showHideChainedChoices = function (allowedSecondaryScreenLookupIds) {
            var q = $('#' + this.inputId);
            if (q[0].tagName === 'SELECT') {
                q.empty();
                q.append('<option value=""></option>');
                this.choices.filter(function (c) { return allowedSecondaryScreenLookupIds.indexOf(c.screenLookupId) !== -1; }).forEach(function (choice) {
                    q.append('<option id="' + choice.inputId + '" value="' + choice.screenLookupId + '">' + choice.name + '</option>');
                });
                return;
            }
            this.choices.forEach(function (c) {
                var el = q.find('#' + c.inputId);
                if (el.length === 0) {
                    throw new Error('unable to locate choice element ' + c.inputId);
                }
                if (el.length > 1) {
                    throw new Error('too many choice elements for ' + c.inputId);
                }
                var show = allowedSecondaryScreenLookupIds.indexOf(c.screenLookupId) !== -1;
                if (el[0].nodeName === 'INPUT') {
                    el = el.parent().parent();
                    if (show) {
                        el.show();
                    }
                    else {
                        el.hide();
                    }
                }
                else {
                    throw new Error('unable to locate choice element ' + c.inputId);
                }
            });
        };
        return ChoiceQuestionBase;
    })(QuestionBase);
    exports.ChoiceQuestionBase = ChoiceQuestionBase;
    var ChoiceModel = (function () {
        function ChoiceModel(choice, scaleId) {
            this.choice = choice;
            this.screenLookupId = choice.SCREENLOOKUPID;
            this.name = choice.SCREENLOOKUP1;
            this.inputId = 'input-' + scaleId.toString() + '-' + choice.SCREENLOOKUPID.toString();
            this.labelId = 'label-' + scaleId.toString() + '-' + choice.SCREENLOOKUPID.toString();
        }
        ChoiceModel.prototype.getTypeAheadMatch = function (search) {
            var regex, isMatch;
            if (search.length === 0)
                return { isMatch: false, name: this.name };
            search = util.escapeRegExp(search);
            regex = new RegExp('^' + search, 'i');
            isMatch = regex.test(this.name);
            return { isMatch: isMatch, name: isMatch ? this.emphasize(this.name, search.length) : this.name };
        };
        ChoiceModel.prototype.emphasize = function (value, length) {
            return '<em>' + value.substr(0, length) + '</em>' + value.substr(length);
        };
        return ChoiceModel;
    })();
    exports.ChoiceModel = ChoiceModel;
    var CollectionQuestionBase = (function (_super) {
        __extends(CollectionQuestionBase, _super);
        function CollectionQuestionBase(args, info) {
            var _this = this;
            _super.call(this, args);
            this.info = info;
            this.uncommittedEntity = ko.observable(null);
            this.setIsAnswered();
            var me = this;
            this.entities = ko.computed(function () {
                if (me.isAnswered())
                    return _this.getEntityCollection(true)().filter(function (x) { return x !== me.uncommittedEntity() && _this.info.getScaleId(x) === _this.args.question.SCREENSCALEID; });
                return [];
            });
        }
        CollectionQuestionBase.prototype.reset = function () {
            _super.prototype.reset.call(this);
            if (this.info)
                this.setIsAnswered();
        };
        CollectionQuestionBase.prototype.setIsAnswered = function () {
            var _this = this;
            var observableCollection = this.getEntityCollection(false), collection = [];
            if (observableCollection !== null)
                collection = observableCollection().filter(function (x) { return _this.info.getScaleId(x) === _this.args.question.SCREENSCALEID; });
            this.isAnswered(collection.length > 0);
            this.isAnswered.notifySubscribers();
        };
        CollectionQuestionBase.prototype.getEntityCollection = function (createIfMissing) {
            return this.args.assessment[this.info.entityCollectionPropertyName];
        };
        CollectionQuestionBase.prototype.add = function (vm, event) {
            var _this = this;
            var entity = this.args.entityManager.createChildEntity(this.args.assessment, this.info.entityCollectionPropertyName, this.info.getNewEntityConfig());
            this.uncommittedEntity(entity);
            var dialogViewModel = (new this.info.entityViewModelConstructor(entity, true, this.args.isReadOnly));
            durandal.showDialog(dialogViewModel).then(function (dialogResult) {
                if (dialogResult) {
                    if (_this.info.disallowMultiple) {
                        var items = _this.entities().filter(function (x) { return x !== entity; }), item;
                        while (item = items.pop()) {
                            _this.remove(item);
                        }
                    }
                }
                else {
                    _this.remove(entity, null);
                }
                _this.uncommittedEntity(null);
                _this.setIsAnswered();
                if (event)
                    $(event.target).focus();
                if (dialogViewModel.addNextPressed)
                    _this.add(vm, event);
            });
        };
        CollectionQuestionBase.prototype.open = function (entity, event) {
            var snapshot = new Snapshot(entity);
            durandal.showDialog(new this.info.entityViewModelConstructor(entity, false, this.args.isReadOnly)).then(function (dialogResult) {
                if (!dialogResult) {
                    snapshot.restore();
                }
                snapshot.dispose();
                if (event)
                    $(event.target).focus();
            });
        };
        CollectionQuestionBase.prototype.remove = function (entity, event) {
            entity.entityAspect.setDeleted();
            this.setIsAnswered();
        };
        return CollectionQuestionBase;
    })(QuestionBase);
    exports.CollectionQuestionBase = CollectionQuestionBase;
});

define('assessments/find',["require", "exports", 'core/util', 'assessments/scales'], function (require, exports, util, scales) {
    var FindQuestion = (function () {
        function FindQuestion(screenDesign) {
            var me = this;
            this.searchString = ko.observable('');
            this.results = ko.observable([]);
            this.showNoResultsMessage = ko.observable(false);
            this.active = ko.observable(false);
            this.throttledSearchString = ko.computed(function () {
                return me.searchString();
            }).extend({ throttle: 500 });
            this.searchString.subscribe(function (value) {
                me.showNoResultsMessage(false);
            });
            this.questions = screenDesign.SCREENQUESTIONS;
            this.throttledSearchString.subscribe(function (value) { return me.performSearch(); });
        }
        FindQuestion.prototype.performSearch = function () {
            var _this = this;
            var s = this.searchString();
            if (s.length < 3) {
                this.showNoResultsMessage(false);
                this.results([]);
                this.active(false);
                return;
            }
            this.active(true);
            var regex = new RegExp(util.escapeRegExp(s), 'i');
            var matches = this.questions.map(function (q) {
                return {
                    questionId: q.QUESTIONID !== null && regex.test(q.QUESTIONID),
                    screenScaleId: regex.test(q.SCREENSCALEID.toString(10)),
                    name: regex.test(q.SCREENSCALE + (q.CONTROLSCREENSCALE === scales.keys.ctlIndicatorField ? ' (Indicator)' : '')),
                    question: q
                };
            }).filter(function (m) { return ((m.questionId || m.screenScaleId || m.name) && !!m.question.Show); }).map(function (m) { return {
                question: m.question,
                nameHtml: (m.question.SCREENSCALE + (m.question.CONTROLSCREENSCALE === scales.keys.ctlIndicatorField ? ' (Indicator)' : '')).replace(regex, _this.highlight),
                propertiesHtml: (m.question.REQUIRED ? 'Required' : 'Optional') + ', ' + (scales.names[m.question.CONTROLSCREENSCALE] || m.question.CONTROLSCREENSCALE) + ', ' + m.question.SCREENSCALEID.toString(10).replace(regex, _this.highlight) + (m.question.QUESTIONID !== null ? ', ' + m.question.QUESTIONID.replace(regex, _this.highlight) : '')
            }; });
            if (matches.length > 30)
                matches = matches.slice(0, 29);
            this.results(matches);
            this.showNoResultsMessage(matches.length === 0);
        };
        FindQuestion.prototype.highlight = function (value) {
            return '<em>' + value + '</em>';
        };
        return FindQuestion;
    })();
    exports.FindQuestion = FindQuestion;
});

define('assessments/hist',["require", "exports", 'assessments/scales'], function (require, exports, scales) {
    var ResponseHistory = (function () {
        function ResponseHistory(ownerId, assessmentId, isReadOnly) {
            this.isReadOnly = isReadOnly;
            var me = this;
            this.unlockedSessions = ko.observableArray([]);
            this.active = ko.observable(false);
            this.isLoading = ko.observable(true);
            this.unableToLoad = ko.observable(false);
            this.history = ko.observable([]);
            this.question = ko.observable(null);
            this.question.subscribe(this.onQuestionChange, this, 'change');
            if (app.webIntake) {
                this.allHistory = [];
                this.isLoading(false);
                return;
            }
            this.isLoading(false);
            this.unableToLoad(true);
        }
        ResponseHistory.prototype.applyValueFromHistory = function (item) {
            if (this.isReadOnly())
                return;
            this.question().applyValueFromHistory(item.response);
        };
        ResponseHistory.prototype.onQuestionChange = function (questionViewModel) {
            var _this = this;
            if (questionViewModel.args.question.CONTROLSCREENSCALE === scales.keys.ctlIndicatorField) {
                if (this.history().length > 0) {
                    this.history([]);
                }
                return;
            }
            this.history(this.getResponseHistory(questionViewModel.args.question.SCREENSCALEID).map(function (r) {
                return {
                    displayValue: _this.getDisplayValue(questionViewModel, r),
                    response: r
                };
            }));
        };
        ResponseHistory.prototype.getResponseHistory = function (scaleId) {
            if (this.isLoading() || this.unableToLoad())
                return [];
            return [];
        };
        ResponseHistory.prototype.getPreviousResponse = function (catalogQuestionId) {
            var history = this.getResponseHistory(catalogQuestionId);
            if (history.length === 0)
                return null;
            return history[0];
        };
        ResponseHistory.prototype.getDisplayValue = function (questionViewModel, response) {
            return 'foo';
        };
        ResponseHistory.prototype.getChoiceDescription = function (choiceId, question) {
            return 'foo';
        };
        return ResponseHistory;
    })();
    exports.ResponseHistory = ResponseHistory;
});

define('assessments/indicator-helper',["require", "exports", 'assessments/scales'], function (require, exports, scales) {
    var IndicatorHelper = (function () {
        function IndicatorHelper() {
            if (IndicatorHelper._instance) {
                throw new Error("Error: Instantiation failed! IndicatorHelper is a static class");
            }
            IndicatorHelper._instance = this;
            this.defaultValueFunction = {};
            this.defaultValueFunction[scales.keys.ctlMultiSelectionListBox] = IndicatorHelper.getMultiChoiceDefaultValue;
            this.defaultValueFunction[scales.keys.ctlMultiSelectionListBoxWithNeeds] = IndicatorHelper.getMultiChoiceDefaultValue;
            this.valueFunction = {};
            this.valueFunction[scales.keys.ctlMultiSelectionListBox] = IndicatorHelper.getMultiChoiceValue;
            this.valueFunction[scales.keys.ctlMultiSelectionListBoxWithNeeds] = IndicatorHelper.getMultiChoiceValue;
            this.valueFunction[scales.keys.ctlDropDownList] = IndicatorHelper.getSingleChoiceValue;
            this.valueFunction[scales.keys.ctlDropDownListWithNeeds] = IndicatorHelper.getSingleChoiceValue;
            this.valueFunction[scales.keys.ctlIndicatorField] = IndicatorHelper.getIndicatorValue;
            this.valueFunction[scales.keys.ctlCurrencyTextbox] = IndicatorHelper.getDecimalValue;
            this.valueFunction[scales.keys.ctlNumericIndicatorField] = IndicatorHelper.getDecimalValue;
            this.valueFunction[scales.keys.ctlNumericTextbox] = IndicatorHelper.getDecimalValue;
            this.valueFunction[scales.keys.ctlRadioButtonList] = IndicatorHelper.getNumericValue;
            this.valueFunction[scales.keys.ctlCommentIndicatorField] = IndicatorHelper.getDecimalValue;
            this.valueFunction[scales.keys.ctlDecimalIndicatorField] = IndicatorHelper.getDecimalValue;
            this.valueFunction[scales.keys.ctlDateIndicatorField] = IndicatorHelper.getIndicatorValue;
            this.valueFunction[scales.keys.ctlDecimalTextbox] = IndicatorHelper.getDecimalValue;
        }
        IndicatorHelper.getDefaultValueByScaleControl = function (controlType) {
            if (typeof this._instance.defaultValueFunction[controlType] !== "function") {
                return this.getDefaultValue();
            }
            return this._instance.defaultValueFunction[controlType]();
        };
        IndicatorHelper.getMultiChoiceDefaultValue = function () {
            return [];
        };
        IndicatorHelper.getDefaultValue = function () {
            return "";
        };
        IndicatorHelper.getValueByScaleControl = function (controlType, Item, SecID) {
            if (typeof this._instance.valueFunction[controlType] !== "function") {
                return this.getValue(Item, SecID);
            }
            var secIdValue = (controlType === scales.keys.ctlRadioButtonList) ? parseFloat(SecID) : SecID;
            return this._instance.valueFunction[controlType](Item, secIdValue);
        };
        IndicatorHelper.getMultiChoiceValue = function (Item, SecID) {
            var values;
            if (SecID !== null && SecID !== "") {
                values = SecID.split('|');
                values.forEach(function (value) {
                    var intValue = parseInt(value, 10);
                    if (!isNaN(intValue)) {
                        value = intValue;
                    }
                });
            }
            else if (Item !== null && Item !== "") {
                values = Item.split('|');
            }
            else {
                values = [];
            }
            return values;
        };
        IndicatorHelper.getSingleChoiceValue = function (Item, SecID) {
            var value;
            if (SecID !== null && SecID !== "") {
                value = parseInt(SecID, 10);
                if (isNaN(value)) {
                    value = SecID;
                }
            }
            else {
                if (Item === null) {
                    value = "";
                }
                else {
                    value = Item;
                }
            }
            return value;
        };
        IndicatorHelper.getIndicatorValue = function (Item, SecID) {
            if (SecID === "true") {
                return true;
            }
            return false;
        };
        IndicatorHelper.getDecimalValue = function (Item, SecID) {
            var value = +Item;
            if (isNaN(value)) {
                return 0;
            }
            return value;
        };
        IndicatorHelper.getNumericValue = function (Item, SecID) {
            if (isNaN(SecID)) {
                return 0;
            }
            return SecID;
        };
        IndicatorHelper.getValue = function (Item, SecID) {
            if (SecID === "") {
                return SecID;
            }
            return Item;
        };
        IndicatorHelper.getQuestionIDByISCREENQUESTION = function (question) {
            var questionID = question.QUESTIONID;
            if (questionID === null || questionID === "") {
                questionID = "s" + question.SCREENSCALEID;
            }
            return questionID;
        };
        IndicatorHelper._instance = new IndicatorHelper();
        return IndicatorHelper;
    })();
    return IndicatorHelper;
});

define('assessments/indicators-manager',["require", "exports", 'assessments/indicator-helper', 'assessments/scales', 'assessments/screen-repo', 'core/util'], function (require, exports, IndicatorHelper, scales, screenRepo, util) {
    var IndicatorsManager = (function () {
        function IndicatorsManager(sessionManager, screenDesign) {
            this.sessionManager = sessionManager;
            this.indicatorFields = [];
            this.indicatorDataModel = {};
            this.constants = {};
            this.questionControls = {};
            this.questionIDs = {};
            this.mapDependencyIndicatorFields = {};
            var that = this;
            var questions = screenDesign.SCREENQUESTIONS.filter(function (sq) { return sq.CONTROLSCREENSCALE !== scales.keys.ctlHeader && sq.CONTROLSCREENSCALE !== scales.keys.ctlInstructionalText; });
            var responses = util.Arrays.toIndex(this.sessionManager.entity.Responses(), function (response) { return response.ScaleID().toString(); });
            questions.forEach(function (question) {
                var response = responses[question.SCREENSCALEID.toString()];
                var questionID = IndicatorHelper.getQuestionIDByISCREENQUESTION(question);
                that.questionIDs[question.SCREENSCALEID] = questionID;
                that.questionControls[questionID] = question.CONTROLSCREENSCALE;
                if (response) {
                    that.indicatorDataModel[questionID] = IndicatorHelper.getValueByScaleControl(that.questionControls[questionID], response.Item(), response.SecID());
                }
                else {
                    that.indicatorDataModel[questionID] = IndicatorHelper.getDefaultValueByScaleControl(that.questionControls[questionID]);
                }
            });
            this.invertedQuestionIds = _.invert(this.questionIDs);
            screenRepo.screenConstants.forEach(function (screenConstant) {
                that.constants[screenConstant.SCREENCONSTANTNAME] = JSON.parse(screenConstant.VALUE);
            });
            this.entityChangedSubscriptionToken = sessionManager.entityChanged.subscribe(this.onEntityChanged.bind(this));
        }
        IndicatorsManager.prototype.initialize = function () {
            this.calculateAllIndicators();
        };
        IndicatorsManager.prototype.onEntityChanged = function (data) {
            var scales;
            if (!this.sessionManager.hasChanges())
                return;
            if (data.entityAction !== breeze.EntityAction.PropertyChange || !data.entity || !data.entity['ScaleID'])
                return;
            var hasChange = this.updateIndicatorModel(data.entity);
            if (hasChange) {
                this.calculateAllIndicators();
            }
        };
        IndicatorsManager.prototype.updateIndicatorModel = function (entity) {
            if (!entity.ScaleID) {
                return false;
            }
            var questionID = this.questionIDs[entity.ScaleID()];
            var newValue = IndicatorHelper.getValueByScaleControl(this.questionControls[questionID], entity.Item(), entity.SecID());
            var hasChange = !_.isEqual(this.indicatorDataModel[questionID], newValue);
            if (hasChange) {
                this.indicatorDataModel[questionID] = newValue;
            }
            return hasChange;
        };
        IndicatorsManager.prototype.calculateAllIndicators = function () {
            var that = this;
            this.indicatorFields.forEach(function (indicatorField) {
                that.calculateIndicator(indicatorField);
            });
        };
        IndicatorsManager.prototype.calculateIndicator = function (indicatorField) {
            var value = indicatorField.resolver.evaluate(this.indicatorDataModel, this.constants);
            if (value === undefined) {
                value = null;
            }
            indicatorField.value(value);
        };
        IndicatorsManager.prototype.addIndicatorViewModel = function (indicatorField) {
            indicatorField.resolver.validate(this.questionIDs, this.invertedQuestionIds);
            this.mapDependencies(indicatorField.resolver.dependencies, indicatorField);
            this.indicatorFields.push(indicatorField);
        };
        IndicatorsManager.prototype.mapDependencies = function (dependencies, indicatorField) {
            var that = this;
            dependencies.forEach(function (scaleID) {
                if (!that.mapDependencies[scaleID]) {
                    that.mapDependencies[scaleID] = [];
                }
                that.mapDependencies[scaleID].push(indicatorField);
            });
        };
        IndicatorsManager.prototype.reset = function () {
        };
        IndicatorsManager.prototype.dispose = function () {
            if (this.sessionManager) {
                this.sessionManager.entityChanged.unsubscribe(this.entityChangedSubscriptionToken);
                this.entityChangedSubscriptionToken = null;
                this.sessionManager = null;
            }
            this.indicatorFields = null;
            this.indicatorDataModel = null;
            this.constants = null;
            this.questionControls = null;
            this.questionIDs = null;
            this.invertedQuestionIds = null;
            this.mapDependencyIndicatorFields = null;
        };
        return IndicatorsManager;
    })();
    return IndicatorsManager;
});

define('assessments/conditions-manager',["require", "exports", 'assessments/scales', 'core/util'], function (require, exports, scales, util) {
    var ConditionsManager = (function () {
        function ConditionsManager(sessionManager, screenDesign) {
            this.sessionManager = sessionManager;
            this.mapFields = [];
            this.mapConditions = {};
            var that = this;
            var conditions = util.Arrays.selectMany(screenDesign.SCREENQUESTIONS, function (sq) { return sq.SourceConditions; });
            this.fixRefs(screenDesign);
            if (conditions.length === 0) {
                return;
            }
            conditions.forEach(function (condition) {
                if (!that.mapConditions[condition.SourceScaleID]) {
                    that.mapConditions[condition.SourceScaleID] = {};
                }
                if (!that.mapConditions[condition.SourceScaleID][condition.TriggerScaleID]) {
                    that.mapConditions[condition.SourceScaleID][condition.TriggerScaleID] = {};
                    that.mapConditions[condition.SourceScaleID][condition.TriggerScaleID].TriggerScaleID = condition.TriggerScaleID;
                    that.mapConditions[condition.SourceScaleID][condition.TriggerScaleID].TriggerScale = condition.TriggerScale;
                    that.mapConditions[condition.SourceScaleID][condition.TriggerScaleID].SourceScale = condition.SourceScale;
                    that.mapConditions[condition.SourceScaleID][condition.TriggerScaleID].Action = condition.Action;
                    that.mapConditions[condition.SourceScaleID][condition.TriggerScaleID].values = [];
                }
                that.mapConditions[condition.SourceScaleID][condition.TriggerScaleID].values.push(condition.Value);
            });
            this.entityChangedSubscriptionToken = sessionManager.entityChanged.subscribe(this.onEntityChanged.bind(this));
        }
        ConditionsManager.prototype.fixRefs = function (screenDesign) {
            var i = screenDesign.SCREENQUESTIONS.length, question, j;
            while (i--) {
                question = screenDesign.SCREENQUESTIONS[i];
                j = question.SourceConditions.length;
                while (j--) {
                    if (question.SCREENSCALEID !== question.SourceConditions[j].SourceScaleID)
                        throw 'unable to fix reference';
                    question.SourceConditions[j].SourceScale = question;
                }
            }
        };
        ConditionsManager.prototype.onEntityChanged = function (data) {
            var scales;
            if (!this.sessionManager.hasChanges())
                return;
            if (data.entityAction !== breeze.EntityAction.PropertyChange || !data.entity || !data.entity['ScaleID'])
                return;
            var entity = data.entity;
            this.applyConditions(entity.ScaleID(), entity.Item());
        };
        ConditionsManager.prototype.applyAllConditions = function () {
            var that = this;
            var responses = this.sessionManager.entity.Responses();
            var sourceIds = _.keys(this.mapConditions);
            sourceIds.forEach(function (sourceId) {
                var response = _.find(responses, function (response) {
                    return response.ScaleID() + '' === sourceId;
                });
                if (response) {
                    that.applyConditions(response.ScaleID(), response.Item());
                }
                else {
                    that.applyConditions(sourceId, "");
                }
            });
        };
        ConditionsManager.prototype.applyConditions = function (sourceID, value) {
            var that = this;
            var triggers = this.mapConditions[sourceID];
            var valueToEvaluate = "";
            if (value !== null) {
                valueToEvaluate = value.toLowerCase().trim();
            }
            if (!triggers || _.isEmpty(triggers)) {
                return;
            }
            var sourceField = this.mapFields[sourceID];
            if (!sourceField) {
                return;
            }
            if (sourceField.args.question.CONTROLSCREENSCALE === scales.keys.ctlMultiSelectionListBox || sourceField.args.question.CONTROLSCREENSCALE === scales.keys.ctlMultiSelectionListBoxWithNeeds) {
                valueToEvaluate = valueToEvaluate.split("|");
            }
            _.each(triggers, function (trigger) {
                var triggerField = that.mapFields[trigger.TriggerScaleID];
                if (triggerField) {
                    var isConditionEqual = false;
                    isConditionEqual = _.some(trigger.values, function (value) {
                        var conditionValue = value.toLowerCase().trim();
                        if (trigger.SourceScale.CONTROLSCREENSCALE === scales.keys.ctlMultiSelectionListBox || trigger.SourceScale.CONTROLSCREENSCALE === scales.keys.ctlMultiSelectionListBoxWithNeeds) {
                            conditionValue = conditionValue.split("|");
                            return that.evaluateMultiSelectionCondition(conditionValue, valueToEvaluate);
                        }
                        else if (trigger.SourceScale.CONTROLSCREENSCALE === scales.keys.ctlCheckbox) {
                            return that.evaluteCondition(Math.abs(+conditionValue).toString(), valueToEvaluate);
                        }
                        else {
                            return that.evaluteCondition(conditionValue, valueToEvaluate);
                        }
                    });
                    if (trigger.Action === "Make Required") {
                        triggerField.isRequired(isConditionEqual);
                    }
                    else if ((trigger.Action === "Show" && isConditionEqual) || (trigger.Action !== "Show" && !isConditionEqual)) {
                        triggerField.isSkipped(false);
                    }
                    else {
                        if (triggerField['skip']) {
                            triggerField['skip']();
                        }
                        else {
                            triggerField.isSkipped(true);
                        }
                    }
                }
            });
        };
        ConditionsManager.prototype.evaluateMultiSelectionCondition = function (conditionValues, values) {
            for (var i = 0; i < values.length; i++) {
                for (var j = 0; j < conditionValues.length; j++) {
                    if (values[i].toLowerCase().trim() == conditionValues[j].toLowerCase().trim()) {
                        return true;
                    }
                }
            }
            return false;
        };
        ConditionsManager.prototype.evaluteCondition = function (conditionValue, value) {
            return _.isEqual(conditionValue, value);
        };
        ConditionsManager.prototype.addFieldViewModel = function (field) {
            this.mapFields[field.args.question.SCREENSCALEID] = field;
        };
        ConditionsManager.prototype.dispose = function () {
            if (this.sessionManager) {
                this.sessionManager.entityChanged.unsubscribe(this.entityChangedSubscriptionToken);
                this.entityChangedSubscriptionToken = null;
                this.sessionManager = null;
            }
            this.mapFields = null;
            this.mapConditions = null;
        };
        return ConditionsManager;
    })();
    return ConditionsManager;
});

define('assessments/question-focus-history',["require", "exports"], function (require, exports) {
    var QuestionFocusHistory = (function () {
        function QuestionFocusHistory(focusQuestion) {
            var _this = this;
            this.focusQuestion = focusQuestion;
            this.history = ko.observableArray([]);
            this.index = ko.observable(-1);
            this.canGoBack = ko.computed(function () { return _this.index() > 0; }, this);
            this.canGoForward = ko.computed(function () { return _this.index() < _this.history().length - 1 && _this.history().length > 0; }, this);
        }
        QuestionFocusHistory.prototype.pushQuestion = function (question) {
            if (this.ignorePushQuestion)
                return;
            this.history.splice(this.index() + 1, Number.MAX_VALUE, question);
            this.index(this.history().length - 1);
        };
        QuestionFocusHistory.prototype.goBack = function () {
            if (!this.canGoBack())
                return;
            this.index(this.index() - 1);
            this.focusCurrentIndex();
        };
        QuestionFocusHistory.prototype.goForward = function () {
            if (!this.canGoForward())
                return;
            this.index(this.index() + 1);
            this.focusCurrentIndex();
        };
        QuestionFocusHistory.prototype.focusCurrentIndex = function () {
            this.ignorePushQuestion = true;
            this.focusQuestion(this.history()[this.index()]);
            this.ignorePushQuestion = false;
        };
        return QuestionFocusHistory;
    })();
    return QuestionFocusHistory;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/string-control',["require", "exports", 'assessments/base', 'core/util', 'assessments/scales', 'core/lookups'], function (require, exports, base, util, scales, lookups) {
    var StringControl = (function (_super) {
        __extends(StringControl, _super);
        function StringControl(args) {
            this.value = ko.observable(null);
            _super.call(this, args);
            this.vendorID = ko.observable(null);
            this.maxLength = args.question.CONTROLSCREENSCALE === scales.keys.ctlPhoneTextbox ? '9 (000) 000-0000'.length : args.question.ANSWERSIZE;
            this.inputType = 'text';
            if (args.question.CONTROLSCREENSCALE === scales.keys.ctlPhoneTextbox)
                this.inputType = 'tel';
            this.typeaheadOptions = TypeaheadOptionsFactory.create(this, args.question);
            if (this.typeaheadOptions) {
                this.padHeight = 100;
            }
        }
        StringControl.prototype.reset = function () {
            _super.prototype.reset.call(this);
            if (this.valueSubscription) {
                this.valueSubscription.dispose();
            }
            this.value(_super.prototype.getResponseValue.call(this));
            this.valueSubscription = this.value.subscribe(_super.prototype.setResponseValue, this);
        };
        StringControl.prototype.applyValueFromHistory = function (historyItem) {
            _super.prototype.applyValueFromHistory.call(this, historyItem);
            this.value(historyItem.data);
        };
        StringControl.prototype.setVendorID = function (vendorID) {
            _super.prototype.setResponseValue.call(this, vendorID);
            this.vendorID(vendorID);
        };
        StringControl.prototype.getVendorID = function () {
            return this.vendorID();
        };
        return StringControl;
    })(base.QuestionBase);
    var TypeaheadOptionsFactory = (function () {
        function TypeaheadOptionsFactory() {
        }
        TypeaheadOptionsFactory.create = function (vm, question) {
            var fosterParent, vendors, lawEnforcementAgency, roleFundCodes = new RegExp('(^|,)' + User.Current.Role.Role.ROLEFUNDCODEs.map(function (rfc) { return util.escapeRegExp(rfc.FUNDCODE); }).join('|') + '($|,)', 'i'), consumer = vm.args.entityManager.parentEntityManager.entity, rrindex;
            if (question.CONTROLSCREENSCALE === scales.keys.ctlDemographicDataLookup) {
                switch (question.DemographicLookupField) {
                    case scales.DemographicField.PLANGUAGE:
                    case scales.DemographicField.RESCOUNTY:
                    case scales.DemographicField.STATE:
                    case scales.DemographicField.CITIZENSHIP:
                        return new AssessmentTypeaheadOptions(function (query, callback) {
                            return lookups.getLookupByClientSideControlID('Demographics', question.DemographicLookupField).map(function (x) { return x.Description; });
                        }, function (name) { return name; }, function (name) { return name; });
                    default:
                        return null;
                }
            }
            if (question.CONTROLSCREENSCALE === scales.keys.ctlCommentLookup) {
                switch (question.HEADERCOLOR) {
                    case 'Needs':
                    case 'Goals':
                    case 'Objectives':
                    case 'Planned Services':
                    case 'Strengths':
                    case 'Interventions':
                        return new AssessmentTypeaheadOptions(function (query, callback) {
                            var results = consumer.PlanLookups().filter(function (x) { return x.Type() === question.HEADERCOLOR && roleFundCodes.test(x.FundCode()); }).map(function (x) { return x.Description(); }).filter(function (v, i, a) { return a.indexOf(v) === i; }).sort(util.stringComparisonOrdinalIgnoreCase);
                            callback(results);
                        }, function (item) { return item; }, function (item) { return item; }, function (item) { return true; }, function (items) { return items; });
                    default:
                        throw new Error('Unexpected HEADERCOLOR for ' + scales.keys.ctlCommentLookup + ': \'' + (question.HEADERCOLOR || '') + '\'');
                }
            }
            if (question.CONTROLSCREENSCALE === scales.keys.ctlLookupDropDown) {
                switch (question.BEGINLEGEND) {
                    case 'Provider':
                    case 'FundCodeProviders':
                    case 'Resource':
                        var isAPSWebIntake = (typeof WebIntakeSettings !== 'undefined' && WebIntakeSettings != null) ? WebIntakeSettings.Type === 'APSWebIntake' : false;
                        fosterParent = question.BEGINLEGEND === 'Resource';
                        vendors = null;
                        if (!(question.BEGINLEGEND === 'FundCodeProviders' && isAPSWebIntake)) {
                            return new AssessmentTypeaheadOptions(function (query, callback) {
                                if (vendors === null) {
                                    vendors = util.Arrays.toIndex(lookups.vendors, function (x) { return x.Agency; }, function (x) { return x; });
                                }
                                query = query.toLowerCase();
                                var results = lookups.vendors.filter(function (v) { return v.FosterParent === fosterParent && v.Agency.toLowerCase().indexOf(query) !== -1 && roleFundCodes.test(v.FundCodes); }).map(function (v) { return v.Agency; });
                                callback(results);
                            }, function (name) { return name; }, function (name) {
                                var vendor = vendors[name];
                                return htmlEncode(vendor.Agency) + '<br /><sm style="font-size: 12px">' + htmlEncode('id: ' + vendor.VendorID.toString(10) + '; capacity: ' + vendor.Capacity.toString(10) + '; ' + 'enrolled: ' + vendor.Enrolled.toString(10)) + '</sm>';
                            });
                        }
                        else {
                            return new AssessmentTypeaheadOptions(function (query, callback) {
                                if (vendors === null) {
                                    vendors = util.Arrays.toIndex(lookups.vendors, function (x) { return x.Agency; }, function (x) { return x; });
                                }
                                query = query.toLowerCase();
                                var results = lookups.vendors.filter(function (v) { return v.FosterParent === fosterParent && v.Agency.toLowerCase().indexOf(query) !== -1 && roleFundCodes.test(v.FundCodes); }).map(function (v) { return v.Agency; });
                                callback(results);
                            }, function (name) {
                                var vendor = vendors[name];
                                vm.setVendorID(vendor.VendorID.toString());
                                return name;
                            }, function (name) {
                                var vendor = vendors[name];
                                return htmlEncode(vendor.Agency) + '<br /><sm style="font-size: 12px">' + htmlEncode('id: ' + vendor.VendorID.toString(10) + '; capacity: ' + vendor.Capacity.toString(10) + '; ' + 'enrolled: ' + vendor.Enrolled.toString(10)) + '</sm>';
                            }, function (name) { return true; }, null, function (data, event) {
                                var vendorValue = vm.getVendorID();
                                var vendor = (vendorValue != null && vendors != null) ? vendors[vendorValue] : null;
                                if (vendor != null) {
                                    return true;
                                }
                                else {
                                    vm.setVendorID(null);
                                    return false;
                                }
                            });
                        }
                    case 'Relation':
                        var relateReviews = consumer.vw_WH_RELATEREVIEW ? consumer.vw_WH_RELATEREVIEW : function () { return []; };
                        rrindex = util.Arrays.toIndex(relateReviews(), function (x) { return 'id-' + x.RECID(); }, function (x) { return x; });
                        return new AssessmentTypeaheadOptions(function (query, callback) {
                            var results;
                            query = query.toLowerCase();
                            results = relateReviews().map(function (r) { return 'id-' + r.RECID().toString(10); });
                            callback(results);
                        }, function (item) { return ((rrindex[item].FIRSTNAME() || '') + ' ' + (rrindex[item].LASTNAME() || '')).trim(); }, function (item) {
                            var r = rrindex[item];
                            return htmlEncode((r.FIRSTNAME() || '') + ' ' + (r.LASTNAME() || '')).trim() + '<br /><sm style="font-size: 12px">' + r.RELATIONSHIP() + (isNullOrEmpty(r.PHONE()) ? '' : '; ' + r.PHONE()) + (r.DOB() === null ? '' : '; ' + moment(r.DOB()).format('M/D/YYYY')) + '</sm>';
                        }, function (item) { return true; }, function (items) { return items; });
                    case 'Diagnosis':
                        var diagThrottleHandle = null;
                        return new AssessmentTypeaheadOptions(function (query, callback) {
                            clearTimeout(diagThrottleHandle);
                            diagThrottleHandle = setTimeout(function () { return lookups.diagnosisSearch(10, query).then(function (results) { return callback(results.map(function (d) { return '[' + d.Code + ']: ' + d.Description; })); }); }, 300);
                        }, function (name) { return name; }, function (name) { return name; });
                    case 'Medications':
                        return null;
                    case 'Country':
                        return new AssessmentTypeaheadOptions(function (query, callback) {
                            var results;
                            query = query.toLowerCase();
                            results = lookups.countries.filter(function (x) { return x.toLowerCase().indexOf(query) !== -1; });
                            callback(results);
                        }, function (name) { return name; }, function (name) { return name; });
                    case 'State':
                        return new AssessmentTypeaheadOptions(function (query, callback) {
                            var results;
                            query = query.toLowerCase();
                            results = lookups.states.filter(function (x) { return x.name.toLowerCase().indexOf(query) !== -1 || x.abbreviation.toLowerCase().indexOf(query) !== -1; }).map(function (x) { return x.name; });
                            callback(results);
                        }, function (name) { return name; }, function (name) { return name; });
                    case 'Worker':
                        return new AssessmentTypeaheadOptions(function (query, callback) {
                            query = query.toLowerCase();
                            var results = lookups.workers.filter(function (x) { return x.Description.toLowerCase().indexOf(query) !== -1; }).map(function (x) { return x.Description; });
                            callback(results);
                        }, function (name) { return name; }, function (name) { return name; });
                    case 'LawEnforcementAgency':
                        return new AssessmentTypeaheadOptions(function (query, callback) {
                            if (lawEnforcementAgency === null || lawEnforcementAgency === undefined) {
                                lawEnforcementAgency = util.Arrays.toIndex(lookups.lawEnforcementAgency, function (x) { return x.Name; }, function (x) { return x; });
                            }
                            query = query.toLowerCase();
                            var providerData = lookups.lawEnforcementAgency.map(function (v) { return v.Name; });
                            var results = providerData.filter(function (x) { return x.toLowerCase().indexOf(query.toLowerCase()) !== -1; });
                            callback(results);
                        }, function (name) {
                            var vendor = lawEnforcementAgency[name];
                            vm.setVendorID(vendor.Provider_ID.toString());
                            return name;
                        }, function (name) {
                            var vendor = lawEnforcementAgency[name];
                            return htmlEncode(vendor.Name) + '<br /><sm style="font-size: 12px">' + htmlEncode('Id: ' + vendor.Provider_ID.toString(10) + '; ProviderNo: ' + vendor.Provider_No + '; Street: ' + vendor.Street + '; City: ' + vendor.City + '; Medicaid ID: ' + vendor.Medicaid_ID) + '</sm>';
                        }, null, null, function (data, event) {
                            var vendorValue = vm.getVendorID();
                            var vendor = (vendorValue != null && lawEnforcementAgency != null) ? lawEnforcementAgency[vendorValue] : null;
                            if (vendor != null) {
                                return true;
                            }
                            else {
                                vm.setVendorID(null);
                                return false;
                            }
                        });
                    default:
                        throw new Error('Unexpected BEGINLEGEND for ' + scales.keys.ctlLookupDropDown + ': \'' + (question.BEGINLEGEND || '') + '\'');
                }
            }
            if (question.CONTROLSCREENSCALE === scales.keys.ctlPlacesControl) {
                if (question.PLACESECTION != null && question.PLACESECTION != undefined && question.PLACESECTION != '') {
                    StorePlaceControlValue(question.PLACEFIELD, question.PLACESECTION, '');
                    var assTypeAhead = new AssessmentTypeaheadOptions(function (query, callback) {
                        sessionStorage.setItem('onLoadFocus' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION, '1');
                        sessionStorage.setItem('search' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION, '1');
                        if (query != '') {
                            StorePlaceControlValue(question.PLACEFIELD, question.PLACESECTION, query);
                        }
                        else if (!GetPlaceAllowOverrideStatus(question, vm.args.assessment.AssessmentID())) {
                            StorePlaceControlValue(question.PLACEFIELD, question.PLACESECTION, query);
                        }
                        var storeData = GetStoredPlaceControlValues();
                        var groupControls = storeData.filter(function (obj) {
                            if (obj.id.indexOf(question.PLACESECTION) === -1)
                                return false;
                            return true;
                        });
                        var emptyValueControls = groupControls.filter(function (obj) { return obj.value == ''; });
                        if (!(groupControls.length == emptyValueControls.length)) {
                            groupControls.filter(function (obj) {
                                return obj.id == question.PLACEFIELD.toString() + '-' + question.PLACESECTION;
                            })[0].value = '';
                            groupControls.push({ id: 'column', value: question.PLACEFIELD });
                            groupControls.push({ id: 'initialtext', value: query });
                            groupControls.push({ id: 'groupid', value: question.PLACESECTION });
                            lookups.bootstrapPlaceBySelection(groupControls).then(function (results) {
                                var lostFocus = sessionStorage.getItem('lostFocus' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION);
                                if (lostFocus != null)
                                    sessionStorage.removeItem('lostFocus' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION);
                                sessionStorage.setItem('search' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION, '0');
                                if (lookups.placeBySelection.length <= 0) {
                                    if (!GetPlaceAllowOverrideStatus(question, vm.args.assessment.AssessmentID())) {
                                        vm.hasError(true);
                                        StorePlaceControlValue(question.PLACEFIELD, question.PLACESECTION, '');
                                    }
                                    sessionStorage.setItem('placeBySelection' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION, '0');
                                    if (lostFocus != null && lostFocus == '1') {
                                        if (!GetPlaceAllowOverrideStatus(question, vm.args.assessment.AssessmentID())) {
                                            vm.value('');
                                        }
                                        vm.hasError(false);
                                    }
                                }
                                else {
                                    sessionStorage.removeItem('placeBySelection' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION);
                                    vm.hasError(false);
                                }
                                callback(lookups.placeBySelection);
                            });
                        }
                        else {
                            lookups.placeBySelection = [];
                            callback(lookups.placeBySelection);
                        }
                    }, function (name) {
                        StorePlaceControlValue(question.PLACEFIELD, question.PLACESECTION, name);
                        StorePlaceAllowOverrideStatus(vm, 'false');
                        sessionStorage.setItem('selectedItem' + '-' + question.PLACEFIELD + "-" + question.PLACESECTION, '1');
                        return name;
                    }, function (name) { return name; }, function (item) { return true; }, function (items) { return items; }, function (data, event) {
                        sessionStorage.removeItem('onLoadFocus' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION);
                        var search = sessionStorage.getItem('search' + '-' + question.PLACEFIELD + "-" + question.PLACESECTION);
                        var selectedItem = sessionStorage.getItem('selectedItem' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION);
                        if (selectedItem != null)
                            sessionStorage.removeItem('selectedItem' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION);
                        var placeBySelectionValues = JSON.parse(sessionStorage.getItem('placeBySelection' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION));
                        var currentQuestion = data.questionViewModels['q' + question.SCREENSCALEID.toString()];
                        if (search != null) {
                            sessionStorage.removeItem('search' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION);
                            if (search == '0') {
                                if (placeBySelectionValues != null && placeBySelectionValues == '0') {
                                    sessionStorage.removeItem('placeBySelection' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION);
                                    if (currentQuestion != null && currentQuestion != undefined) {
                                        if (!GetPlaceAllowOverrideStatus(currentQuestion.args.question, currentQuestion.args.assessment.AssessmentID())) {
                                            currentQuestion.value('');
                                            currentQuestion.hasError(false);
                                        }
                                    }
                                }
                                if (selectedItem == null) {
                                    if (!GetPlaceAllowOverrideStatus(currentQuestion.args.question, currentQuestion.args.assessment.AssessmentID())) {
                                        StorePlaceControlValue(question.PLACEFIELD, question.PLACESECTION, '');
                                    }
                                    else {
                                        StorePlaceControlValue(question.PLACEFIELD, question.PLACESECTION, currentQuestion.value());
                                        if (currentQuestion.value() != null && currentQuestion.value() != undefined && currentQuestion.value() != '') {
                                            StorePlaceAllowOverrideStatus(currentQuestion, 'true');
                                        }
                                        currentQuestion.hasError(false);
                                    }
                                    if (currentQuestion != null && currentQuestion != undefined) {
                                        if (!GetPlaceAllowOverrideStatus(currentQuestion.args.question, currentQuestion.args.assessment.AssessmentID())) {
                                            currentQuestion.value('');
                                            currentQuestion.hasError(false);
                                        }
                                    }
                                }
                            }
                            else if (search == '1') {
                                if (!GetPlaceAllowOverrideStatus(currentQuestion.args.question, currentQuestion.args.assessment.AssessmentID())) {
                                    StorePlaceControlValue(question.PLACEFIELD, question.PLACESECTION, '');
                                }
                                else {
                                    StorePlaceControlValue(question.PLACEFIELD, question.PLACESECTION, currentQuestion.value());
                                    if (currentQuestion.value() != null && currentQuestion.value() != undefined && currentQuestion.value() != '') {
                                        StorePlaceAllowOverrideStatus(currentQuestion, 'true');
                                    }
                                    currentQuestion.hasError(false);
                                }
                                if (currentQuestion != null && currentQuestion != undefined) {
                                    if (!GetPlaceAllowOverrideStatus(currentQuestion.args.question, currentQuestion.args.assessment.AssessmentID())) {
                                        currentQuestion.value('');
                                        currentQuestion.hasError(false);
                                    }
                                }
                                sessionStorage.setItem('lostFocus' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION, '1');
                            }
                        }
                        return true;
                    });
                    assTypeAhead.minLength = 0;
                    assTypeAhead.items = 10;
                    assTypeAhead.autoSelect = false;
                    return assTypeAhead;
                }
            }
            return null;
        };
        return TypeaheadOptionsFactory;
    })();
    function StorePlaceControlValue(placeFied, placeSection, val) {
        var placeControlStorageKey = 'placeControlValues';
        var placeControlValues = JSON.parse(sessionStorage.getItem(placeControlStorageKey));
        var key = placeFied + "-" + placeSection;
        if (placeControlValues == null)
            placeControlValues = [];
        if (placeControlValues.filter(function (obj) {
            return obj.id == key;
        }).length <= 0)
            placeControlValues.push({ id: key, value: val });
        else
            placeControlValues.filter(function (obj) {
                return obj.id == key;
            })[0].value = val;
        sessionStorage.setItem(placeControlStorageKey, JSON.stringify(placeControlValues));
    }
    function GetStoredPlaceControlValues() {
        var placeControlStorageKey = 'placeControlValues';
        var placeControlValues = JSON.parse(sessionStorage.getItem(placeControlStorageKey));
        return placeControlValues;
    }
    function GetPlaceAllowOverrideStatus(question, assessmentId) {
        var placeAllowOverride = sessionStorage.getItem('PlaceAllowOverride_' + question.PLACESECTION + '_' + assessmentId);
        if (placeAllowOverride === null || placeAllowOverride === undefined) {
            placeAllowOverride = false;
        }
        else {
            placeAllowOverride = (placeAllowOverride.toLowerCase() === 'true');
        }
        if (placeAllowOverride) {
            return true;
        }
        if (question.PlaceAllowOverride === null || question.PlaceAllowOverride === undefined) {
            return false;
        }
        return question.PlaceAllowOverride;
    }
    function StorePlaceAllowOverrideStatus(currentQuestion, status) {
        var placeAllowOverrideKey = 'PlaceAllowOverride_' + currentQuestion.args.question.PLACESECTION + '_' + currentQuestion.args.assessment.AssessmentID();
        var placeAllowOverrideQuestionKey = 'PlaceAllowOverrideQuestionId_' + currentQuestion.args.question.PLACESECTION + '_' + currentQuestion.args.assessment.AssessmentID();
        sessionStorage.setItem(placeAllowOverrideKey, status);
        if (currentQuestion.args.question.PlaceAllowOverride != null || currentQuestion.args.question.PlaceAllowOverride != undefined) {
            if (currentQuestion.args.question.PlaceAllowOverride) {
                var qIds = sessionStorage.getItem(placeAllowOverrideQuestionKey);
                if (qIds === null || qIds === undefined) {
                    qIds = '';
                }
                if (currentQuestion.value() != null && currentQuestion.value() != undefined && currentQuestion.value() === '') {
                    qIds = qIds.replace(currentQuestion.args.question.QUESTIONID, '');
                    if (qIds === '') {
                        sessionStorage.removeItem(placeAllowOverrideQuestionKey);
                        sessionStorage.removeItem(placeAllowOverrideKey);
                    }
                    else {
                        sessionStorage.setItem(placeAllowOverrideQuestionKey, qIds);
                    }
                }
                else if (currentQuestion.value() != null && currentQuestion.value() != undefined && currentQuestion.value() != '') {
                    if (qIds.indexOf(currentQuestion.args.question.QUESTIONID) === -1) {
                        qIds = qIds + currentQuestion.args.question.QUESTIONID;
                    }
                    sessionStorage.setItem(placeAllowOverrideQuestionKey, qIds);
                }
            }
        }
    }
    var AssessmentTypeaheadOptions = (function () {
        function AssessmentTypeaheadOptions(search, getValueFor, highlight, matcher, sorter, blur) {
            this.search = search;
            this.getValueFor = getValueFor;
            this.highlight = highlight;
            this.matcher = matcher;
            this.sorter = sorter;
            this.blur = blur;
            this.items = 15;
            this.autoSelect = true;
            this.minLength = 1;
            var $contentDiv = null, descriptions = null, self = this;
            this.source = function (query, process) { return self.search(query, function (items) { return process(items.slice(0, 15)); }); };
            this.scrollHeight = function () {
                if ($contentDiv === null || $contentDiv.length === 0)
                    $contentDiv = $('.assessment div.form-content:first');
                if ($contentDiv.length === 0)
                    return 0;
                return $contentDiv[0].scrollTop;
            };
            this.updater = function (name) { return getValueFor(name); };
            this.highlighter = function (name) { return highlight(name); };
            if (!blur) {
                this.blur = function (data, event) { return true; };
            }
        }
        return AssessmentTypeaheadOptions;
    })();
    return StringControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/date-control',["require", "exports", 'assessments/base'], function (require, exports, base) {
    var DateControl = (function (_super) {
        __extends(DateControl, _super);
        function DateControl(args) {
            this.value = ko.observable(null);
            _super.call(this, args);
        }
        DateControl.prototype.reset = function () {
            var _this = this;
            _super.prototype.reset.call(this);
            var rawValue = _super.prototype.getResponseValue.call(this);
            var parsed = this.parseValue(rawValue);
            if (this.valueSubscription) {
                this.valueSubscription.dispose();
            }
            this.value(parsed);
            this.valueSubscription = this.value.subscribe(function (newValue) {
                if (newValue != null) {
                    _super.prototype.setResponseValue.call(_this, moment(newValue).format('MM/DD/YYYY'));
                }
                else {
                    _super.prototype.setResponseValue.call(_this, null);
                }
            }, this);
        };
        DateControl.prototype.applyValueFromHistory = function (historyItem) {
            _super.prototype.applyValueFromHistory.call(this, historyItem);
            var parsed = this.parseValue(historyItem.data);
            this.value(parsed);
        };
        DateControl.prototype.parseValue = function (value) {
            if (value === null) {
                return null;
            }
            if (typeof value !== 'string') {
                throw new Error('what is this value?');
            }
            var parsed = moment(value, 'MM/DD/YYYY');
            if (parsed.isValid()) {
                return parsed.toDate();
            }
            return null;
        };
        return DateControl;
    })(base.QuestionBase);
    return DateControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/decimal-control',["require", "exports", 'assessments/base'], function (require, exports, base) {
    var DecimalControl = (function (_super) {
        __extends(DecimalControl, _super);
        function DecimalControl(args) {
            this.value = ko.observable(null);
            if (args.question.HIGHVALUE === null) {
                this.maxValue = 999999.99;
            }
            else {
                this.maxValue = args.question.HIGHVALUE;
            }
            if (args.question.LOWVALUE === null) {
                this.minValue = -999999.99;
            }
            else {
                this.minValue = args.question.LOWVALUE;
            }
            _super.call(this, args);
        }
        DecimalControl.prototype.reset = function () {
            _super.prototype.reset.call(this);
            var rawValue = _super.prototype.getResponseValue.call(this);
            if (isNullOrEmpty(rawValue) && !isNullOrEmpty(this.args.question.DefaultValue)) {
                rawValue = this.args.question.DefaultValue;
            }
            var parsed = this.parseValue(rawValue);
            if (this.valueSubscription) {
                this.valueSubscription.dispose();
            }
            this.value(parsed);
            this.valueSubscription = this.value.subscribe(this.applyValue, this);
        };
        DecimalControl.prototype.applyValue = function (newValue, noDirty) {
            if (newValue !== null) {
                _super.prototype.setResponseValue.call(this, newValue.toString());
            }
            else {
                _super.prototype.setResponseValue.call(this, null);
            }
        };
        DecimalControl.prototype.applyValueFromHistory = function (historyItem) {
            _super.prototype.applyValueFromHistory.call(this, historyItem);
            var parsed = this.parseValue(historyItem.data);
            this.value(parsed);
        };
        DecimalControl.prototype.parseValue = function (value) {
            if (value === null) {
                return null;
            }
            if (typeof value !== 'string') {
                throw new Error('what is this value?');
            }
            var parsed = parseFloat(value);
            if (isNaN(parsed)) {
                return null;
            }
            return parsed;
        };
        return DecimalControl;
    })(base.QuestionBase);
    return DecimalControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/multiple-choice-control',["require", "exports", 'assessments/base'], function (require, exports, base) {
    var MultipleChoiceControl = (function (_super) {
        __extends(MultipleChoiceControl, _super);
        function MultipleChoiceControl(args) {
            this.value = ko.observableArray([]);
            _super.call(this, args);
        }
        MultipleChoiceControl.prototype.reset = function () {
            _super.prototype.reset.call(this);
            if (this.valueSubscription) {
                this.valueSubscription.dispose();
            }
            var rawValue = _super.prototype.getResponseValue.call(this), screenLookupIds = this.parseValue(rawValue);
            this.value(screenLookupIds);
            this.applyValue(screenLookupIds, true);
            this.valueSubscription = this.value.subscribe(this.applyValue, this, 'change');
        };
        MultipleChoiceControl.prototype.parseValue = function (rawValue) {
            var _this = this;
            rawValue = isNullOrEmpty(rawValue) ? '' : rawValue;
            return rawValue.split('|').map(function (x) { return _this.getChoiceByScreenLookupValue(x); }).filter(function (x) { return x !== null; }).map(function (x) { return x.SCREENLOOKUPID.toString(10); });
        };
        MultipleChoiceControl.prototype.applyValue = function (screenLookupIds, noDirty) {
            var _this = this;
            var value;
            if (screenLookupIds === null)
                screenLookupIds = [];
            var choices = screenLookupIds.map(function (screenLookupId) { return _this.getChoiceByScreenLookupID(screenLookupId); }).filter(function (choice) { return choice !== null; });
            if (!noDirty) {
                _super.prototype.setResponseValue.call(this, choices.map(function (c) { return c.SCREENLOOKUP1; }).join('|'), choices.map(function (c) { return c.SECONDARYVALUE || ''; }).join('|'));
            }
            this.isAnswered(choices.length > 0);
        };
        MultipleChoiceControl.prototype.applyValueFromHistory = function (historyItem) {
            _super.prototype.applyValueFromHistory.call(this, historyItem);
            this.value(this.parseValue(historyItem.data));
        };
        MultipleChoiceControl.prototype.selectAll = function () {
            if (this.storeAllowedSecondaryScreenLookupIds != null && this.storeAllowedSecondaryScreenLookupIds != undefined) {
                this.value(this.storeAllowedSecondaryScreenLookupIds);
            }
            else {
                var all = this.choices.map(function (c) { return c.screenLookupId.toString(10); });
                this.value(all);
            }
        };
        MultipleChoiceControl.prototype.selectNone = function () {
            var none = [];
            this.value(none);
        };
        MultipleChoiceControl.prototype.showHideChainedChoices = function (allowedSecondaryScreenLookupIds) {
            this.storeAllowedSecondaryScreenLookupIds = allowedSecondaryScreenLookupIds.map(String);
            _super.prototype.showHideChainedChoices.call(this, allowedSecondaryScreenLookupIds);
            var toSelect = [];
            this.value().forEach(function (v) {
                var value = parseInt(v, 10);
                if (allowedSecondaryScreenLookupIds.indexOf(value) !== -1) {
                    toSelect.push(v.toString());
                }
            });
            this.value(toSelect);
        };
        return MultipleChoiceControl;
    })(base.ChoiceQuestionBase);
    return MultipleChoiceControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/single-choice-control',["require", "exports", 'assessments/base', 'assessments/scales'], function (require, exports, base, scales) {
    var SingleChoiceControl = (function (_super) {
        __extends(SingleChoiceControl, _super);
        function SingleChoiceControl(args) {
            this.value = ko.observable('');
            this.hasDefault = false;
            _super.call(this, args);
        }
        SingleChoiceControl.prototype.reset = function () {
            _super.prototype.reset.call(this);
            if (this.valueSubscription) {
                this.valueSubscription.dispose();
            }
            var screenLookupValue = _super.prototype.getResponseValue.call(this), screenLookupId, noDirty = true;
            if (this.args.question.CONTROLSCREENSCALE === scales.keys.ctlCheckbox || this.args.question.CONTROLSCREENSCALE === scales.keys.ctlCheckboxWithNeeds) {
                switch (screenLookupValue) {
                    case '1':
                        screenLookupId = '0';
                        break;
                    case '0':
                        screenLookupId = '1';
                        break;
                    default:
                        screenLookupId = '';
                        break;
                }
            }
            else {
                var choice = this.getChoiceByScreenLookupValue(screenLookupValue);
                var defaultChoice = this.getChoiceByScreenLookupValue(this.args.question.DefaultValue);
                if (choice == null) {
                    var demographicLookupField = this.args.question.DemographicLookupField;
                    var choiceLength = Number(this.choices.length);
                    var choicesCopy = this.choices;
                    if (choiceLength > 0) {
                        this.lastScreenLookupId = choicesCopy[choiceLength - 1].choice.SCREENLOOKUPID;
                        var additonalRadioOption = [];
                        if (!isNullOrEmpty(screenLookupValue) && demographicLookupField == 'lblRACE') {
                            additonalRadioOption.push({ SORTORDER: +this.lastScreenLookupId + 1, SCREENLOOKUPID: +this.lastScreenLookupId + 1, SCREENLOOKUP1: screenLookupValue.toString().toString(), NeedCodeID: null, SECONDARYVALUE: null, ValueID: null });
                            var additionalOption = new base.ChoiceModel(additonalRadioOption[0], this.args.question.SCREENSCALEID);
                            this.choices.push(additionalOption);
                            choice = additonalRadioOption[0];
                        }
                    }
                }
                this.hasDefault = !!defaultChoice;
                if (!choice && defaultChoice) {
                    choice = defaultChoice;
                    noDirty = false;
                }
                screenLookupId = choice === null ? '' : choice.SCREENLOOKUPID.toString(10);
            }
            this.value(screenLookupId);
            this.applyValue(screenLookupId, noDirty);
            this.valueSubscription = this.value.subscribe(this.applyValue, this);
        };
        SingleChoiceControl.prototype.applyValue = function (screenLookupId, noDirty) {
            var choice = this.getChoiceByScreenLookupID(screenLookupId);
            if (choice === null) {
                if (!noDirty) {
                    _super.prototype.setResponseValue.call(this, '');
                }
            }
            else {
                if (!noDirty) {
                    if (this.args.question.CONTROLSCREENSCALE === scales.keys.ctlCheckbox || this.args.question.CONTROLSCREENSCALE === scales.keys.ctlCheckboxWithNeeds) {
                        _super.prototype.setResponseValue.call(this, choice.SCREENLOOKUP1 === 'Yes' ? '1' : '0', choice.SECONDARYVALUE);
                    }
                    else {
                        _super.prototype.setResponseValue.call(this, choice.SCREENLOOKUP1, choice.SECONDARYVALUE);
                    }
                }
            }
        };
        SingleChoiceControl.prototype.applyValueFromHistory = function (historyItem) {
            _super.prototype.applyValueFromHistory.call(this, historyItem);
            this.value(historyItem.data);
        };
        SingleChoiceControl.prototype.showHideChainedChoices = function (allowedSecondaryScreenLookupIds) {
            _super.prototype.showHideChainedChoices.call(this, allowedSecondaryScreenLookupIds);
            var value = parseInt(this.value(), 10);
            if (isNaN(value) || allowedSecondaryScreenLookupIds.indexOf(value) === -1) {
                this.value('');
            }
        };
        return SingleChoiceControl;
    })(base.ChoiceQuestionBase);
    return SingleChoiceControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/ssn-control',["require", "exports", 'assessments/base'], function (require, exports, base) {
    var SsnControl = (function (_super) {
        __extends(SsnControl, _super);
        function SsnControl(args) {
            var _this = this;
            this.value = ko.observable(null);
            _super.call(this, args);
            this.onBlur = (function (data, event) {
                var input = event.target;
                if (!isNullOrEmpty(_this.validateValue(_this.lastValue))) {
                    setTimeout(function () { return input.value = _this.maskValue(_this.lastValue); }, 0);
                }
                else {
                    _this.removeData(input);
                }
            }).bind(this);
            this.onUnmaskClick = (function (data, event) {
                var input = event.target['previousElementSibling'];
                input.focus();
                input.value = _this.unmaskValue(input.value);
            }).bind(this);
            this.canUnmask = ko.computed(function () { return SystemSettings.EnableSSNMasking && security.hasPermission(security.Permission.SsnUnmask) && !isNullOrEmpty(_this.value()); }, this);
        }
        SsnControl.prototype.reset = function () {
            var _this = this;
            _super.prototype.reset.call(this);
            if (this.valueSubscription) {
                this.valueSubscription.dispose();
            }
            this.lastValue = _super.prototype.getResponseValue.call(this);
            this.value(this.maskValue(this.lastValue));
            this.valueSubscription = this.value.subscribe(function (newValue) {
                _this.lastValue = _this.unmaskValue(newValue);
                _super.prototype.setResponseValue.call(_this, _this.lastValue);
                console.log(_this.lastValue);
            }, this);
        };
        SsnControl.prototype.maskValue = function (value) {
            if (SystemSettings.EnableSSNMasking && !isNullOrEmpty(value) && /^\d{3}-\d{2}-\d{4}$/.test(value)) {
                return 'XXX-XX-' + value.substr(7, 4);
            }
            return value;
        };
        SsnControl.prototype.unmaskValue = function (value) {
            var position = value.indexOf('X');
            while (position !== -1) {
                value = value.substr(0, position) + this.lastValue[position] + value.substr(position + 1);
                position = value.indexOf('X', position);
            }
            return value;
        };
        SsnControl.prototype.removeData = function (element) {
            var $formGroup = $(element).closest('.form-group');
            $formGroup.removeClass('has-success');
            this.lastValue = '';
            this.value('');
        };
        SsnControl.prototype.validateValue = function (value) {
            var SSNVal = /^((?!000)(?!666)([0-8]\d{2}))-((?!00)\d{2})-((?!0000)\d{4})$/;
            if (!isNullOrEmpty(value) && SystemSettings.ValidateSSN && !SSNVal.test(value)) {
                alert('A Social Security Number cannot begin with \"9\", have an area number of \"666\" or \"000\", have a group number of \"00\" or a serial number of \"0000\". Please enter a valid Social Security Number.');
                return '';
            }
            return value;
        };
        SsnControl.prototype.applyValueFromHistory = function (historyItem) {
            _super.prototype.applyValueFromHistory.call(this, historyItem);
            this.value(historyItem.data);
        };
        return SsnControl;
    })(base.QuestionBase);
    return SsnControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/indicator-resolver',["require", "exports", 'core/util'], function (require, exports, util) {
    var utils = {
        InList: function (scalesValues, values) {
            values = values.map(function (x) { return x.toString(); });
            if (_.isArray(scalesValues)) {
                scalesValues = scalesValues.map(function (x) { return x.toString(); });
                var intersection = _.intersection(scalesValues, values);
                return !_.isEmpty(intersection);
            }
            else {
                scalesValues = scalesValues.toString();
                return _.contains(values, scalesValues);
            }
        },
        IsAnswered: function (value) {
            if (_.isString(value) && value === "") {
                return false;
            }
            if (_.isUndefined(value) || _.isNull(value)) {
                return false;
            }
            if (_.isArray(value) && value.length === 0) {
                return false;
            }
            if (_.isObject(value) && _.isEmpty(value)) {
                return false;
            }
            return true;
        },
        contains: function (array, value) {
            if (value === null || value === undefined) {
                return false;
            }
            return util.Arrays.any(array, function (x) { return x !== null && x !== undefined && x.toString() === value.toString(); });
        }
    };
    utils = _.extend({}, _, utils);
    var IndicatorResolverBase = (function () {
        function IndicatorResolverBase(options) {
            this.dependenciesRegex = /scales\[(.[^\[\]]*)\]/g;
            this.hasError = ko.observable(false);
            this.errorMessage = ko.observable(null);
            this.dependencies = [];
            this.originalFormula = options.equation;
            this.formula = options.equation;
        }
        IndicatorResolverBase.prototype.validate = function (questionIds, invertedQuestionIds) {
            this.checkDependecies(invertedQuestionIds);
            if (!this.hasError()) {
                this.validateFormula();
            }
        };
        IndicatorResolverBase.prototype.checkDependecies = function (invertedQuestionIds) {
        };
        IndicatorResolverBase.prototype.validateFormula = function () {
            try {
                this.evaluationFunction = new Function("scales, utils, constants", "return " + this.formula);
            }
            catch (e) {
                this.evaluationFunction = new Function();
                this.dependencies = [];
                this.hasError(true);
                this.errorMessage("Malformed formula: " + this.originalFormula);
            }
        };
        IndicatorResolverBase.prototype.shouldValidateFormula = function () {
            return !/\/\*no-validate\*\//.test(this.formula);
        };
        IndicatorResolverBase.prototype.getDependencies = function () {
            var match;
            var dependencies = [];
            while (match = this.dependenciesRegex.exec(this.formula)) {
                dependencies.push(match[1].replace(/\"|\'/g, ""));
            }
            return dependencies;
        };
        IndicatorResolverBase.prototype.evaluate = function (scales, constants) {
            throw new Error('This method is abstract');
        };
        return IndicatorResolverBase;
    })();
    exports.IndicatorResolverBase = IndicatorResolverBase;
    var IndicatorResolver = (function (_super) {
        __extends(IndicatorResolver, _super);
        function IndicatorResolver(options) {
            _super.call(this, options);
            this.trueMessage = options.trueMessage;
            this.falseMessage = options.falseMessage;
        }
        IndicatorResolver.prototype.evaluate = function (scales, constants) {
            var value;
            if (this.hasError()) {
                return null;
            }
            try {
                value = !!(this.evaluationFunction(scales, utils, constants));
            }
            catch (e) {
                this.hasError(true);
                this.errorMessage("There is an error in with the indicator's formula: " + this.originalFormula);
                return "";
            }
            return (value) ? this.trueMessage : this.falseMessage;
        };
        return IndicatorResolver;
    })(IndicatorResolverBase);
    exports.IndicatorResolver = IndicatorResolver;
    var NumericIndicatorResolver = (function (_super) {
        __extends(NumericIndicatorResolver, _super);
        function NumericIndicatorResolver(options) {
            _super.call(this, options);
        }
        NumericIndicatorResolver.prototype.evaluate = function (scales, constants) {
            var value;
            if (this.hasError()) {
                return null;
            }
            try {
                value = this.evaluationFunction(scales, utils, constants);
            }
            catch (e) {
                this.hasError(true);
                this.errorMessage("There is an error in with the indicator's formula: " + this.originalFormula);
                return "";
            }
            return value;
        };
        return NumericIndicatorResolver;
    })(IndicatorResolverBase);
    exports.NumericIndicatorResolver = NumericIndicatorResolver;
    var LegacyResolver = (function (_super) {
        __extends(LegacyResolver, _super);
        function LegacyResolver() {
            _super.apply(this, arguments);
        }
        LegacyResolver.prototype.validate = function (questionIds, invertedQuestionIds) {
            this.convertFormula(questionIds);
            if (!this.hasError()) {
                this.validateFormula();
            }
        };
        LegacyResolver.prototype.convertFormula = function (questionIDs) {
            throw new Error('This method is abstract');
        };
        return LegacyResolver;
    })(NumericIndicatorResolver);
    exports.LegacyResolver = LegacyResolver;
    var CalculatedFieldResolver = (function (_super) {
        __extends(CalculatedFieldResolver, _super);
        function CalculatedFieldResolver() {
            _super.apply(this, arguments);
            this.regex = /(\d+|\[\d+\])/g;
            this.questionDependencies = [];
        }
        CalculatedFieldResolver.prototype.convertFormula = function (questionIDs) {
            var that = this;
            var match;
            var matches = [];
            var missingDependencies = [];
            try {
                while (match = this.regex.exec(that.formula)) {
                    matches.push(match[1]);
                }
                matches.forEach(function (match) {
                    if (match[0] === "[") {
                        that.formula = that.replaceConstant(that.formula, match);
                    }
                    else {
                        if (match in questionIDs) {
                            that.dependencies.push(match);
                            that.formula = that.replaceScaleID(that.formula, questionIDs, match);
                        }
                        else {
                            missingDependencies.push(match);
                        }
                    }
                });
                if (missingDependencies.length > 0) {
                    this.hasError(true);
                    this.errorMessage('The formula depends on questions that do not exist on the assessment form: ' + missingDependencies.join(', ') + '.');
                    this.dependencies = [];
                    this.evaluationFunction = new Function();
                    return;
                }
            }
            catch (e) {
                this.hasError(true);
                this.dependencies = [];
                this.errorMessage("Error while converting formula: " + this.originalFormula);
            }
        };
        CalculatedFieldResolver.prototype.replaceScaleID = function (equation, questionIDs, scaleID) {
            var questionID = questionIDs[scaleID];
            this.questionDependencies.push(questionID);
            return equation.replace(scaleID, "(+scales['" + questionID + "'])");
        };
        CalculatedFieldResolver.prototype.replaceConstant = function (equation, constant) {
            return equation.replace(constant, constant.replace(/\[|\]/g, ""));
        };
        CalculatedFieldResolver.prototype.evaluate = function (scales, constants) {
            var value;
            if (this.hasError()) {
                return null;
            }
            if (!this.isAnsweredDependencies(scales)) {
                return null;
            }
            try {
                value = this.evaluationFunction(scales, utils, constants);
            }
            catch (e) {
                this.hasError(true);
                this.errorMessage("There is an error in with the indicator's formula: " + this.originalFormula);
                return null;
            }
            return value;
        };
        CalculatedFieldResolver.prototype.isAnsweredDependencies = function (scales) {
            var notAnswered = _.some(this.questionDependencies, function (questionId) {
                return !utils.IsAnswered(scales[questionId]);
            });
            return !notAnswered;
        };
        return CalculatedFieldResolver;
    })(LegacyResolver);
    exports.CalculatedFieldResolver = CalculatedFieldResolver;
    var RawScoreResolver = (function (_super) {
        __extends(RawScoreResolver, _super);
        function RawScoreResolver(options) {
            _super.call(this, options);
            this.regex = /{(.[^{}]+)}/g;
            this.rawscoreId = options.rawscoreId;
        }
        RawScoreResolver.prototype.convertFormula = function (questionIDs) {
            var that = this;
            var match;
            var matches = [];
            if (!(this.rawscoreId in questionIDs)) {
                this.hasError(true);
                this.dependencies = [];
                this.errorMessage('The formula depends on questions that do not exist on the assessment form: ' + this.rawscoreId + '.');
                this.evaluationFunction = new Function();
                return;
            }
            else {
                this.dependencies.push(this.rawscoreId);
            }
            var questionId = questionIDs[this.rawscoreId];
            try {
                this.formula = this.replaceConstants(this.formula);
                this.formula = this.replaceRS(this.formula, questionId);
                while (match = this.regex.exec(this.formula)) {
                    matches.push(match[1]);
                }
                this.formula = this.replaceConditionalLogic(matches, questionId);
            }
            catch (e) {
                this.hasError(true);
                this.errorMessage("Error while converting formula: " + this.originalFormula);
                return;
            }
        };
        RawScoreResolver.prototype.replaceConditionalLogic = function (matches, questionId) {
            var match = matches.shift();
            var conditions = match.split(':');
            var equation = "(" + conditions[0] + ")?" + conditions[1] + ":";
            if (matches.length > 0) {
                equation = equation + "(" + this.replaceConditionalLogic(matches, questionId) + ")";
            }
            else {
                equation = equation + "(+scales['" + questionId + "'])";
            }
            return equation;
        };
        RawScoreResolver.prototype.replaceRS = function (equation, questionId) {
            return equation.replace(/rs/g, "(+scales['" + questionId + "'])");
        };
        RawScoreResolver.prototype.replaceConstants = function (equation) {
            return equation.replace(/\[|\]/g, "");
        };
        return RawScoreResolver;
    })(LegacyResolver);
    exports.RawScoreResolver = RawScoreResolver;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/indicator-control',["require", "exports", 'assessments/base', 'assessments/indicator-resolver'], function (require, exports, base, Resolver) {
    var IndicatorControl = (function (_super) {
        __extends(IndicatorControl, _super);
        function IndicatorControl(args) {
            _super.call(this, args);
            var options = JSON.parse(args.question.BEGINLEGEND);
            this.resolver = new Resolver.IndicatorResolver(options);
            this.trueMessage = options.trueMessage;
            this.falseMessage = options.falseMessage;
        }
        IndicatorControl.prototype.setResponseValue = function (value, secondaryValue) {
            if (value === this.trueMessage) {
                _super.prototype.setResponseValue.call(this, this.trueMessage, "true");
            }
            else {
                _super.prototype.setResponseValue.call(this, this.falseMessage, "false");
            }
        };
        IndicatorControl.prototype.reset = function () {
            _super.prototype.reset.call(this);
            if (this.valueSubscription) {
                this.valueSubscription.dispose();
            }
            this.value(_super.prototype.getResponseValue.call(this));
            this.valueSubscription = this.value.subscribe(this.setResponseValue, this);
        };
        return IndicatorControl;
    })(base.IndicatorBase);
    return IndicatorControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/numeric-indicator-control',["require", "exports", 'assessments/base', 'assessments/indicator-resolver'], function (require, exports, base, Resolver) {
    var NumericIndicatorControl = (function (_super) {
        __extends(NumericIndicatorControl, _super);
        function NumericIndicatorControl(args) {
            _super.call(this, args);
            this.resolver = new Resolver.NumericIndicatorResolver(JSON.parse(args.question.BEGINLEGEND));
        }
        return NumericIndicatorControl;
    })(base.IndicatorBase);
    return NumericIndicatorControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/calculated-control',["require", "exports", 'assessments/base', 'assessments/indicator-resolver'], function (require, exports, base, Resolver) {
    var CalculatedControl = (function (_super) {
        __extends(CalculatedControl, _super);
        function CalculatedControl(args) {
            _super.call(this, args);
            var options = {
                equation: args.question.BEGINLEGEND
            };
            this.resolver = new Resolver.CalculatedFieldResolver(options);
        }
        return CalculatedControl;
    })(base.LegacyIndicatorBase);
    return CalculatedControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/rawscore-control',["require", "exports", 'assessments/base', 'assessments/indicator-resolver'], function (require, exports, base, Resolver) {
    var RawScoreControl = (function (_super) {
        __extends(RawScoreControl, _super);
        function RawScoreControl(args) {
            _super.call(this, args);
            var options = {
                rawscoreId: args.question.BEGINLEGEND,
                equation: args.question.ENDLEGEND
            };
            this.resolver = new Resolver.RawScoreResolver(options);
        }
        return RawScoreControl;
    })(base.LegacyIndicatorBase);
    return RawScoreControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/header-control',["require", "exports", 'assessments/base'], function (require, exports, base) {
    var HeaderControl = (function (_super) {
        __extends(HeaderControl, _super);
        function HeaderControl(args) {
            _super.call(this, args);
            this.skipSub = this.isSkipped.subscribe(this.syncElement.bind(this));
            this.syncElement();
        }
        HeaderControl.prototype.syncElement = function () {
            var skip = this.isSkipped();
            var $el = $('.nav-tree a[href^=\'#section-' + this.args.question.SCREENSCALEID.toString() + '\']').parent();
            if (skip) {
                $el.hide();
            }
            else {
                $el.show();
            }
        };
        HeaderControl.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.skipSub.dispose();
        };
        HeaderControl.prototype.reset = function () {
            _super.prototype.setResponseValue.call(this, this.args.question.SCREENSCALE, null);
        };
        return HeaderControl;
    })(base.QuestionBase);
    return HeaderControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/instructional-control',["require", "exports", 'assessments/base'], function (require, exports, base) {
    var InstructionalControl = (function (_super) {
        __extends(InstructionalControl, _super);
        function InstructionalControl(args) {
            this.value = ko.observable(null);
            _super.call(this, args);
            this.skipSub = this.isSkipped.subscribe(this.syncElement.bind(this));
            this.syncElement();
        }
        InstructionalControl.prototype.syncElement = function () {
            var skip = this.isSkipped();
            var $el = $('.nav-tree a[href^=\'#section-' + this.args.question.SCREENSCALEID.toString() + '\']').parent();
            if (skip) {
                $el.hide();
            }
            else {
                $el.show();
            }
        };
        InstructionalControl.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.skipSub.dispose();
        };
        InstructionalControl.prototype.reset = function () {
            _super.prototype.reset.call(this);
            this.value(this.args.question.BEGINLEGEND);
        };
        return InstructionalControl;
    })(base.QuestionBase);
    return InstructionalControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/medication',["require", "exports", 'core/viewmodels', 'core/lookups'], function (require, exports, viewmodels, lookups) {
    var Medication = (function (_super) {
        __extends(Medication, _super);
        function Medication(entity, isAdd, isParentReadOnly) {
            _super.call(this, entity, isAdd, isParentReadOnly);
            this.frequencyIsLookup = false;
            this.routeadminIsLookup = false;
            this.medmanagerIsLookup = false;
            this.dosageIsText = false;
            if (equalsIgnoreCase(security.getFieldControlType('Medications Detail', 'MEDICATION'), 'ctlMedicationTableSearch')) {
                this.medication = lookups.medications;
            }
            else {
                this.medication = lookups.getLookup('Medications Detail', 'MEDICATION', entity.MEDICATION()).map(function (m) { return m.Description; });
            }
            var retrievedSqQuestionsJSONForMedication = localStorage.getItem("sqQuestionspreForMedication");
            var parseRetrievedSqQuestionsJSONForMedication = JSON.parse(retrievedSqQuestionsJSONForMedication);
            var isMedication = false;
            if (parseRetrievedSqQuestionsJSONForMedication.length > 0) {
                var shouldFieldShow = parseRetrievedSqQuestionsJSONForMedication[0].CONTROLSCREENSCALE === 'ctlMedicationDataForm';
                this.shouldFieldShow = shouldFieldShow;
            }
            this.othermedication = (entity.OTHERMEDICATION());
            this.status = lookups.getLookup('Medications Detail', 'STATUS', entity.STATUS());
            this.routeOfAdministration = lookups.getLookup('Medications Detail', 'ROUTEADMIN', entity.ROUTEADMIN());
            this.whereObtained = lookups.getLookup('Medications Detail', 'MedsObtained', entity.MedsObtained());
            this.mailOrder = lookups.getLookup('Medications Detail', 'MailOrder', entity.MailOrder());
            this.packaging = lookups.getLookup('Medications Detail', 'Packaging', entity.Packaging());
            this.typeOfAssistance = lookups.getLookup('Medications Detail', 'AssistanceType', entity.AssistanceType());
            this.medicationAssistance = lookups.getLookup('Medications Detail', 'MedicationAssistance', entity.MedicationAssistance());
            this.frequencyIsLookup = !!security.getFieldControlPropertyValue('Medications Detail', 'FREQUENCY', security.FieldControlPropertyName.LookupIDDesc);
            this.medmanagerIsLookup = !!security.getFieldControlPropertyValue('Medications Detail', 'MEDMANAGER', security.FieldControlPropertyName.LookupIDDesc);
            if (this.frequencyIsLookup) {
                this.frequency = lookups.getLookup('Medications Detail', 'FREQUENCY', entity.Packaging());
            }
            else {
                this.frequency = [];
            }
            if (this.medmanagerIsLookup) {
                this.medmanager = lookups.getLookup('Medications Detail', 'MEDMANAGER', entity.MEDMANAGER());
            }
            else {
                this.medmanager = [];
            }
            this.dosageIsText = equalsIgnoreCase(security.getFieldControlType('Medications Detail', 'DOSAGE'), 'ctlTextbox');
            if (equalsIgnoreCase(security.getFieldControlType('Medications Detail', 'MEDMANAGEMENTBY'), 'ctlWorkerSearchPopUp')) {
                this.MEDMANAGEMENTBY = lookups.workers;
            }
            this.PRESCRIBEDBY = (entity.PRESCRIBEDBY());
            this.COMMENTS = (entity.COMMENTS());
            this.Gentext1 = (entity.Gentext1());
            this.Gentext2 = (entity.Gentext2());
            this.Gentext3 = (entity.Gentext3());
            this.Gentext4 = (entity.Gentext4());
            this.MedUnit = lookups.getLookup('Medications Detail', 'MedUnit', entity.MedUnit());
            entity.MEDICATION.subscribe(function (val) {
                var validators = entity.entityType.getProperty('OTHERMEDICATION').validators;
                var existingRequiredValidator = ko.utils.arrayFirst(validators, function (v) { return v.name === 'required'; });
                if (val !== 'Other') {
                    if (existingRequiredValidator != null) {
                        validators.splice(validators.indexOf(existingRequiredValidator), 1);
                        entity.entityAspect.removeValidationError(existingRequiredValidator);
                    }
                }
                else {
                    if (existingRequiredValidator === null) {
                        validators.push(breeze.Validator.required());
                    }
                }
            });
            entity.MEDMANAGEMENTBY.subscribe(function (val) {
                var validators = entity.entityType.getProperty('MEDMANAGEMENTBY').validators;
                var existingRequiredValidator = ko.utils.arrayFirst(validators, function (v) { return v.name === 'number'; });
                if (val !== null) {
                    if (existingRequiredValidator != null) {
                        validators.splice(validators.indexOf(existingRequiredValidator), 1);
                        entity.entityAspect.removeValidationError(existingRequiredValidator);
                    }
                }
            });
            var observable = ko.observable();
        }
        Medication.prototype.dispose = function () {
            var validators = this.entity.entityType.getProperty('OTHERMEDICATION').validators;
            var existingRequiredValidator = ko.utils.arrayFirst(validators, function (v) { return v.name === 'required'; });
            if (existingRequiredValidator != null) {
                validators.splice(validators.indexOf(existingRequiredValidator), 1);
                this.entity.entityAspect.removeValidationError(existingRequiredValidator);
            }
            _super.prototype.dispose.call(this);
        };
        return Medication;
    })(viewmodels.ModalEntityViewModel);
    return Medication;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/medication-list-control',["require", "exports", 'assessments/base', 'assessments/controls/medication', 'entities/api', 'core/lookups'], function (require, exports, base, Medication, entities, lookups) {
    var MedicationListControl = (function (_super) {
        __extends(MedicationListControl, _super);
        function MedicationListControl(args) {
            _super.call(this, args, {
                entityTypeName: entities.entityTypes.Medication,
                entityCollectionPropertyName: 'Medications',
                keyPropertyName: 'MEDICATIONREVIEWID',
                entityViewModelConstructor: Medication,
                getNewEntityConfig: function () { return ({
                    ScreenScaleID: args.question.SCREENSCALEID,
                    ChapterName: '**not used**',
                    PageName: '**not used**',
                }); },
                getScaleId: function (entity) { return entity.ScreenScaleID(); }
            });
            this.showSearch = ko.observable(false);
            this.medicationReviews = ko.observableArray([]);
            if (args.question.CONTROLSCREENSCALE === "ctlMedicationDataForm") {
                var bLegands = args.question.BEGINLEGEND;
                if (bLegands != null && bLegands != "") {
                    var resultBLeg = bLegands.split("#").filter(function (arrLeg) { return arrLeg.charAt(arrLeg.length - 1) == "0"; });
                    var finRes = [];
                    var res = [];
                    resultBLeg.forEach(function (element) {
                        finRes.push(element.split("|")[1]);
                        if (element.split("|")[0] == "MEDUNIT")
                            res.push("MedUnit");
                        else
                            res.push(element.split("|")[0]);
                    });
                    this.visibleColumnsMedication = finRes;
                    this.visibleColumnsMedicationHeader = res;
                }
            }
        }
        MedicationListControl.prototype.select = function (event, selectedMedication) {
            var entity = this.args.entityManager.createChildEntity(this.args.assessment, this.info.entityCollectionPropertyName, this.info.getNewEntityConfig());
            entity.MEDICATIONREVIEWID(selectedMedication.MEDICATIONREVIEWID());
            entity.MEDICATION(selectedMedication.MEDICATION());
            entity.OTHERMEDICATION(selectedMedication.OTHERMEDICATION());
            entity.STARTDATE(selectedMedication.STARTDATE());
            entity.ENDDATE(selectedMedication.ENDDATE());
            entity.STATUS(selectedMedication.STATUS());
            entity.DOSAGE(selectedMedication.DOSAGE());
            entity.FREQUENCY(selectedMedication.FREQUENCY());
            entity.ROUTEADMIN(selectedMedication.ROUTEADMIN());
            entity.MEDMANAGER(selectedMedication.MEDMANAGER());
            entity.MedsObtained(selectedMedication.MedsObtained());
            entity.MailOrder(selectedMedication.MailOrder());
            entity.Packaging(selectedMedication.Packaging());
            entity.AssistanceType(selectedMedication.AssistanceType());
            entity.MedicationAssistance(selectedMedication.MedicationAssistance());
            entity.MEDMANAGEMENTBY(selectedMedication.MEDMANAGEMENTBY());
            entity.PRESCRIBEDBY(selectedMedication.ASPRESCRIBED());
            entity.COMMENTS(selectedMedication.COMMENTS());
            entity.Gentext1(selectedMedication.Gentext1());
            entity.Gentext2(selectedMedication.Gentext2());
            entity.Gentext3(selectedMedication.Gentext3());
            entity.Gentext4(selectedMedication.Gentext4());
            entity.MedUnit(selectedMedication.MedUnit());
            this.uncommittedEntity(entity);
            this.uncommittedEntity(null);
            this.setIsAnswered();
            this.hideSearch();
        };
        MedicationListControl.prototype.hideSearch = function () {
            this.showSearch(false);
        };
        MedicationListControl.prototype.getWorkersName = function (id) {
            var arr = lookups.workers.filter(function (x) { return x.MemberID === id; });
            if (arr.length > 0) {
                return arr[0].Description;
            }
            return '';
        };
        MedicationListControl.prototype.medicationIsOther = function (value) {
            if (value.MEDICATION() === 'Other') {
                return value.OTHERMEDICATION();
            }
            return '';
        };
        MedicationListControl.prototype.search = function () {
            var currentMedicationIDs = _.map(this.entities(), function (medication) {
                return medication.MEDICATIONREVIEWID();
            });
            var medications = this.args.entityManager.parentEntityManager.entity.MEDICATIONREVIEWs().filter(function (m) { return equalsIgnoreCase(m.ChapterName(), 'consumers'); });
            this.medicationReviews.removeAll();
            ko.utils.arrayPushAll(this.medicationReviews, _.filter(medications, function (medication) {
                return !_.contains(currentMedicationIDs, medication.MEDICATIONREVIEWID());
            }));
            this.showSearch(true);
        };
        return MedicationListControl;
    })(base.CollectionQuestionBase);
    return MedicationListControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/relation',["require", "exports", 'core/viewmodels', 'core/lookups'], function (require, exports, viewmodels, lookups) {
    var RelationViewModel = (function (_super) {
        __extends(RelationViewModel, _super);
        function RelationViewModel(entity, isAdd, isParentReadOnly) {
            var _this = this;
            _super.call(this, entity, isAdd, isParentReadOnly);
            this.tabTypes = ['Family', 'Case', 'Professional'];
            this.relationships = ko.observable([]);
            this.multiRelationships = ko.observable([]);
            this.isDetailReadOnly(isParentReadOnly);
            this.multiRelationship = ko.observableArray((this.entity.MultiRelationship() || '').split('|').filter(function (value) { return !isNullOrEmpty(value); }));
            this.multiRelationshipSubscription = this.multiRelationship.subscribe(function (newValue) { return _this.entity.MultiRelationship(newValue.join('|')); }, this);
            this.tabType = ko.computed({
                read: function () { return (_this.entity.TabType() || '').replace(' Relation', ''); },
                write: function (newValue) { return _this.entity.TabType(newValue + ' Relation'); },
                owner: this
            });
            this.tabTypeSubscription = this.entity.TabType.subscribe(this.tabTypeChanged, this);
            if (this.entity.TabType())
                this.tabTypeChanged(this.entity.TabType());
        }
        RelationViewModel.prototype.tabTypeChanged = function (newValue) {
            var relationships, tabType = newValue.replace(' Relation', ''), pageName = 'Consumer All ' + tabType + ' Relations';
            if (equalsIgnoreCase(security.getFieldControlType(pageName, 'relationship'), 'ctlRelationshipDropdownlist')) {
                relationships = lookups.relationships.filter(function (x) { return equalsIgnoreCase(x.TabType, tabType); }).map(function (x) { return x.Description; });
            }
            else {
                relationships = lookups.getLookup(pageName, 'relationship').map(function (x) { return x.Description; });
            }
            this.relationships(relationships);
            if (equalsIgnoreCase(security.getFieldControlType(pageName, 'multirelationship'), 'ctlRelationshipDropdownlist')) {
                relationships = lookups.relationships.filter(function (x) { return equalsIgnoreCase(x.TabType, tabType); }).map(function (x) { return x.Description; });
            }
            else {
                relationships = lookups.getLookup(pageName, 'multirelationship').map(function (x) { return x.Description; });
            }
            this.multiRelationships(relationships);
        };
        RelationViewModel.prototype.dispose = function () {
            this.multiRelationshipSubscription.dispose();
            this.tabType.dispose();
            this.tabTypeSubscription.dispose();
        };
        return RelationViewModel;
    })(viewmodels.ModalEntityViewModel);
    return RelationViewModel;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/relation-search',["require", "exports", 'core/viewmodels', 'entities/api', 'core/util'], function (require, exports, viewmodels, entities, util) {
    var RelationSearch = (function (_super) {
        __extends(RelationSearch, _super);
        function RelationSearch(existingRelations, add, copy) {
            _super.call(this);
            this.existingRelations = existingRelations;
            this.add = add;
            this.copy = copy;
            this.tabTypes = ['Family', 'Case', 'Professional'];
            this.tabType = ko.observable(this.tabTypes[0]);
            this.firstName = ko.observable('');
            this.lastName = ko.observable('');
            this.searchResults = ko.observable([]);
            this.enableAdd = ko.observable(false);
            this.connectionFailure = ko.observable(false);
            var queueSearch = this.queueSearch.bind(this);
            this.subscriptions = [
                this.firstName.subscribe(queueSearch),
                this.lastName.subscribe(queueSearch),
                this.tabType.subscribe(queueSearch)
            ];
        }
        RelationSearch.prototype.select = function (relation) {
            this.submit();
            this.copy(relation, this.tabType() + ' Relation');
        };
        RelationSearch.prototype.addNew = function () {
            this.submit();
            this.add(this.tabType() + ' Relation');
        };
        RelationSearch.prototype.queueSearch = function () {
            var _this = this;
            clearTimeout(this.searchTimeoutHandle);
            setTimeout(function () { return _this.search(); }, 300);
        };
        RelationSearch.prototype.search = function () {
            var _this = this;
            var that = this;
            entities.createBreezeEntityManager('Consumers').then(function (em) {
                var query = new breeze.EntityQuery().from('RelationSearch').noTracking(true).withParameters({ firstNameLike: _this.firstName(), lastNameLike: _this.lastName(), relationSearchType: _this.tabType() });
                return em.executeQuery(query);
            }).then(function (queryResult) {
                var results = queryResult.results;
                results = results.filter(function (r) { return !util.Arrays.any(_this.existingRelations, function (er) { return er.ContactID() === r.CONTACTID; }); });
                _this.searchResults(results);
                _this.connectionFailure(false);
                clearTimeout(_this.connectionFailureTimeoutHandle);
            }).fail(function (reason) {
                if (util.isConnectionFailure(reason)) {
                    _this.connectionFailure(true);
                    clearTimeout(_this.connectionFailureTimeoutHandle);
                    setTimeout(function () { return _this.connectionFailure(false); }, 5000);
                    return;
                }
                return Q.reject(reason);
            }).finally(function () { return _this.enableAdd(true); }).done();
        };
        return RelationSearch;
    })(viewmodels.ModalViewModelBase);
    return RelationSearch;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/relation-attach',["require", "exports", 'core/viewmodels', 'core/util'], function (require, exports, viewmodels, util) {
    var RelationAttach = (function (_super) {
        __extends(RelationAttach, _super);
        function RelationAttach(existingRelations, consumerRelations, copy, displaySearch) {
            _super.call(this);
            this.existingRelations = existingRelations;
            this.consumerRelations = consumerRelations;
            this.copy = copy;
            this.displaySearch = displaySearch;
            this.relations = consumerRelations.filter(function (r) { return !util.Arrays.any(existingRelations, function (er) { return er.ContactID() === r.CONTACTID(); }); });
        }
        RelationAttach.prototype.select = function (relation) {
            this.submit();
            this.copy(relation);
        };
        RelationAttach.prototype.search = function () {
            this.submit();
            this.displaySearch();
        };
        return RelationAttach;
    })(viewmodels.ModalViewModelBase);
    return RelationAttach;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/relation-control',["require", "exports", 'assessments/base', 'durandal/app', 'entities/api', 'assessments/controls/relation', 'assessments/controls/relation-search', 'assessments/controls/relation-attach'], function (require, exports, base, durandal, entities, RelationViewModel, RelationSearch, RelationAttach) {
    var RelationControl = (function (_super) {
        __extends(RelationControl, _super);
        function RelationControl(args) {
            _super.call(this, args, {
                entityTypeName: entities.entityTypes.AssessmentRelation,
                entityCollectionPropertyName: 'Relations',
                keyPropertyName: 'AssessID',
                entityViewModelConstructor: RelationViewModel,
                getNewEntityConfig: function () { return ({
                    ScreenScaleID: args.question.SCREENSCALEID,
                    ChapterName: '**not used**',
                    PageName: '**not used**',
                }); },
                getScaleId: function (entity) { return entity.ScreenScaleID(); },
                disallowMultiple: true
            });
        }
        RelationControl.prototype.addWithTabType = function (tabType) {
            this.add(this);
            this.uncommittedEntity().TabType(tabType);
        };
        RelationControl.prototype.copyConsumerRelation = function (existing) {
            var relation;
            this.add(this);
            relation = this.uncommittedEntity();
            relation.RecID(existing.RECID());
            relation.ContactID(existing.CONTACTID());
            relation.Relationship(existing.RELATIONSHIP());
            relation.FirstName(existing.FIRSTNAME());
            relation.LastName(existing.LASTNAME());
            relation.MiddleName(existing.MIDDLENAME());
            relation.Street(existing.STREET());
            relation.Street2(existing.Street2());
            relation.City(existing.CITY());
            relation.State(existing.STATE());
            relation.Zipcode(existing.ZIP());
            relation.ResCounty(existing.COUNTRY());
            relation.Phone(existing.PHONE());
            relation.WorkPhone(existing.WORKPHONE());
            relation.CellPhone(existing.CELLPHONE());
            relation.VendorID(existing.TargetVendorID());
            relation.TabType(existing.TabType());
            relation.ReadOnlyDueToWorkerOrDemographicLink(existing.ReadOnlyDueToWorkerOrDemographicLink());
            relation.Email(existing.EMAIL());
            relation.MultiRelationship(existing.Multirelationship());
        };
        RelationControl.prototype.copySearchResult = function (contact, tabType) {
            var relation;
            this.add(this);
            relation = this.uncommittedEntity();
            relation.ContactID(contact.CONTACTID);
            relation.FirstName(contact.FirstName);
            relation.LastName(contact.LastName);
            relation.MiddleName(contact.MiddleName);
            relation.Street(contact.Street);
            relation.Street2(contact.Street2);
            relation.City(contact.City);
            relation.State(contact.State);
            relation.Zipcode(contact.Zipcode);
            relation.ResCounty(contact.ResCounty);
            relation.Phone(contact.Phone);
            relation.WorkPhone(contact.WorkPhone);
            relation.CellPhone(contact.CellPhone);
            relation.VendorID(contact.VendorID);
            relation.ReadOnlyDueToWorkerOrDemographicLink(contact.ReadOnlyDueToWorkerOrDemographicLink);
            relation.Email(contact.Email);
            relation.TabType(tabType);
        };
        RelationControl.prototype.getExistingRelations = function () {
            var _this = this;
            var assessment = this.args.assessment;
            return assessment.Relations().filter(function (r) { return r.ScreenScaleID() === _this.args.question.SCREENSCALEID; });
        };
        RelationControl.prototype.search = function () {
            var existingRelations = this.getExistingRelations(), copy = this.copySearchResult.bind(this), add = this.addWithTabType.bind(this);
            durandal.showDialog(new RelationSearch(existingRelations, add, copy)).done();
        };
        RelationControl.prototype.attach = function () {
            var existingRelations = this.getExistingRelations(), consumerRelations = this.args.entityManager.parentEntityManager.entity.vw_WH_RELATEREVIEW(), copy = this.copyConsumerRelation.bind(this), search = this.search.bind(this);
            durandal.showDialog(new RelationAttach(existingRelations, consumerRelations, copy, search)).done();
        };
        return RelationControl;
    })(base.CollectionQuestionBase);
    return RelationControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/file-upload-control',["require", "exports", 'assessments/base', 'core/util'], function (require, exports, base, util) {
    var FileUploadControl = (function (_super) {
        __extends(FileUploadControl, _super);
        function FileUploadControl(args) {
            this.value = ko.observable(null);
            this.options = $.extend({ accept: ".jpg,.jpeg,.png,.doc,.docx,.txt,.pdf", multiple: true }, JSON.parse(args.question.DefaultValue || '{}'));
            _super.call(this, args);
        }
        FileUploadControl.prototype.reset = function () {
            var _this = this;
            _super.prototype.reset.call(this);
            if (this.valueSubscription) {
                this.valueSubscription.dispose();
            }
            if (this.getFiles().length > 0) {
                var existingFiles1 = this.getFiles();
                util.dmsUploadFileModel.dmsUploadFile(existingFiles1);
            }
            else {
                this.value(null);
            }
            this.valueSubscription = this.value.subscribe(function (newValue) {
                _super.prototype.setResponseValue.call(_this, newValue.length ? newValue.length.toString() : '');
                var files = _this.getFiles().filter(function (f) { return f.ScreenScaleID !== _this.args.question.SCREENSCALEID; });
                _this.setFiles(files);
                newValue.forEach(function (f) {
                    var reader = new FileReader();
                    reader.onloadend = function () {
                        var files = _this.getFiles();
                        files.push({
                            ScreenScaleID: _this.args.question.SCREENSCALEID,
                            Name: f.name,
                            ContentType: f.type || '',
                            Data: reader.result.replace(/^data:[^,]*,/, ''),
                            LastModifiedDate: moment(f.lastModifiedDate).toDate(),
                            Size: f.size
                        });
                        _this.setFiles(files);
                    };
                    reader.readAsDataURL(f);
                });
            }, this);
        };
        FileUploadControl.prototype.setFiles = function (files) {
            this.args.assessment.files(JSON.stringify(files));
        };
        FileUploadControl.prototype.getFiles = function () {
            return JSON.parse(this.args.assessment.files());
        };
        FileUploadControl.prototype.applyValueFromHistory = function (historyItem) {
        };
        return FileUploadControl;
    })(base.QuestionBase);
    return FileUploadControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/diagnosis-control',["require", "exports", 'assessments/base', 'core/util', 'core/lookups'], function (require, exports, base, util, lookups) {
    var throttleHandle = null;
    var codes = {};
    var DiagnosisControl = (function (_super) {
        __extends(DiagnosisControl, _super);
        function DiagnosisControl(args) {
            _super.call(this, args);
            if (!this.value) {
                this.value = ko.observable('');
            }
            this.padHeight = 100;
            this.setTypeaheadOptions();
        }
        DiagnosisControl.prototype.setTypeaheadOptions = function () {
            var _this = this;
            var $contentDiv = null;
            this.typeaheadOptions = {
                source: function (query, callback) {
                    clearTimeout(throttleHandle);
                    throttleHandle = setTimeout(function () { return lookups.diagnosisSearch(10, query).then(function (results) {
                        var i = results.length, result, name, names = [];
                        while (i--) {
                            result = results[i];
                            name = result.Code + ': ' + result.Description;
                            codes[name] = result;
                            names[i] = name;
                        }
                        callback(names);
                    }); }, 300);
                },
                items: 15,
                updater: function (name) {
                    _this.expected = name;
                    var lookupCode = codes[name];
                    _super.prototype.setResponseValue.call(_this, lookupCode.ID.toString(10));
                    var response = _super.prototype.getResponse.call(_this, false);
                    var assessment = response.Assessment();
                    var diag = util.Arrays.firstOrDefault(assessment.Diags(), function (x) { return x.DiagCodesID().toString(10) === response.Item(); });
                    if (!diag) {
                        response.entityAspect.entityManager.createEntity('AssessmentDiag', { AssessID: response.AssessmentID(), DiagCodesID: lookupCode.ID, Code: lookupCode.Code, Description: lookupCode.Description });
                    }
                    return name;
                },
                highlighter: function (name) {
                    var diag = codes[name];
                    return '<strong style="display: inline-block; width: 80px">' + htmlEncode(diag.Code) + '</strong>' + htmlEncode(diag.Description);
                },
                blur: function (data, event) {
                    if (_this.value() !== _this.expected) {
                        _this.value(_this.expected);
                    }
                    return true;
                },
                matcher: function (item) { return true; },
                scrollHeight: function () {
                    if ($contentDiv === null || $contentDiv.length === 0)
                        $contentDiv = $('.assessment div.form-content:first');
                    if ($contentDiv.length === 0)
                        return 0;
                    return $contentDiv[0].scrollTop;
                }
            };
        };
        DiagnosisControl.prototype.reset = function () {
            var _this = this;
            _super.prototype.reset.call(this);
            if (!this.value) {
                this.value = ko.observable('');
            }
            if (this.valueSubscription) {
                this.valueSubscription.dispose();
            }
            var response = _super.prototype.getResponse.call(this, false);
            this.expected = '';
            var diag = null;
            if (response && response.Assessment() && (diag = util.Arrays.firstOrDefault(response.Assessment().Diags(), function (x) { return x.DiagCodesID().toString(10) === response.Item(); }))) {
                this.expected = diag.Code() + ': ' + diag.Description();
            }
            this.value(this.expected);
            this.valueSubscription = this.value.subscribe(function (name) {
                if (name === '') {
                    _this.expected = '';
                    _super.prototype.setResponseValue.call(_this, '');
                }
            });
        };
        DiagnosisControl.prototype.applyValueFromHistory = function (historyItem) {
            _super.prototype.applyValueFromHistory.call(this, historyItem);
        };
        return DiagnosisControl;
    })(base.QuestionBase);
    return DiagnosisControl;
});

define('webIntakeType',["require", "exports", 'entities/api'], function (require, exports, entities) {
    exports.questionID = 'inqtype';
    function getMainReportType() {
        var types = [];
        var reportTypeMain;
        var mainEntity;
        types.push(entities.entityTypes.InquiryAssessment);
        var allinstances = entities.getInstances(types);
        var mainEntityManager = allinstances[0];
        mainEntity = mainEntityManager.entity;
        reportTypeMain = mainEntity.Responses().filter(function (i) { return i.QuestionID() === exports.questionID; });
        return reportTypeMain[0].Item();
    }
    exports.getMainReportType = getMainReportType;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/participant',["require", "exports", 'entities/api', 'core/messageBox', 'assessments/screen-repo', 'core/viewmodels', 'plugins/dialog', 'webIntakeType'], function (require, exports, entities, messageBox, screenDesignRepo, viewmodels, dialog, inquiryType) {
    var Participant = (function (_super) {
        __extends(Participant, _super);
        function Participant(entity, isAdd, isParentReadOnly, screenId, parentEntityManager, sessionEntityManager) {
            if (screenId === void 0) { screenId = ""; }
            if (parentEntityManager === void 0) { parentEntityManager = null; }
            if (sessionEntityManager === void 0) { sessionEntityManager = null; }
            _super.call(this, entity, isAdd, isParentReadOnly);
            this.screenId = screenId;
            this.parentEntityManager = parentEntityManager;
            this.sessionEntityManager = sessionEntityManager;
            this.ScreenId = screenId;
            this.setAppValueForCurrentParticipant(screenId);
            this.ParentEntityManager = parentEntityManager;
            this.SessionEntityManager = sessionEntityManager;
            this.SessionEntityManager.parentEntityManager = this.parentEntityManager;
            this.ParticipantViewModel = screenDesignRepo.getAssessmentViewModel();
            this.ParticipantViewModel.entityManager = this.sessionEntityManager;
            if (!isAdd) {
                this.tempJson = this.sessionEntityManager.exportEntities();
                var temp = JSON.parse(this.tempJson);
                this.respones = temp.entityGroupMap["InquiryAssessmentResponse:#Server.Domain"].entities;
                var reportTypeParticipant = this.sessionEntityManager.entity.Responses().filter(function (q) { return q.QuestionID() === inquiryType.questionID; });
                if (reportTypeParticipant.length > 0) {
                    reportTypeParticipant[0].Item(inquiryType.getMainReportType());
                }
            }
        }
        Participant.prototype.validate = function () {
            if (!this.ParticipantViewModel.validate()) {
                app.busyIndicator.setReady();
                return false;
            }
            return true;
        };
        Participant.prototype.setAppValueForCurrentParticipant = function (screenId) {
            app.participantControlAcitve = true;
            app.participantScreenID = screenId;
        };
        Participant.prototype.cancel = function () {
            var _this = this;
            if (!this.isAdd) {
                var tempJsonOnCancel = this.sessionEntityManager.exportEntities();
                if (this.tempJson == tempJsonOnCancel) {
                    dialog.close(this, false);
                    return;
                }
            }
            sessionStorage.setItem('msgBoxSetFocus', '1');
            messageBox.show('apsWebIntake.cancelTitle', 'apsWebIntake.cancelMessage', messageBox.buttons.okCancel).then(function (result) {
                if (result === messageBox.ok) {
                    if (_this.isAdd) {
                        entities.removeLocalRootInstance(_this.sessionEntityManager.entity.AssessmentID(), entities.entityTypes.InquiryAssessment);
                        dialog.close(_this, false);
                    }
                    else {
                        _this.respones.forEach(function (r) {
                            var response = _this.sessionEntityManager.entity.Responses().filter(function (i) { return i.ResponseID() === r.ResponseID; });
                            if (response != null) {
                                var hasProperty = r.hasOwnProperty('Item');
                                var item = r.Item;
                                if (hasProperty) {
                                    response[0].Item(item);
                                }
                                else {
                                    response[0].Item(null);
                                }
                            }
                        });
                        dialog.close(_this, false);
                    }
                }
                if (result === messageBox.cancel) {
                    $('[participant-btn-cancel]').focus();
                }
            });
        };
        return Participant;
    })(viewmodels.ModalEntityViewModel);
    return Participant;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/participant-list-control',["require", "exports", 'assessments/base', 'entities/api', 'durandal/app', 'assessments/controls/participant'], function (require, exports, base, entities, durandal, Participant) {
    var ParticipantListControl = (function (_super) {
        __extends(ParticipantListControl, _super);
        function ParticipantListControl(args) {
            var _this = this;
            _super.call(this, args);
            this.participantEntities = ko.observableArray([]);
            this.predefinedBooleanValues = ko.observableArray([]);
            this.getScreenId(args.question.BEGINLEGEND);
            this.setPredefinedBooleanValues();
            this.setHeaders(args.question.BEGINLEGEND);
            this.isSkipped = ko.observable(!args.question.Show);
            this.isSkipped.subscribe(function (isSkipped) {
                if (isSkipped) {
                    _this.deleteAllInstances();
                }
            });
            this.currentMaxNoOfRecordsAllowed = args.question.MaxNoOfRecordsAllowed;
            this.maxNoOfRecordsAllowed = args.question.MaxNoOfRecordsAllowed;
        }
        ParticipantListControl.prototype.add = function (data, event) {
            var _this = this;
            if (this.currentMaxNoOfRecordsAllowed != null) {
                if (this.currentMaxNoOfRecordsAllowed <= 0) {
                    return;
                }
            }
            entities.createInstance(entities.entityTypes.INQUIRY).then(function (em) {
                _this.parentEntityManager = em;
                return entities.createInstance(entities.entityTypes.InquiryAssessment, {});
            }).then(function (em) {
                _this.sessionEntityManager = em;
                var dialogViewModel = new Participant(_this.sessionEntityManager.entity, true, false, _this.screenId, _this.parentEntityManager, _this.sessionEntityManager);
                durandal.showDialog(dialogViewModel).then(function (dialogResult) {
                    if (dialogResult) {
                        if (_this.currentMaxNoOfRecordsAllowed != null) {
                            _this.currentMaxNoOfRecordsAllowed = _this.currentMaxNoOfRecordsAllowed - 1;
                            if (_this.currentMaxNoOfRecordsAllowed <= 0) {
                                event.currentTarget.title = 'You have entered the maximum number of records allowed for this field.';
                                event.currentTarget.style.backgroundColor = "#ccc";
                            }
                        }
                        _this.sessionEntityManager.entity.Status(_this.screenId);
                        _this.sessionEntityManager.entity.VisibleResponses = ko.observableArray([]);
                        _this.visibleQuestonIds.forEach(function (questionId) {
                            var responseFromEntity = _this.sessionEntityManager.entity.Responses().filter(function (i) { return i.QuestionID() === questionId; });
                            if (responseFromEntity[0] != null) {
                                if (_this.predefinedBooleanValues.indexOf(questionId) >= 0) {
                                    responseFromEntity[0].IsBoolean = ko.observable(true);
                                }
                                else {
                                    responseFromEntity[0].IsBoolean = ko.observable(false);
                                }
                                _this.sessionEntityManager.entity.VisibleResponses.push(responseFromEntity[0]);
                            }
                            else {
                                _this.sessionEntityManager.entity.VisibleResponses.push({
                                    Item: ko.observable(''),
                                    IsBoolean: ko.observable(false)
                                });
                            }
                        });
                        if (dialogViewModel.validate()) {
                            _this.participantEntities.push(_this.sessionEntityManager.entity);
                            _this.setIsAnswered();
                        }
                    }
                    _this.setFocusToNewBtn();
                });
            });
        };
        ParticipantListControl.prototype.open = function (entity) {
            var _this = this;
            entities.getInstance(entities.entityTypes.InquiryAssessment, entity.AssessmentID()).then(function (em) {
                _this.sessionEntityManager = em;
                _this.sessionEntityManager.parentEntityManager = em.parentEntityManager;
                var dialogViewModel = new Participant(_this.sessionEntityManager.entity, false, false, _this.screenId, _this.parentEntityManager, _this.sessionEntityManager);
                durandal.showDialog(dialogViewModel).then(function (dialogResult) {
                    if (dialogResult) {
                    }
                    _this.setFocusToNewBtn();
                });
            });
        };
        ParticipantListControl.prototype.remove = function (entity, event) {
            if (this.currentMaxNoOfRecordsAllowed != null) {
                this.currentMaxNoOfRecordsAllowed = this.currentMaxNoOfRecordsAllowed + 1;
                var addBtn = this.view.getElementsByTagName('button')['addparticipant'];
                if (addBtn != null && addBtn !== 'undefined') {
                    addBtn.title = '';
                    addBtn.style.backgroundColor = '';
                }
            }
            this.participantEntities.remove(entity);
            entities.removeLocalRootInstance(entity.AssessmentID(), entities.entityTypes.InquiryAssessment);
            this.setIsAnswered();
        };
        ParticipantListControl.prototype.deleteAllInstances = function () {
            if (this.currentMaxNoOfRecordsAllowed != null) {
                this.currentMaxNoOfRecordsAllowed = this.maxNoOfRecordsAllowed;
                var addBtn = this.view.getElementsByTagName('button')['addparticipant'];
                if (addBtn != null && addBtn !== 'undefined') {
                    addBtn.title = '';
                    addBtn.style.backgroundColor = '';
                }
            }
            this.participantEntities.removeAll();
            this.setIsAnswered();
        };
        ParticipantListControl.prototype.getScreenId = function (legend) {
            var firstSplitPart = legend.split('$')[0];
            if (firstSplitPart != null) {
                this.screenId = firstSplitPart.split('|')[1];
            }
        };
        ParticipantListControl.prototype.setPredefinedBooleanValues = function () {
            this.predefinedBooleanValues.push('allegationprima');
            this.predefinedBooleanValues.push('apprimary');
            this.predefinedBooleanValues.push('avprimary');
        };
        ParticipantListControl.prototype.setHeaders = function (bLegands) {
            if (bLegands != null && bLegands != "") {
                var secondPartWithoutScrenID = bLegands.split("$")[1];
                var resultBLeg = secondPartWithoutScrenID.split("#").filter(function (arrLeg) { return arrLeg.charAt(arrLeg.length - 1) == "0"; });
                var finRes = [];
                var res = [];
                resultBLeg.forEach(function (element, index) {
                    finRes.push(element.split("|")[1]);
                    res.push(element.split("|")[0]);
                });
            }
            this.visibleColumnsParticipant = finRes;
            this.visibleQuestonIds = res;
        };
        ParticipantListControl.prototype.setIsAnswered = function () {
            this.isAnswered(this.participantEntities().length > 0);
            this.isAnswered.notifySubscribers();
        };
        ParticipantListControl.prototype.setFocusToNewBtn = function () {
            var addBtn = this.view.getElementsByTagName('button')['addparticipant'];
            if (addBtn != null && addBtn !== 'undefined') {
                addBtn.focus();
            }
        };
        return ParticipantListControl;
    })(base.QuestionBase);
    return ParticipantListControl;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/copy-address-from-list',["require", "exports", 'entities/api', 'assessments/base', 'plugins/dialog'], function (require, exports, entities, base, dialog) {
    var CopyAddressFromList = (function (_super) {
        __extends(CopyAddressFromList, _super);
        function CopyAddressFromList(args, questionViewModels) {
            var _this = this;
            _super.call(this, args);
            this.participantsAddressData = ko.observableArray([]);
            this.addressSelected = function () {
                var Street, Street2;
                var City, State, County, ZipCode;
                var HomePhone, CellPhone, WorkPhone;
                var copyAddressFromQuestionID = _this.self.currentQuestionID;
                switch (copyAddressFromQuestionID) {
                    case "rcopyaddress":
                        Street = 'rstreet';
                        Street2 = 'rsteet2';
                        City = 'rcity';
                        State = 'rstate';
                        County = 'rcounty';
                        ZipCode = 'rzipcode';
                        HomePhone = 'rhphone';
                        CellPhone = 'rcphone';
                        WorkPhone = 'rwphone';
                        break;
                    case "avcopyaddress":
                        Street = 'avstreet';
                        Street2 = 'avstreet2';
                        City = 'avcity';
                        State = 'avstate';
                        County = 'avcounty';
                        ZipCode = 'avzipcode';
                        HomePhone = 'avhomephone';
                        CellPhone = 'avcellphone';
                        WorkPhone = 'avworkphone';
                        break;
                    case "apcopyaddress":
                        Street = 'apstreet';
                        Street2 = 'apstreet2';
                        City = 'apcity';
                        State = 'apstate';
                        County = 'apcounty';
                        ZipCode = 'apzipcode';
                        HomePhone = 'aphomephone';
                        CellPhone = 'apcellphone';
                        WorkPhone = 'apworkphone';
                        break;
                    case "opcopyaddress":
                        Street = 'opstreet';
                        Street2 = 'opstreet2';
                        City = 'opcity';
                        State = 'opstate';
                        County = 'opcounty';
                        ZipCode = 'opzipcode';
                        HomePhone = 'ophomephone';
                        CellPhone = 'opcellphone';
                        WorkPhone = 'opworkphone';
                        break;
                    case "incicopyaddress":
                        Street = 'incidentstreet';
                        Street2 = 'incidentstreet2';
                        City = 'incidentcity';
                        State = 'incidentstate';
                        County = 'incidentcounty';
                        ZipCode = 'incidentzipcode';
                        break;
                    default:
                        return '';
                        break;
                }
                var placeSection = null;
                for (var item in _this.self.qvm) {
                    if (_this.addressSelected.arguments.length > 0) {
                        _this.setAddressField(item, Street, 'Street', _this.addressSelected.arguments[0]);
                        _this.setAddressField(item, Street2, 'Street2', _this.addressSelected.arguments[0]);
                        _this.setAddressField(item, City, 'City', _this.addressSelected.arguments[0]);
                        _this.setAddressField(item, State, 'State', _this.addressSelected.arguments[0]);
                        _this.setAddressField(item, County, 'County', _this.addressSelected.arguments[0]);
                        _this.setAddressField(item, ZipCode, 'ZipCode', _this.addressSelected.arguments[0]);
                        _this.setAddressField(item, HomePhone, 'HomePhone', _this.addressSelected.arguments[0]);
                        _this.setAddressField(item, CellPhone, 'CellPhone', _this.addressSelected.arguments[0]);
                        _this.setAddressField(item, WorkPhone, 'WorkPhone', _this.addressSelected.arguments[0]);
                        if (_this.self.qvm[item].args.question.QUESTIONID === City) {
                            _this.StorePlaceControlValue(_this.self.qvm[item].args.question.PLACEFIELD, _this.self.qvm[item].args.question.PLACESECTION, _this.addressSelected.arguments[0].City);
                            placeSection = _this.self.qvm[item].args.question.PLACESECTION;
                        }
                        if (_this.self.qvm[item].args.question.QUESTIONID === State) {
                            _this.StorePlaceControlValue(_this.self.qvm[item].args.question.PLACEFIELD, _this.self.qvm[item].args.question.PLACESECTION, _this.addressSelected.arguments[0].State);
                            placeSection = _this.self.qvm[item].args.question.PLACESECTION;
                        }
                        if (_this.self.qvm[item].args.question.QUESTIONID === County) {
                            _this.StorePlaceControlValue(_this.self.qvm[item].args.question.PLACEFIELD, _this.self.qvm[item].args.question.PLACESECTION, _this.addressSelected.arguments[0].County);
                            placeSection = _this.self.qvm[item].args.question.PLACESECTION;
                        }
                        if (_this.self.qvm[item].args.question.QUESTIONID === ZipCode) {
                            _this.StorePlaceControlValue(_this.self.qvm[item].args.question.PLACEFIELD, _this.self.qvm[item].args.question.PLACESECTION, _this.addressSelected.arguments[0].ZipCode);
                            placeSection = _this.self.qvm[item].args.question.PLACESECTION;
                        }
                    }
                }
                if (placeSection != null || placeSection != undefined) {
                    sessionStorage.setItem('PlaceAllowOverride_' + placeSection + '_' + _this.self.args.assessment.AssessmentID(), 'true');
                }
                dialog.close(_this, false);
                return;
            };
            this.self = this;
            this.qvm = questionViewModels;
            this.currentQuestionID = args.question.QUESTIONID;
            var data = this.GetAddressData();
            this.participantsAddressData = ko.observableArray(data);
        }
        CopyAddressFromList.prototype.GetAddressData = function () {
            var _this = this;
            var types = [];
            types.push(entities.entityTypes.InquiryAssessment);
            var allinstances = entities.getInstances(types);
            var addressData = [];
            var entityManager;
            allinstances.forEach(function (manager, index) {
                entityManager = manager;
                var questionData = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rcopyaddress') || (e.QuestionID() === 'avcopyaddress') || (e.QuestionID() === 'apcopyaddress') || (e.QuestionID() === 'opcopyaddress') || (e.QuestionID() === 'incicopyaddress'); });
                if (questionData != null && questionData != undefined && questionData != '') {
                    var i = 0;
                    var firstName, lastName, streetAddress, streetAddress2;
                    var city, state, county, zipCode;
                    var homePhone, cellPhone, workPhone;
                    var participantType;
                    for (i = 0; i < questionData.length; i++) {
                        participantType = '';
                        firstName = [];
                        lastName = [];
                        streetAddress = [];
                        streetAddress2 = [];
                        city = [];
                        state = [];
                        county = [];
                        zipCode = [];
                        homePhone = [];
                        cellPhone = [];
                        workPhone = [];
                        participantType = _this.findParticipantType(questionData[i]);
                        if (questionData[i].QuestionID() != 'incicopyaddress') {
                            firstName = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rfirstname') || (e.QuestionID() === 'avfirstname') || (e.QuestionID() === 'apfirstname') || (e.QuestionID() === 'opfirstname'); });
                            lastName = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rlastname') || (e.QuestionID() === 'avlastname') || (e.QuestionID() === 'aplastname') || (e.QuestionID() === 'oplastname'); });
                            streetAddress = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rstreet') || (e.QuestionID() === 'avstreet') || (e.QuestionID() === 'apstreet') || (e.QuestionID() === 'opstreet'); });
                            streetAddress2 = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rsteet2') || (e.QuestionID() === 'avstreet2') || (e.QuestionID() === 'apstreet2') || (e.QuestionID() === 'opstreet2'); });
                            city = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rcity') || (e.QuestionID() === 'avcity') || (e.QuestionID() === 'apcity') || (e.QuestionID() === 'opcity'); });
                            state = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rstate') || (e.QuestionID() === 'avstate') || (e.QuestionID() === 'apstate') || (e.QuestionID() === 'opstate'); });
                            county = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rcounty') || (e.QuestionID() === 'avcounty') || (e.QuestionID() === 'apcounty') || (e.QuestionID() === 'opcounty'); });
                            zipCode = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rzipcode') || (e.QuestionID() === 'avzipcode') || (e.QuestionID() === 'apzipcode') || (e.QuestionID() === 'opzipcode'); });
                            homePhone = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rhphone') || (e.QuestionID() === 'avhomephone') || (e.QuestionID() === 'aphomephone') || (e.QuestionID() === 'ophomephone'); });
                            cellPhone = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rcphone') || (e.QuestionID() === 'avcellphone') || (e.QuestionID() === 'apcellphone') || (e.QuestionID() === 'opcellphone'); });
                            workPhone = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'rwphone') || (e.QuestionID() === 'avworkphone') || (e.QuestionID() === 'apworkphone') || (e.QuestionID() === 'opworkphone'); });
                        }
                        else {
                            streetAddress = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'incidentstreet'); });
                            streetAddress2 = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'incidentstreet2'); });
                            city = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'incidentcity'); });
                            state = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'incidentstate'); });
                            county = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'incidentcounty'); });
                            zipCode = entityManager.entity.Responses().filter(function (e) { return (e.QuestionID() === 'incidentzipcode'); });
                        }
                        var data = {
                            "FirstName": _this.getFieldData(firstName),
                            "LastName": _this.getFieldData(lastName),
                            "ParticipantType": participantType,
                            "Street": _this.getFieldData(streetAddress),
                            "Street2": _this.getFieldData(streetAddress2),
                            "City": _this.getFieldData(city),
                            "State": _this.getFieldData(state),
                            "County": _this.getFieldData(county),
                            "ZipCode": _this.getFieldData(zipCode),
                            "HomePhone": _this.getFieldData(homePhone),
                            "CellPhone": _this.getFieldData(cellPhone),
                            "WorkPhone": _this.getFieldData(workPhone),
                        };
                        if (data.Street != null || data.Street2 != null || data.City != null || data.State != null || data.County != null || data.ZipCode != null || data.HomePhone != null || data.CellPhone != null || data.WorkPhone != null) {
                            addressData.push(data);
                        }
                    }
                }
            });
            return addressData;
        };
        CopyAddressFromList.prototype.getFieldData = function (field) {
            if (field != null || field != undefined || field != '') {
                if (field.length > 0) {
                    if (field[0].Item() != "") {
                        return field[0].Item();
                    }
                }
            }
            return null;
        };
        CopyAddressFromList.prototype.findParticipantType = function (questionData) {
            var storageData = sessionStorage.getItem("copyAddressDefaultValue_" + questionData.AssessmentID());
            if (storageData != null && storageData != undefined && storageData != '') {
                var qdata = storageData.split('~');
                var j;
                for (j = 0; j < qdata.length; j++) {
                    if (qdata[j].length > 1) {
                        if (qdata[j].split(',')[1] == questionData.QuestionID()) {
                            if (qdata[j].split(',')[0] == null || qdata[j].split(',')[0] == undefined || qdata[j].split(',')[0] == '') {
                                return this.getParticipantType(questionData.QuestionID());
                            }
                            return qdata[j].split(',')[0];
                        }
                    }
                }
            }
            return '';
        };
        CopyAddressFromList.prototype.getParticipantType = function (questionId) {
            switch (questionId) {
                case "rcopyaddress":
                    return 'Reporter';
                    break;
                case "avcopyaddress":
                    return 'Alleged Victim';
                    break;
                case "apcopyaddress":
                    return 'Alleged Perpetrator';
                    break;
                case "opcopyaddress":
                    return 'Other';
                    break;
                case "incicopyaddress":
                    return 'Incident';
                    break;
                default:
                    return '';
                    break;
            }
        };
        CopyAddressFromList.prototype.setAddressField = function (item, questionID, dataFieldName, data) {
            if (this.self.qvm[item].args.question.QUESTIONID === questionID) {
                this.self.qvm[item].value(data[dataFieldName]);
            }
        };
        CopyAddressFromList.prototype.StorePlaceControlValue = function (placeFied, placeSection, val) {
            var placeControlStorageKey = 'placeControlValues';
            var placeControlValues = JSON.parse(sessionStorage.getItem(placeControlStorageKey));
            var key = placeFied + "-" + placeSection;
            if (placeControlValues == null)
                placeControlValues = [];
            if (placeControlValues.filter(function (obj) {
                return obj.id == key;
            }).length <= 0)
                placeControlValues.push({ id: key, value: val });
            else
                placeControlValues.filter(function (obj) {
                    return obj.id == key;
                })[0].value = val;
            sessionStorage.setItem(placeControlStorageKey, JSON.stringify(placeControlValues));
            sessionStorage.removeItem('onLoadFocus' + '-' + placeFied + '-' + placeSection);
        };
        CopyAddressFromList.prototype.cancel = function () {
            dialog.close(this, false);
            return;
        };
        return CopyAddressFromList;
    })(base.QuestionBase);
    return CopyAddressFromList;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/controls/copy-address-from',["require", "exports", 'assessments/base', 'assessments/controls/copy-address-from-list', 'durandal/app'], function (require, exports, base, CopyAddressList, durandal) {
    var CopyAddressFromControl = (function (_super) {
        __extends(CopyAddressFromControl, _super);
        function CopyAddressFromControl(args) {
            _super.call(this, args);
            this.onCopyAddressFromClick = (function (data, event) {
                durandal.showDialog(new CopyAddressList(args, data.questionViewModels)).done();
            }).bind(this);
        }
        return CopyAddressFromControl;
    })(base.QuestionBase);
    return CopyAddressFromControl;
});

define('assessments/controls/control-maker',["require", "exports", 'assessments/scales', 'assessments/controls/string-control', 'assessments/controls/date-control', 'assessments/controls/decimal-control', 'assessments/controls/multiple-choice-control', 'assessments/controls/single-choice-control', 'assessments/controls/ssn-control', 'assessments/controls/indicator-control', 'assessments/controls/numeric-indicator-control', 'assessments/controls/calculated-control', 'assessments/controls/rawscore-control', 'assessments/controls/header-control', 'assessments/controls/instructional-control', 'assessments/controls/medication-list-control', 'assessments/controls/relation-control', 'assessments/controls/file-upload-control', 'assessments/controls/diagnosis-control', 'assessments/controls/participant-list-control', 'assessments/controls/copy-address-from'], function (require, exports, scales, StringControl, DateControl, DecimalControl, MultipleChoiceControl, SingleChoiceControl, SsnControl, IndicatorControl, NumericIndicatorControl, CalculatedControl, RawScoreControl, HeaderControl, InstructionalControl, MedicationListControl, RelationControl, FileUploadControl, DiagnosisControl, ParticipantListControl, CopyAddressFromControl) {
    var constructors = {};
    constructors[scales.keys.ctlDropDownList] = SingleChoiceControl;
    constructors[scales.keys.ctlDropDownListWithNeeds] = SingleChoiceControl;
    constructors[scales.keys.ctlRadioButtonList] = SingleChoiceControl;
    constructors[scales.keys.ctlCheckbox] = SingleChoiceControl;
    constructors[scales.keys.ctlCheckboxWithNeeds] = SingleChoiceControl;
    constructors[scales.keys.ctlLikert] = SingleChoiceControl;
    constructors[scales.keys.ctlRichText] = StringControl;
    constructors[scales.keys.ctlTextbox] = StringControl;
    constructors[scales.keys.ctlPhoneTextbox] = StringControl;
    constructors[scales.keys.ctlLookupDropDown] = StringControl;
    constructors[scales.keys.ctlEmailTextbox] = StringControl;
    constructors[scales.keys.ctlTimeControl] = StringControl;
    constructors[scales.keys.ctlMultiSelectionListBox] = MultipleChoiceControl;
    constructors[scales.keys.ctlMultiSelectionListBoxWithNeeds] = MultipleChoiceControl;
    constructors[scales.keys.ctlDateCalendar] = DateControl;
    constructors[scales.keys.ctlNumericTextbox] = DecimalControl;
    constructors[scales.keys.ctlCurrencyTextbox] = DecimalControl;
    constructors[scales.keys.ctlDecimalTextbox] = DecimalControl;
    constructors[scales.keys.ctlSSNTextbox] = SsnControl;
    constructors[scales.keys.ctlIndicatorField] = IndicatorControl;
    constructors[scales.keys.ctlNumericIndicatorField] = NumericIndicatorControl;
    constructors[scales.keys.ctlCalculatedField] = CalculatedControl;
    constructors[scales.keys.ctlRawScoreField] = RawScoreControl;
    constructors[scales.keys.ctlCommentIndicatorField] = NumericIndicatorControl;
    constructors[scales.keys.ctlDecimalIndicatorField] = NumericIndicatorControl;
    constructors[scales.keys.ctlDateIndicatorField] = IndicatorControl;
    constructors[scales.keys.ctlHeader] = HeaderControl;
    constructors[scales.keys.ctlInstructionalText] = InstructionalControl;
    constructors[scales.keys.ctlMedicationDataForm] = MedicationListControl;
    constructors[scales.keys.ctlRelationDataForm] = RelationControl;
    constructors[scales.keys.ctlFiles] = FileUploadControl;
    constructors[scales.keys.ctlDiagCodeSearchLookUp] = DiagnosisControl;
    constructors[scales.keys.ctlScreenDesignGridFieldControl] = ParticipantListControl;
    constructors[scales.keys.ctlCopyAddressFrom] = CopyAddressFromControl;
    var ControlMaker = (function () {
        function ControlMaker() {
        }
        ControlMaker.create = function (type, args) {
            if (type === scales.keys.ctlDemographicDataLookup) {
                switch (args.question.DemographicLookupField) {
                    case scales.DemographicField.SSN:
                        return new SsnControl(args);
                    case scales.DemographicField.ADDRESSTYPE:
                    case scales.DemographicField.ETHNICITYLOOKUP:
                    case scales.DemographicField.GENDER:
                    case scales.DemographicField.GENDERIDENTITY:
                    case scales.DemographicField.CURMARSTATUS:
                    case scales.DemographicField.REFERRALSOURCE:
                    case scales.DemographicField.RESIDENCETYPE:
                    case scales.DemographicField.SALUTATION:
                    case scales.DemographicField.Suffix:
                    case scales.DemographicField.VeteranStatus:
                    case scales.DemographicField.StudentWithADisability:
                    case scales.DemographicField.IndividualWithADisability:
                    case scales.DemographicField.PrimaryDisabilityType:
                    case scales.DemographicField.PrimaryDisabilitySource:
                    case scales.DemographicField.SecondaryDisabilityType:
                    case scales.DemographicField.SecondaryDisabilitySource:
                    case scales.DemographicField.SignificanceOfDisability:
                    case scales.DemographicField.DegreeOfVisualImpairment:
                    case scales.DemographicField.MajorCauseOfVisualImpairment:
                    case scales.DemographicField.OtherAgeRelatedImpairments:
                    case scales.DemographicField.PLANGUAGE:
                    case scales.DemographicField.BelowPovertyLevel:
                        return new SingleChoiceControl(args);
                    case scales.DemographicField.RACE:
                        return !isNullOrEmpty(JSON.parse(localStorage.getItem("GroupSetupConfigRace"))) ? (JSON.parse(localStorage.getItem("GroupSetupConfigRace")) == 'ctlLookupDropDown' ? new SingleChoiceControl(args) : new MultipleChoiceControl(args)) : null;
                    case scales.DemographicField.DOB:
                        return new DateControl(args);
                    case scales.DemographicField.MultiRace:
                        return new MultipleChoiceControl(args);
                    case scales.DemographicField.RESCOUNTY:
                    case scales.DemographicField.STATE:
                    case scales.DemographicField.CITIZENSHIP:
                    default:
                        return new StringControl(args);
                }
            }
            if (type === scales.keys.ctlEnrollmentDataLookup) {
                switch (args.question.EnrollmentLookupField) {
                    case scales.EnrollmentField.ReferralSource:
                        return new SingleChoiceControl(args);
                    case scales.EnrollmentField.ADMITDATE:
                    case scales.EnrollmentField.DateOfEligibilityDetermination:
                    case scales.EnrollmentField.EligibilityDeterminationExtension:
                        return new DateControl(args);
                    case scales.EnrollmentField.MedicalInsuranceCoverageAtApplication:
                    case scales.EnrollmentField.MonthlyPublicSupportAtApplication:
                        return new MultipleChoiceControl(args);
                    default:
                        return new StringControl(args);
                }
            }
            if (typeof this.constrs[type] !== "function") {
                return new StringControl(args);
            }
            return new this.constrs[type](args);
        };
        ControlMaker.constrs = constructors;
        return ControlMaker;
    })();
    return ControlMaker;
});

define('assessments/chain-manager',["require", "exports", 'core/util', 'assessments/scales', 'assessments/controls/multiple-choice-control', 'assessments/controls/single-choice-control'], function (require, exports, util, scales, MultipleChoiceControl, SingleChoiceControl) {
    var interestingScaleTypes = [scales.keys.ctlDropDownList, scales.keys.ctlDropDownListWithNeeds, scales.keys.ctlMultiSelectionListBox, scales.keys.ctlMultiSelectionListBoxWithNeeds];
    function toKey(screenScaleId) {
        return 'q' + screenScaleId.toString(10);
    }
    var ChainManager = (function () {
        function ChainManager(sessionManager, screenDesign, questionViewModels) {
            this.sessionManager = sessionManager;
            this.screenDesign = screenDesign;
            this.questionViewModels = questionViewModels;
            this.isEntityChangeCausingChainEval = false;
            this.allowedChoices = {};
        }
        ChainManager.prototype.initialize = function () {
            var _this = this;
            var chains = this.screenDesign.Chains;
            chains = chains.filter(function (c) { return !!_this.questionViewModels[toKey(c.ScreenScaleIDPrimary)] && !!_this.questionViewModels[toKey(c.ScreenScaleIDSecondary)]; });
            chains = chains.filter(function (c) { return interestingScaleTypes.indexOf(_this.questionViewModels[toKey(c.ScreenScaleIDPrimary)].args.question.CONTROLSCREENSCALE) !== -1; });
            chains = chains.filter(function (c) { return interestingScaleTypes.indexOf(_this.questionViewModels[toKey(c.ScreenScaleIDSecondary)].args.question.CONTROLSCREENSCALE) !== -1; });
            this.primaries = util.Arrays.toIndex(util.Arrays.groupBy(chains, function (c) { return toKey(c.ScreenScaleIDPrimary); }), function (g) { return g.key.toString(); }, function (g) { return g; });
            this.secondaries = util.Arrays.toIndex(util.Arrays.groupBy(chains, function (c) { return toKey(c.ScreenScaleIDSecondary); }), function (g) { return g.key.toString(); }, function (g) { return g; });
            this.subscribeToResponseChanges();
            this.filterAllQuestions();
        };
        ChainManager.prototype.subscribeToResponseChanges = function () {
            this.entityChangedSubscriptionToken = this.sessionManager.entityChanged.subscribe(this.onEntityChanged.bind(this));
        };
        ChainManager.prototype.onEntityChanged = function (data) {
            var _this = this;
            if (data.entityAction !== breeze.EntityAction.PropertyChange || !data.entity || !data.entity['ScaleID'])
                return;
            var screenScaleId = data.entity.ScaleID();
            var chains = this.primaries[toKey(screenScaleId)];
            if (!chains) {
                return;
            }
            clearTimeout(this.chainEvalTimeoutHandle);
            if (this.isEntityChangeCausingChainEval) {
                if (this.chainEvalEntityChangeCount >= 1000) {
                    this.isEntityChangeCausingChainEval = false;
                    alert('Error: Lookup chain loop detected.  Lookup chain evaluation has been cancelled.');
                    return;
                }
            }
            else {
                this.isEntityChangeCausingChainEval = true;
                this.chainEvalEntityChangeCount = 0;
            }
            clearTimeout(this.chainEvalTimeoutHandle);
            this.chainEvalTimeoutHandle = setTimeout(function () { return _this.isEntityChangeCausingChainEval = false; }, 50);
            var secondaryScreenScaleIds = chains.map(function (c) { return c.ScreenScaleIDSecondary; }).filter(function (value, index, self) { return self.indexOf(value) === index; });
            secondaryScreenScaleIds.forEach(function (screenScaleId) { return _this.filterQuestionChoices(screenScaleId); });
        };
        ChainManager.prototype.filterAllQuestions = function () {
            var _this = this;
            this.screenDesign.SCREENQUESTIONS.forEach(function (q) { return _this.filterQuestionChoices(q.SCREENSCALEID); });
        };
        ChainManager.prototype.filterQuestionChoices = function (screenScaleId) {
            var chains = this.secondaries[toKey(screenScaleId)];
            if (!chains) {
                return;
            }
            var primary = this.questionViewModels[toKey(chains[0].ScreenScaleIDPrimary)];
            if (!primary) {
                return;
            }
            var secondary = this.questionViewModels[toKey(screenScaleId)];
            if (!secondary) {
                return;
            }
            var selectedPrimaryScreenLookupIds;
            if (primary instanceof MultipleChoiceControl) {
                selectedPrimaryScreenLookupIds = primary.value().map(function (x) { return parseInt(x, 10); });
            }
            else if (primary instanceof SingleChoiceControl) {
                selectedPrimaryScreenLookupIds = [parseInt(primary.value(), 10)];
            }
            else {
                throw new Error('unexpected primary control type');
            }
            selectedPrimaryScreenLookupIds = selectedPrimaryScreenLookupIds.filter(function (x) { return !isNaN(x); });
            var allowedSecondaryScreenLookupIds = chains.filter(function (c) { return selectedPrimaryScreenLookupIds.indexOf(c.LookupIDPrimary) !== -1; }).map(function (c) { return c.LookupIDSecondary; }).filter(function (value, index, self) { return self.indexOf(value) === index; });
            this.allowedChoices[screenScaleId] = allowedSecondaryScreenLookupIds.join(',');
            if (secondary instanceof MultipleChoiceControl) {
                secondary.showHideChainedChoices(allowedSecondaryScreenLookupIds);
            }
            else if (secondary instanceof SingleChoiceControl) {
                secondary.showHideChainedChoices(allowedSecondaryScreenLookupIds);
            }
            else {
                throw new Error('unexpected secondary control type');
            }
        };
        ChainManager.prototype.dispose = function () {
            this.sessionManager.entityChanged.unsubscribe(this.entityChangedSubscriptionToken);
            this.primaries = null;
            this.secondaries = null;
            this.screenDesign = null;
            this.questionViewModels = null;
        };
        return ChainManager;
    })();
    return ChainManager;
});

define('assessments/web-intake-action-buttons',["require", "exports", 'core/util'], function (require, exports, util) {
    var submitScreenScale = 'SubmitButtonVisibility';
    var cancelScreenScale = 'CancelButtonVisibility';
    var printScreenScale = 'PrintButtonVisibility';
    var show = 'show';
    var WebIntakeActionButtons = (function () {
        function WebIntakeActionButtons(sessionManager, screenDesign, isReadOnly) {
            this.sessionManager = sessionManager;
            this.screenDesign = screenDesign;
            this.showSubmit = ko.observable(true);
            this.showDraft = ko.observable(true);
            this.showCancel = ko.observable(true);
            this.showPrint = ko.observable(true);
            if (isReadOnly) {
                this.showSubmit(false);
                this.showDraft(false);
                this.showCancel(false);
                return;
            }
            var requiresObservation = false;
            var question = util.Arrays.firstOrDefault(screenDesign.SCREENQUESTIONS, function (q) { return equalsIgnoreCase(q.SCREENSCALE, submitScreenScale); });
            if (question) {
                this.submitScreenScaleId = question.SCREENSCALEID;
                requiresObservation = true;
                this.updateVisibility(this.showSubmit, this.submitScreenScaleId);
                this.updateVisibility(this.showDraft, this.submitScreenScaleId);
            }
            question = util.Arrays.firstOrDefault(screenDesign.SCREENQUESTIONS, function (q) { return equalsIgnoreCase(q.SCREENSCALE, cancelScreenScale); });
            if (question) {
                this.cancelScreenScaleId = question.SCREENSCALEID;
                requiresObservation = true;
                this.updateVisibility(this.showCancel, this.cancelScreenScaleId);
            }
            question = util.Arrays.firstOrDefault(screenDesign.SCREENQUESTIONS, function (q) { return equalsIgnoreCase(q.SCREENSCALE, printScreenScale); });
            if (question) {
                this.printScreenScaleId = question.SCREENSCALEID;
                requiresObservation = true;
                this.updateVisibility(this.showPrint, this.printScreenScaleId);
            }
            if (!requiresObservation) {
                return;
            }
            this.entityChangedSubscriptionToken = this.sessionManager.entityChanged.subscribe(this.onEntityChanged.bind(this));
        }
        WebIntakeActionButtons.prototype.updateVisibility = function (observable, screenScaleId) {
            var indicatorResponse = util.Arrays.firstOrDefault(this.sessionManager.entity.Responses(), function (r) { return r.ScaleID() === screenScaleId; });
            observable(indicatorResponse && equalsIgnoreCase(indicatorResponse.Item(), show));
        };
        WebIntakeActionButtons.prototype.onEntityChanged = function (data) {
            if (data.entityAction !== breeze.EntityAction.PropertyChange || !data.entity || !data.entity['ScaleID'])
                return;
            var screenScaleId = data.entity.ScaleID();
            if (screenScaleId === this.submitScreenScaleId) {
                this.updateVisibility(this.showSubmit, this.submitScreenScaleId);
                this.updateVisibility(this.showDraft, this.submitScreenScaleId);
            }
            if (screenScaleId === this.cancelScreenScaleId) {
                this.updateVisibility(this.showCancel, this.cancelScreenScaleId);
            }
            if (screenScaleId === this.printScreenScaleId) {
                this.updateVisibility(this.showPrint, this.printScreenScaleId);
            }
        };
        WebIntakeActionButtons.prototype.dispose = function () {
            this.sessionManager.entityChanged.unsubscribe(this.entityChangedSubscriptionToken);
            this.screenDesign = null;
            this.sessionManager = null;
            this.showCancel = null;
            this.showPrint = null;
            this.showSubmit = null;
        };
        return WebIntakeActionButtons;
    })();
    return WebIntakeActionButtons;
});

define('unsupportedBrowser',["require", "exports"], function (require, exports) {
    exports.browser = ko.observable('');
    exports.version = ko.observable('');
    exports.yourBrowserIsNotSupportedMessage = ko.observable('');
    function compositionComplete(child, parent, settings) {
        $('.h-built-with-html5').delay(3000).fadeOut(2000);
        $('.form-group', child).on('focusin', function (e) { return $(e.target).closest('.form-group').addClass('focusin'); }).on('focusout', function (e) { return $(e.target).closest('.form-group').removeClass('focusin'); });
    }
    exports.compositionComplete = compositionComplete;
    function isBrowserAllowed() {
        var userAgent = navigator.userAgent.toLowerCase();
        var matches = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        var temp = [];
        var canUseTheApp = false, msie = /msie (\d+\.?(?:\d+)?)/i.exec(userAgent);
        if (msie && msie.length > 0) {
            this.browser('ie');
            this.version(+msie[1]);
        }
        else if (/trident/i.test(userAgent)) {
            temp = /\brv[ :]+(\d+)/g.exec(userAgent) || [];
            this.browser('ie');
            this.version(temp[1] || '');
        }
        else if (matches[1] === 'chrome') {
            this.browser('chrome');
            this.version(matches[2] ? matches[2] : navigator.appVersion);
            temp = userAgent.match(/\bopr\/(\d+)/);
            if (temp !== null) {
                this.browser('opera');
                this.version(temp[1]);
            }
        }
        else {
            this.browser(matches[2] ? matches[1] : navigator.appName);
            this.browser(this.browser().toLocaleLowerCase());
            this.version(matches[2] ? matches[2] : navigator.appVersion);
        }
        if (userAgent.indexOf('android') > -1) {
            if (this.browser() === 'chrome' && Number(this.version()) >= 38)
                canUseTheApp = true;
            else if (this.browser() === 'firefox')
                canUseTheApp = true;
            else
                canUseTheApp = false;
        }
        else if (userAgent.indexOf('iemobile') > -1) {
            canUseTheApp = false;
        }
        else if (userAgent.indexOf('blackberry') > -1) {
            canUseTheApp = false;
        }
        else if (userAgent.indexOf('iphone') > -1) {
            if (window.screen.height >= (1136 / 2))
                canUseTheApp = true;
            else
                canUseTheApp = false;
        }
        else if (userAgent.indexOf('ipad') > -1) {
            canUseTheApp = true;
        }
        else {
            if (this.browser() === 'chrome' && Number(this.version()) >= 38)
                canUseTheApp = true;
            else if (this.browser() === 'firefox' || this.browser() === 'safari')
                canUseTheApp = true;
            else if (this.browser() === 'ie' && Number(this.version()) >= 10)
                canUseTheApp = true;
            else
                canUseTheApp = false;
        }
        this.yourBrowserIsNotSupportedMessage($.i18n.t('common.yourBrowserIsNotSupported').format(this.browser(), this.version()));
        return canUseTheApp;
    }
    exports.isBrowserAllowed = isBrowserAllowed;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/assessment',["require", "exports", 'assessments/assessment-base', 'assessments/screen-repo', 'core/util', 'entities/api', 'assessments/base', 'assessments/find', 'assessments/hist', 'core/viewmodels', 'entities/snapshot', 'assessments/indicators-manager', 'assessments/conditions-manager', 'assessments/question-focus-history', 'assessments/scales', 'assessments/controls/string-control', 'assessments/controls/date-control', 'assessments/controls/decimal-control', 'assessments/controls/multiple-choice-control', 'assessments/controls/single-choice-control', 'assessments/controls/ssn-control', 'assessments/controls/indicator-control', 'assessments/controls/control-maker', 'plugins/router', 'core/messageBox', 'assessments/chain-manager', 'assessments/web-intake-action-buttons', 'core/lookups', 'webIntakeType', 'unsupportedBrowser'], function (require, exports, AssessmentBase, screenDesignRepository, util, entities, base, find, hist, viewmodels, Snapshot, IndicatorsManager, ConditionsManager, QuestionFocusHistory, scales, StringControl, DateControl, DecimalControl, MultipleChoiceControl, SingleChoiceControl, SsnControl, IndicatorControl, ControlMaker, durandalRouter, messageBox, ChainManager, WebIntakeActionButtons, lookups, inquiryType, browserCompat) {
    var Assessment = (function (_super) {
        __extends(Assessment, _super);
        function Assessment() {
            _super.call(this);
            this.questionViewModels = {};
            this.typeAheadText = '';
            this.clearTypeAheadTimeoutHandle = -1;
            this.currentFormGroup = null;
            this.currentQuestionViewModel = null;
            this.narrative = ko.observable(false);
            this.editSession = ko.observable(false);
            this.properties = ko.observable(false);
            this.help = ko.observable(true);
            this.rejectedChangesSubscription = 0;
            this.controlConstructors = {
                StringControl: StringControl,
                DateControl: DateControl,
                DecimalControl: DecimalControl,
                MultipleChoiceControl: MultipleChoiceControl,
                SingleChoiceControl: SingleChoiceControl,
                SsnControl: SsnControl,
                IndicatorControl: IndicatorControl,
            };
            this.isReadOnlyField = {};
            this.disposed = false;
            this.entityChangedThrottles = {};
            this.questionFocusHistory = new QuestionFocusHistory(this.focusQuestion.bind(this));
            this.workersLookup = lookups.workers;
        }
        Assessment.prototype.createCommands = function () {
            _super.prototype.createCommands.call(this);
            var Command = viewmodels.Command;
            this.commands.add('focusFindQuestion', new Command(this.focusFindQuestion.bind(this)));
            this.commands.add('showHelp', new Command(this.showHelp.bind(this)));
            this.commands.add('focusSectionList', new Command(this.focusSectionList.bind(this)));
            this.commands.add('toggleNarrative', new Command(this.toggleNarrative.bind(this)));
            this.commands.add('toggleHistory', new Command(this.toggleHistory.bind(this)));
            this.commands.add('toggleHelp', new Command(this.toggleHelp.bind(this)));
            this.commands.add('toggleProperties', new Command(this.toggleProperties.bind(this)));
            this.commands.add('goBack', new Command(this.questionFocusHistory.goBack.bind(this.questionFocusHistory), this.questionFocusHistory.canGoBack));
            this.commands.add('goForward', new Command(this.questionFocusHistory.goForward.bind(this.questionFocusHistory), this.questionFocusHistory.canGoForward));
            this.commands.add('nextUnansweredQuestion', new Command(this.gotoNextUnanswered.bind(this, false)));
            this.commands.add('previousUnansweredQuestion', new Command(this.gotoNextUnanswered.bind(this, true)));
            this.commands.add('nextRequiredQuestion', new Command(this.gotoNextRequired.bind(this, false)));
            this.commands.add('previousRequiredQuestion', new Command(this.gotoNextRequired.bind(this, true)));
            this.commands.add('editAssessmentProperties', new Command(this.toggleEditSession.bind(this)));
            this.commands.add('submit', new Command(this.submitEditSession.bind(this)));
            this.commands.add('cancel', new Command(this.cancelEditSession.bind(this)));
        };
        Assessment.prototype.reverseStatus = function () {
            var fragment = location.hash;
            this.entity.Status('Pending');
            this.saveAndClose().then(function () { return setTimeout(function () { return durandalRouter.navigate(fragment); }, 100); });
        };
        Assessment.prototype.afterSave = function () {
            var _this = this;
            var fragment = location.hash;
            if (!this.isReadOnly() && !this.isClosing && security.likeComplete(this.entity.Status())) {
                setTimeout(function () { return _this.close().then(function () { return setTimeout(function () { return durandalRouter.navigate(fragment); }, 100); }); }, 100);
            }
        };
        Assessment.prototype.beforeFinishActivate = function () {
            var _this = this;
            this.rejectedChangesSubscription = this.entityManager.rejectedChanges.subscribe(function () {
                setTimeout(function () {
                    if (_this.disposed) {
                        return;
                    }
                    _this.resetQuestionViewModels();
                }, 100);
            });
            this.entityManager['changeTracker'] = new entities.ChangeTracker(this.entityManager);
            return _super.prototype.beforeFinishActivate.call(this).then(function () {
                if (app.webIntake) {
                    if (app.participantControlAcitve) {
                        return screenDesignRepository.getScreenDesignFromServerByScreenId(app.participantScreenID);
                    }
                    else {
                        if (WebIntakeSettings.SecondaryScreenDesignID != 0) {
                            return Q.all([screenDesignRepository.getScreenDesignFromServer(WebIntakeSettings.ScreenDesignID), screenDesignRepository.getScreenDesignFromServer(WebIntakeSettings.SecondaryScreenDesignID)]).then(function (screenDesigns) {
                                var primary = screenDesigns[0], secondary = screenDesigns[1];
                                if (WebIntakeSettings.ReverseScreenDesigns) {
                                    primary.SCREENQUESTIONS.forEach(function (q) { return q.SCREENSORTORDER += 1000000; });
                                }
                                else {
                                    secondary.SCREENQUESTIONS.forEach(function (q) { return q.SCREENSORTORDER += 1000000; });
                                }
                                primary.SCREENQUESTIONS = primary.SCREENQUESTIONS.concat(secondary.SCREENQUESTIONS);
                                primary.SCREENQUESTIONS.forEach(function (q) {
                                    if (WebIntakeSettings.HiddenScaleIds.indexOf(q.SCREENSCALEID) !== -1) {
                                        q.Show = 0;
                                    }
                                });
                                return primary;
                            });
                        }
                        else {
                            return screenDesignRepository.getScreenDesign(WebIntakeSettings.ScreenDesignID);
                        }
                    }
                }
                else {
                    if (screenDesignRepository.isInPackage('ConsumerAssessments', _this.entity.ScreenDesignID())) {
                        return screenDesignRepository.getScreenDesign(_this.entity.ScreenDesignID());
                    }
                    messageBox.show('screenDesignNotInPackage.title', 'screenDesignNotInPackage.message', messageBox.buttons.okOnly, [_this.entity.ScreenDesignID().toString(10)]).done();
                    return Q.reject(app.activationCancelledException);
                }
            }).then(function (screenDesign) {
                if (app.webIntake || app.consumerModule) {
                    _this.webIntakeActionButtons = new WebIntakeActionButtons(_this.entityManager, screenDesign, _this.isReadOnly());
                }
                screenDesign.SCREENQUESTIONS = screenDesign.SCREENQUESTIONS.filter(function (x) { return !(x.CONTROLSCREENSCALE === scales.keys.ctlHeader && x.HEADERCOLOR === x.FONTCOLOR && !isNullOrEmpty(x.HEADERCOLOR)); });
                _this.screenDesign = screenDesign;
                _this.selectedScreenDesign(util.Arrays.firstOrDefault(_this.screenDesigns, function (s) { return s.SCREENDESIGNID === screenDesign.SCREENDESIGNID; }));
                screenDesign.SCREENQUESTIONS = screenDesign.SCREENQUESTIONS.filter(function (q) { return q.ACTIVE !== 0; });
                _this.indicatorsManager = new IndicatorsManager(_this.entityManager, screenDesign);
                _this.conditionsManager = new ConditionsManager(_this.entityManager, screenDesign);
                _this.chainManager = new ChainManager(_this.entityManager, screenDesign, _this.questionViewModels);
                _this.findQuestion = new find.FindQuestion(screenDesign);
                _this.responseHistory = new hist.ResponseHistory(_this.entity.OwnerID(), _this.entity.AssessmentID(), _this.isReadOnly);
                _this.questions = screenDesign.SCREENQUESTIONS.sort(function (a, b) { return a.SCREENSORTORDER - b.SCREENSORTORDER; });
                var storeInSession = screenDesign.SCREENQUESTIONS.filter(function (x) { return x.CONTROLSCREENSCALE === scales.keys.ctlDateCalendar; });
                localStorage.setItem("sqQuestionspre", JSON.stringify(storeInSession));
                var sDesign = security.getScreenDesignHeaders('ConsumerAssessments');
                _this.screenDesignIsReadOnly = ((!util.Arrays.any(sDesign, function (s) { return s.SCREENDESIGNID === screenDesign.SCREENDESIGNID; })) && !app.webIntake);
                var storeInSessionForMedication = screenDesign.SCREENQUESTIONS.filter(function (x) { return x.CONTROLSCREENSCALE === scales.keys.ctlMedicationDataForm; });
                localStorage.setItem("sqQuestionspreForMedication", JSON.stringify(storeInSessionForMedication));
                if (app.participantControlAcitve) {
                    var reportTypeParticipant = screenDesign.SCREENQUESTIONS.filter(function (q) { return q.QUESTIONID === inquiryType.questionID; });
                    if (reportTypeParticipant.length > 0) {
                        reportTypeParticipant[0].DefaultValue = inquiryType.getMainReportType();
                    }
                }
            });
        };
        Assessment.prototype.getQuestionByScaleId = function (scaleId) {
            return this.questionViewModels['q' + scaleId.toString(10)].args.question;
        };
        Assessment.prototype.fillStrResponse = function (scaleId, value) {
            var question = this.getQuestionByScaleId(scaleId);
            if (question) {
                var qvm = this.questionViewModels['q' + question.SCREENSCALEID.toString()];
                qvm.value(value);
            }
        };
        Assessment.prototype.beforeSave = function () {
            var ids = this.screenDesign.SCREENQUESTIONS.filter(function (x) { return x.CONTROLSCREENSCALE === scales.keys.ctlMedicationDataForm; }).map(function (x) { return x.SCREENSCALEID; }), i = ids.length, scaleId, vm, value, response;
            while (i--) {
                scaleId = ids[i];
                vm = this.questionViewModels['q' + scaleId];
                value = this.entity.Medications().filter(function (m) { return m.ScreenScaleID() === scaleId && m.MEDICATIONREVIEWID() > 0; }).map(function (m) { return m.MEDICATIONREVIEWID(); }).join('|');
                response = vm.getResponse(true);
                response.Item(value);
            }
            ids = this.screenDesign.SCREENQUESTIONS.filter(function (x) { return x.CONTROLSCREENSCALE === scales.keys.ctlRelationDataForm; }).map(function (x) { return x.SCREENSCALEID; });
            i = ids.length;
            while (i--) {
                scaleId = ids[i];
                vm = this.questionViewModels['q' + scaleId];
                value = this.entity.Relations().filter(function (r) { return r.ScreenScaleID() === scaleId && r.RecID() > 0; }).map(function (r) { return r.RecID(); }).join('|');
                response = vm.getResponse(true);
                response.Item(value);
            }
            return Q.resolve(null);
        };
        Assessment.prototype.scrollToError = function (validationError) {
            if (!validationError.context || !validationError.context.scaleId)
                return;
            var question = this.getQuestionByScaleId(validationError.context.scaleId);
            if (question) {
                var questionElement = $("#q" + question.SCREENSCALEID.toString());
                this.scrollElementIntoView(questionElement, $('.form-content'), true);
                this.focusQuestion(question, true);
            }
        };
        Assessment.prototype.validate = function () {
            if (this.entity.Status() === 'Draft') {
                return true;
            }
            for (var item in this.questionViewModels) {
                this.questionViewModels[item].hasError(false);
            }
            var isBaseValid = _super.prototype.validate.call(this);
            return isBaseValid && this.validateDataEntryRules();
        };
        Assessment.prototype.validateDataEntryRules = function (scaleId) {
            var dataEntryErrors = this.validateRequiredFields().concat(this.validateBusinessRules()), validationError, i, question, correctedErrors;
            if (!scaleId) {
                for (i = 0; i < dataEntryErrors.length; i++) {
                    validationError = dataEntryErrors[i];
                    if (!validationError.context.scaleId)
                        continue;
                    question = this.getQuestionByScaleId(validationError.context.scaleId);
                    if (question) {
                        this.questionViewModels['q' + question.SCREENSCALEID.toString()].hasError(true);
                    }
                    if (this.validationErrors.indexOf(validationError) === -1) {
                        this.validationErrors.push(validationError);
                    }
                }
            }
            correctedErrors = this.validationErrors().filter(function (v) { return v.context && v.context.scaleId && !util.Arrays.any(dataEntryErrors, function (x) { return x.context.scaleId === v.context.scaleId; }); });
            for (i = 0; i < correctedErrors.length; i++) {
                validationError = correctedErrors[i];
                question = this.getQuestionByScaleId(validationError.context.scaleId);
                if (question) {
                    this.questionViewModels['q' + question.SCREENSCALEID.toString()].hasError(false);
                }
                this.validationErrors.splice(this.validationErrors.indexOf(validationError), 1);
            }
            return dataEntryErrors.length === 0;
        };
        Assessment.prototype.validateRequiredFields = function () {
            var question, i, qvm, validationErrors = [];
            for (i = 0; i < this.questions.length; i++) {
                question = this.questions[i];
                if (question.CONTROLSCREENSCALE === scales.keys.ctlIndicatorField || question.CONTROLSCREENSCALE === scales.keys.ctlLineSpace || question.CONTROLSCREENSCALE === scales.keys.ctlHeader || question.CONTROLSCREENSCALE === scales.keys.ctlInstructionalText) {
                    continue;
                }
                qvm = this.questionViewModels['q' + question.SCREENSCALEID.toString()];
                if (qvm.isRequired() && !(qvm.isAnswered() || qvm.isSkipped())) {
                    validationErrors.push({ context: { scaleId: question.SCREENSCALEID, type: 'required' }, errorMessage: '"' + question.SCREENSCALE + '" is required.' });
                }
            }
            return validationErrors;
        };
        Assessment.prototype.validateBusinessRules = function () {
            if (this.entity.Status() === 'Draft') {
                return [];
            }
            var question, i, participantIndex, validationErrors = [];
            var mainReportType = null;
            if (app.webIntake) {
                if (this.screenDesign.SCREENQUESTIONS.filter(function (q) { return q.QUESTIONID === inquiryType.questionID; }).length > 0) {
                    mainReportType = inquiryType.getMainReportType();
                }
            }
            for (i = 0; i < this.questions.length; i++) {
                question = this.questions[i];
                if (question.CONTROLSCREENSCALE === scales.keys.ctlPhoneTextbox) {
                    var qvm = this.questionViewModels['q' + question.SCREENSCALEID.toString()];
                    if (qvm.isAnswered() && !/^[1-9]?\([1-9]\d\d\)/.test(qvm.value())) {
                        validationErrors.push({ context: { scaleId: question.SCREENSCALEID, type: 'required' }, errorMessage: 'Area code is invalid in "' + question.SCREENSCALE + '".' });
                    }
                }
                if (question.CONTROLSCREENSCALE === scales.keys.ctlScreenDesignGridFieldControl && app.webIntake) {
                    var participantList = this.questionViewModels['q' + question.SCREENSCALEID.toString()].participantEntities();
                    for (participantIndex = 0; participantIndex < participantList.length; participantIndex++) {
                        var responsesData = participantList[participantIndex].Responses();
                        var reportTypeParticipant = responsesData.filter(function (q) { return q.QuestionID() === inquiryType.questionID && q.Item() != mainReportType; });
                        if (reportTypeParticipant.length > 0) {
                            var firstname = '', lastname = '';
                            responsesData.forEach(function (q) {
                                if ((q.QuestionID() === 'apfirstname' && q.isAnswered()) || (q.QuestionID() === 'avfirstname' && q.isAnswered()) || (q.QuestionID() === 'opfirstname' && q.isAnswered()))
                                    firstname = q.Item();
                                else if ((q.QuestionID() === 'aplastname' && q.isAnswered()) || (q.QuestionID() === 'avlastname' && q.isAnswered()) || (q.QuestionID() === 'oplastname' && q.isAnswered()))
                                    lastname = q.Item();
                            });
                            if (firstname !== '' || lastname !== '') {
                                validationErrors.push({ context: { scaleId: question.SCREENSCALEID, type: 'reporttype' }, errorMessage: firstname + ' ' + lastname });
                                continue;
                            }
                            var data = responsesData.filter(function (q) { return q.QuestionID() === 'allegationtype' && q.isAnswered(); });
                            if (data.length > 0) {
                                validationErrors.push({ context: { scaleId: question.SCREENSCALEID, type: 'reporttype' }, errorMessage: data[0].Item() });
                                continue;
                            }
                            validationErrors.push({ context: { scaleId: question.SCREENSCALEID, type: 'reporttype' }, errorMessage: '' });
                        }
                    }
                }
                if (question.CONTROLSCREENSCALE === scales.keys.ctlPlacesControl) {
                    var currentQuestion = this.questionViewModels['q' + question.SCREENSCALEID.toString()];
                    if (currentQuestion != null && currentQuestion != undefined) {
                        if (currentQuestion.hasError() == true)
                            validationErrors.push({ context: { scaleId: question.SCREENSCALEID, type: 'required' }, errorMessage: 'Invalid entry for "' + question.PLACEFIELD + '".' });
                        var onLoadFocus = sessionStorage.getItem('onLoadFocus' + '-' + question.PLACEFIELD + '-' + question.PLACESECTION);
                        if (onLoadFocus != null) {
                            var placeAllowOverride = sessionStorage.getItem('PlaceAllowOverride_' + question.PLACESECTION + '_' + this.entity.AssessmentID());
                            if (placeAllowOverride === null || placeAllowOverride === undefined) {
                                placeAllowOverride = false;
                            }
                            if (!placeAllowOverride) {
                                var qValue = currentQuestion['value']();
                                if (qValue != null)
                                    validationErrors.push({ context: { scaleId: question.SCREENSCALEID, type: 'required' }, errorMessage: 'Invalid entry for "' + question.PLACEFIELD + '".' });
                            }
                        }
                    }
                }
                if (question.CONTROLSCREENSCALE === scales.keys.ctlFiles) {
                    var fileUploadQuestion = this.questionViewModels['q' + question.SCREENSCALEID.toString()];
                    var listFiles = fileUploadQuestion.value();
                    var isvalidfilename = false;
                    if (listFiles != null && listFiles != undefined && listFiles.length > 0) {
                        for (var iFileIndex = 0; iFileIndex < listFiles.length; iFileIndex++) {
                            var iFileExt = listFiles[iFileIndex].name.split('.');
                            if (iFileExt.length === 0 || fileUploadQuestion.options.accept.indexOf(iFileExt[iFileExt.length - 1]) === -1) {
                                validationErrors.push({ context: { scaleId: this.questions[i].SCREENSCALEID, type: 'required' }, errorMessage: listFiles[iFileIndex].name + ' File extension is not supported.' });
                            }
                            isvalidfilename = util.isValidFileName(listFiles[iFileIndex].name);
                            if (!isvalidfilename) {
                                validationErrors.push({ context: { scaleId: this.questions[i].SCREENSCALEID, type: 'required' }, errorMessage: listFiles[iFileIndex].name + ' Attached files may have only letters, numbers, hyphens, underscores, and spaces in the name. Please review your attachments and try again. ' });
                            }
                            if ((listFiles[iFileIndex].size > 15728640) === true) {
                                validationErrors.push({ context: { scaleId: this.questions[i].SCREENSCALEID, type: 'required' }, errorMessage: listFiles[iFileIndex].name + '  This file exceeds the allowed file size limit (15 megabytes). ' });
                            }
                        }
                    }
                }
            }
            return validationErrors;
        };
        Assessment.prototype.afterEntityChanged = function (data) {
            var _this = this;
            var scaleId, handleIndex, handle;
            if (data.entity['ScaleID']) {
                scaleId = data.entity['ScaleID']();
                handleIndex = 'q' + scaleId.toString();
                handle = this.entityChangedThrottles[handleIndex];
                if (handle !== undefined) {
                    clearTimeout(handle);
                    delete this.entityChangedThrottles[handle];
                }
                this.entityChangedThrottles[handleIndex] = setTimeout(function () { return _this.validateDataEntryRules(scaleId); }, 10);
            }
        };
        Assessment.prototype.beforeClose = function () {
            return Q.resolve(null);
        };
        Assessment.prototype.resetQuestionViewModels = function () {
            var question, qvm;
            for (var i = 0; i < this.questions.length; i++) {
                question = this.questions[i];
                if (question.CONTROLSCREENSCALE === scales.keys.ctlIndicatorField || question.CONTROLSCREENSCALE === scales.keys.ctlLineSpace) {
                    continue;
                }
                qvm = this.questionViewModels['q' + question.SCREENSCALEID.toString()];
                qvm.reset();
            }
            this.indicatorsManager.reset();
        };
        Assessment.prototype.showHelp = function (qvm) {
            return;
        };
        Assessment.prototype.hideChoice = function (scaleId, screenLookupId) {
            if (!app.participantControlAcitve) {
                return false;
            }
            if (this.chainManager.allowedChoices[scaleId] === "") {
                return true;
            }
            if (this.chainManager.allowedChoices[scaleId] !== undefined) {
                var alChoices = this.chainManager.allowedChoices[scaleId].split(',');
                return alChoices.indexOf(screenLookupId.toString()) > -1 ? false : true;
            }
            else
                return false;
        };
        Assessment.prototype.allowedChoices = function (scaleId) {
            return this.chainManager.allowedChoices[scaleId];
        };
        Assessment.prototype.getQuestionViewModel = function (question) {
            var key = 'q' + question.SCREENSCALEID.toString();
            if (this.questionViewModels.hasOwnProperty(key)) {
                return this.questionViewModels[key];
            }
            var qArgs = new base.QuestionActivationArgs(question, this.entity, this.isReadOnly(), this.entityManager, this.fillStrResponse.bind(this));
            this.questionViewModels[key] = ControlMaker.create(question.CONTROLSCREENSCALE, qArgs);
            if (this.questionViewModels[key] instanceof base.IndicatorBase) {
                this.indicatorsManager.addIndicatorViewModel(this.questionViewModels[key]);
            }
            this.conditionsManager.addFieldViewModel(this.questionViewModels[key]);
            return this.questionViewModels[key];
        };
        Assessment.prototype.compositionComplete = function (child, parent, settings) {
            var _this = this;
            _super.prototype.compositionComplete.call(this, child, parent, settings);
            this.setFormReadOnly(child);
            var intervalHandle = setInterval(function () {
                if ($('.content .form-content', child).length === 0)
                    return;
                clearInterval(intervalHandle);
                _this.compositionReallyComplete(child, parent, settings);
            }, 10);
        };
        Assessment.prototype.compositionReallyComplete = function (child, parent, settings) {
            this.chainManager.initialize();
            if (this.entityManager.hasChanges())
                this.indicatorsManager.calculateAllIndicators();
            var me = this;
            this.conditionsManager.applyAllConditions();
            this.setFormReadOnly(child);
            var $content = $('.form-content', child);
            $content.scrollspy({ target: '.nav-tree', offset: 10 });
            var previousDimensions = { width: $content[0].scrollWidth, height: $content[0].scrollHeight };
            this.scrollspyRefreshInterval = setInterval(function () {
                var newDimensions = { width: $content[0].scrollWidth, height: $content[0].scrollHeight };
                if (newDimensions.width - previousDimensions.width === 0 && newDimensions.height - previousDimensions.height === 0) {
                    return;
                }
                previousDimensions = newDimensions;
                $content.scrollspy('refresh');
                $content[0].scrollTop = $content[0].scrollTop + 1;
                $content[0].scrollTop = $content[0].scrollTop - 1;
            }, 1000);
            $('.tree.nav.sidenav li > a', child).on('click', function (event) {
                event.preventDefault();
                me.scrollElementIntoView($(event.target.hash, child), $('.form-content', child), true);
            });
            $('.tree.nav.sidenav li', child).on('activate.bs.scrollspy', function (event) {
                me.scrollNavItemIntoView(event);
            });
            setTimeout(function () {
                if (browserCompat.browser() === 'ie') {
                    $(child).find('input,textarea,select').filter(':visible:first').focus();
                }
                else {
                    $(child).find('input,textarea,select').filter(':visible:enabled').filter(':visible:first').focus();
                }
            }, 150);
            var clearFocusTimeout = -1, clearFocus = function () {
                clearTimeout(clearFocusTimeout);
                me.clearTypeAhead();
                if (me.currentFormGroup && me.currentQuestionViewModel) {
                    me.currentFormGroup.removeClass('focusin');
                }
            }, $formGroups = $('.form-content form > .form-group', child), isFirstFocus = true;
            $formGroups.on('focusin', function (focusEvent) {
                clearTimeout(clearFocusTimeout);
                var formGroup = $(focusEvent.target).closest('.form-group')[0];
                if (!isFirstFocus && me.currentFormGroup !== null && me.currentFormGroup[0].id === formGroup.id) {
                    me.currentFormGroup.addClass('focusin');
                    if (!app.tabletOrPhone) {
                        me.scrollFormGroupIntoView(focusEvent);
                    }
                    return;
                }
                isFirstFocus = false;
                clearFocus();
                me.currentFormGroup = $(formGroup);
                var key = formGroup.id;
                me.currentQuestionViewModel = me.questionViewModels[key];
                me.currentFormGroup.addClass('focusin');
                if (!app.tabletOrPhone) {
                    me.scrollFormGroupIntoView(focusEvent);
                }
                me.responseHistory.question(me.currentQuestionViewModel);
                me.questionFocusHistory.pushQuestion(me.currentQuestionViewModel.args.question);
                me.currentQuestionViewModel.initiallySkipped(false);
                me.currentFormGroup.prevUntil(':not(.initially-skipped:header)').slice(0).removeClass('initially-skipped');
            }).on('focusout', function (focusEvent) {
                clearTimeout(clearFocusTimeout);
                clearFocusTimeout = setTimeout(clearFocus, 350);
            }).on('keydown.assessments.ui.assessment', function (event) {
                me.handleFormGroupInputKeyDown(event);
            });
            if (this.questions.length === 0) {
                this.toggleNarrative();
            }
            else {
                this.currentFormGroup = $formGroups.first();
                this.currentQuestionViewModel = me.questionViewModels[this.currentFormGroup[0].id];
            }
            $formGroups.find('input[type=text],input[type=number],input[type=tel]').on('focus.assessments.ui.assessment', function (focusEvent) {
                $(focusEvent.target).one('mouseup.assessments.ui.assessment', function (mouseUpEvent) {
                    mouseUpEvent.preventDefault();
                }).select();
            });
            var $sidebar = $('.list-container', child);
            $sidebar.on('touchmove', function (event) { return $sidebar[0].offsetHeight < $sidebar[0].scrollHeight; });
            $('.files-clear-btn', child).click(function (event) {
                $(event.target).parents('.input-group').find(':text').trigger($.Event('keyup', { keyCode: 46 }));
            });
            var varExistingFiles = util.dmsUploadFileModel.dmsUploadFile();
            if (varExistingFiles != null && varExistingFiles.length > 0) {
                var completeFileName = "";
                for (var i = 0; i < varExistingFiles.length; i++) {
                    if (this.currentFormGroup.context.querySelectorAll("[id=input-" + varExistingFiles[i].ScreenScaleID + "]").length > 0) {
                        var ctrlDiv = this.currentFormGroup.context.querySelectorAll("[id=input-" + varExistingFiles[i].ScreenScaleID + "]")[0];
                        var ctrlInput = ctrlDiv.getElementsByTagName("input")[1];
                        completeFileName += '"' + varExistingFiles[i].Name + '",';
                        if (i == varExistingFiles.length - 1) {
                            completeFileName = completeFileName.replace(/,\s*$/, "");
                            ctrlInput.value = completeFileName;
                        }
                        util.dmsUploadFileModel.dmsUploadFile(null);
                    }
                }
            }
        };
        Assessment.prototype.scrollFormGroupIntoView = function (focusEvent) {
            var $formGroup = $(focusEvent.target).closest('.form-group');
            if (app.webIntake) {
                var el = $formGroup[0];
                var rect = el.getBoundingClientRect();
                if (rect.height > (window.innerHeight || document.documentElement.clientHeight)) {
                    return;
                }
                if (rect.top < 0 || rect.bottom > (window.innerHeight || document.documentElement.clientHeight)) {
                    window.scrollTo(0, $formGroup.offset().top);
                }
                return;
            }
            this.scrollElementIntoView($formGroup, $('.form-content:first', this.view), false, this.currentQuestionViewModel.padHeight);
        };
        Assessment.prototype.scrollNavItemIntoView = function (activateEvent) {
            var $li = $(activateEvent.target);
            this.scrollElementIntoView($li, $(activateEvent.target.parentNode.parentNode));
        };
        Assessment.prototype.scrollElementIntoView = function ($element, $container, toTop, padHeight) {
            var containerTop = $container.scrollTop(), containerBottom = containerTop + $container.outerHeight();
            padHeight = padHeight || 0;
            var elementTop = $element.offset().top - ($container.offset() || { top: 0 }).top + containerTop, elementBottom = elementTop + $element.outerHeight() + padHeight;
            if ($element.outerHeight() > $container.outerHeight()) {
                return;
            }
            if (elementBottom > containerBottom || elementTop < containerTop || toTop) {
                $container.scrollTop(elementTop);
            }
        };
        Assessment.prototype.handleFormGroupInputKeyDown = function (keyDownEvent) {
            if (this.currentQuestionViewModel === null)
                return;
            if (keyDownEvent.altKey || keyDownEvent.ctrlKey || keyDownEvent.shiftKey && keyDownEvent.which !== 9)
                return;
            var question = this.currentQuestionViewModel.args.question;
            var key = 'q' + question.SCREENSCALEID.toString();
            var scale = question.CONTROLSCREENSCALE;
            switch (keyDownEvent.which) {
                case 37:
                    this.queueTypeAheadClear();
                    if (scale === scales.keys.ctlMultiSelectionListBox || scale === scales.keys.ctlMultiSelectionListBoxWithNeeds) {
                        this.gotoNextMultiSelectChoiceFromEvent(true, keyDownEvent);
                        return true;
                    }
                    if (scale === scales.keys.ctlScreenDesignGridFieldControl) {
                        this.gotoNextScreenDesignGridFromEvent(true, keyDownEvent);
                        return true;
                    }
                    break;
                case 39:
                    this.queueTypeAheadClear();
                    if (scale === scales.keys.ctlMultiSelectionListBox || scale === scales.keys.ctlMultiSelectionListBoxWithNeeds) {
                        this.gotoNextMultiSelectChoiceFromEvent(false, keyDownEvent);
                        return true;
                    }
                    if (scale === scales.keys.ctlScreenDesignGridFieldControl) {
                        this.gotoNextScreenDesignGridFromEvent(false, keyDownEvent);
                        return true;
                    }
                    break;
                case 9:
                    if (keyDownEvent.shiftKey) {
                        this.gotoNextQuestion(true, keyDownEvent);
                    }
                    else {
                        if (app.webIntake && this.questions.indexOf(question) === this.questions.length - 1) {
                            return true;
                        }
                        this.gotoNextQuestion(false, keyDownEvent);
                    }
                    return true;
                case 46:
                    if (this.isReadOnly())
                        return false;
                    if (this.questionViewModels[key] instanceof SingleChoiceControl) {
                        this.currentQuestionViewModel.value('');
                        keyDownEvent.preventDefault();
                        return true;
                    }
                    else if (this.questionViewModels[key] instanceof MultipleChoiceControl) {
                        this.currentQuestionViewModel.value([]);
                        keyDownEvent.preventDefault();
                        return true;
                    }
                    return false;
                default:
                    if (this.handleTypeAhead(keyDownEvent)) {
                        keyDownEvent.preventDefault();
                    }
                    break;
            }
            return false;
        };
        Assessment.prototype.clearTypeAhead = function () {
            clearTimeout(this.clearTypeAheadTimeoutHandle);
            this.typeAheadText = '';
            if (this.currentFormGroup != null) {
                $('.radio em, .checkbox em', this.currentFormGroup).replaceWith((function (index, innerHTML) { return innerHTML; }));
                $('.h-type-ahead-not-match', this.currentFormGroup).each(function (index, elem) {
                    elem.disabled = false;
                    $(elem).removeClass('h-type-ahead-not-match deemphasize');
                });
            }
        };
        Assessment.prototype.queueTypeAheadClear = function () {
            var _this = this;
            clearTimeout(this.clearTypeAheadTimeoutHandle);
            this.clearTypeAheadTimeoutHandle = setTimeout(function () { return _this.clearTypeAhead(); }, 2000);
        };
        Assessment.prototype.handleTypeAhead = function (keyDownEvent) {
            var _this = this;
            if (this.isReadOnly())
                return false;
            if (keyDownEvent.altKey || keyDownEvent.ctrlKey)
                return false;
            var character = '';
            if (keyDownEvent.which >= 65 && keyDownEvent.which <= 90) {
                character = String.fromCharCode('a'.charCodeAt(0) + keyDownEvent.which - 65);
            }
            else if (keyDownEvent.which >= 48 && keyDownEvent.which <= 57) {
                character = String.fromCharCode('0'.charCodeAt(0) + keyDownEvent.which - 48);
            }
            else if (keyDownEvent.which >= 96 && keyDownEvent.which <= 105) {
                character = String.fromCharCode('0'.charCodeAt(0) + keyDownEvent.which - 96);
            }
            else if (keyDownEvent.which === 8 || keyDownEvent.which === 46) {
                character = '';
            }
            else if (keyDownEvent.which === 190) {
                character = '.';
            }
            else {
                return false;
            }
            var choiceQuestionViewModel = this.currentQuestionViewModel;
            var question = choiceQuestionViewModel.args.question;
            if (!(choiceQuestionViewModel instanceof SingleChoiceControl || choiceQuestionViewModel instanceof MultipleChoiceControl)) {
                return false;
            }
            if (keyDownEvent.target instanceof HTMLSelectElement) {
                return false;
            }
            if (keyDownEvent.which === 8 || keyDownEvent.which === 46) {
                if (this.typeAheadText.length > 0) {
                    this.typeAheadText = this.typeAheadText.substr(0, this.typeAheadText.length - 1);
                }
                else {
                    return keyDownEvent.which === 8;
                }
            }
            this.typeAheadText += character;
            var foundMatch = false;
            var formGroup = $(keyDownEvent.target).closest('.form-group')[0];
            var choices;
            choices = choiceQuestionViewModel.choices.map(function (c) {
                return { choice: c, match: c.getTypeAheadMatch(_this.typeAheadText) };
            });
            var matchCount = choices.filter(function (c) { return c.match.isMatch; }).length;
            choices.forEach(function (c) {
                var $input = $('#' + c.choice.inputId, formGroup);
                var $label = $('#' + c.choice.labelId, formGroup);
                $('em', $label).remove();
                $label.contents().filter(function (i) { return $label.contents()[i].nodeType === 3; }).remove();
                $label.prepend(c.match.name);
                $input[0].disabled = !c.match.isMatch && matchCount > 1;
                if (c.match.isMatch) {
                    $label.removeClass('h-type-ahead-not-match deemphasize');
                }
                else if (matchCount < 2) {
                    $label.removeClass('deemphasize');
                    $input.removeClass('deemphasize');
                    $label.addClass('h-type-ahead-not-match');
                    $input.addClass('h-type-ahead-not-match');
                }
                else {
                    $label.addClass('h-type-ahead-not-match deemphasize');
                    $input.addClass('h-type-ahead-not-match deemphasize');
                }
                if (c.match.isMatch && !foundMatch) {
                    foundMatch = true;
                    $('#' + c.choice.inputId, formGroup).focus();
                    if (matchCount === 1 && (choiceQuestionViewModel instanceof SingleChoiceControl)) {
                        choiceQuestionViewModel.value(c.choice.choice.SCREENLOOKUPID.toString());
                    }
                }
            }, this);
            this.queueTypeAheadClear();
            if (matchCount === 0 && this.typeAheadText.length > 1 && character.length > 0) {
                this.typeAheadText = '';
                this.handleTypeAhead(keyDownEvent);
            }
            return true;
        };
        Assessment.prototype.gotoNextMultiSelectChoiceFromEvent = function (reverse, event) {
            var current = this.currentFormGroup.find('input[type="checkbox"]:focus'), available = this.currentFormGroup.find('input[type="checkbox"]:enabled');
            if (current.length !== 1 || available.length < 2)
                return false;
            var index = available.index(current[0]);
            index += (reverse ? -1 : 1);
            if (index < 0)
                index = available.length - 1;
            if (index >= available.length)
                index = 0;
            available[index].focus();
            event.preventDefault();
            return true;
        };
        Assessment.prototype.gotoNextScreenDesignGridFromEvent = function (reverse, event) {
            var current = this.currentFormGroup.find('button:focus, td:focus, th:focus'), available = this.currentFormGroup.find('button:enabled, td[tabindex], th[tabindex]');
            if (current.length !== 1 || available.length < 2)
                return false;
            var index = available.index(current[0]);
            index += (reverse ? -1 : 1);
            if (index < 0)
                index = available.length - 1;
            if (index >= available.length)
                index = 0;
            available[index].focus();
            event.preventDefault();
            return true;
        };
        Assessment.prototype.gotoNextQuestion = function (reverse, event, unanswered, required) {
            var current = this.currentQuestionViewModel.args.question;
            var next = this.getNextQuestion(current, current, reverse, unanswered, required);
            var input = this.getDefaultFocusTarget(next);
            if (input === null)
                return false;
            if (event)
                event.preventDefault();
            input.focus();
            return true;
        };
        Assessment.prototype.gotoNextUnanswered = function (reverse) {
            this.gotoNextQuestion(reverse, null, true, false);
        };
        Assessment.prototype.gotoNextRequired = function (reverse) {
            this.gotoNextQuestion(reverse, null, true, true);
        };
        Assessment.prototype.focusQuestion = function (question, highlight) {
            var input, $formGroup, $header;
            if (question.CONTROLSCREENSCALE === scales.keys.ctlHeader || question.CONTROLSCREENSCALE === scales.keys.ctlInstructionalText) {
                $header = $('#section-' + question.SCREENSCALEID.toString());
                this.scrollElementIntoView($header, $('.form-content'), true);
                question = this.getNextQuestion(question, question, false);
                this.focusQuestion(question, highlight);
                return;
            }
            input = this.getDefaultFocusTarget(question);
            if (input === null)
                return;
            if (highlight) {
                $formGroup = $(input).closest('.form-group');
                $formGroup.addClass('highlight');
                setTimeout(function () { return $formGroup.removeClass('highlight'); }, 500);
                console.info(question);
            }
            input.focus();
        };
        Assessment.prototype.getNextQuestion = function (originalCurrent, current, reverse, unanswered, required) {
            var currentIndex = this.questions.indexOf(current);
            var nextIndex = currentIndex + (reverse ? -1 : 1);
            if (nextIndex >= this.questions.length) {
                nextIndex = 0;
            }
            else if (nextIndex < 0) {
                nextIndex = this.questions.length - 1;
            }
            var nextQuestion = this.questions[nextIndex];
            if (originalCurrent === nextQuestion)
                return originalCurrent;
            if (nextQuestion.CONTROLSCREENSCALE === scales.keys.ctlLineSpace || nextQuestion.CONTROLSCREENSCALE === scales.keys.ctlHeader || nextQuestion.CONTROLSCREENSCALE === scales.keys.ctlInstructionalText) {
                return this.getNextQuestion(originalCurrent, nextQuestion, reverse, unanswered, required);
            }
            if (required && nextQuestion.REQUIRED === 0 && nextQuestion !== current) {
                return this.getNextQuestion(originalCurrent, nextQuestion, reverse, unanswered, required);
            }
            var nextQuestionViewModel = this.getQuestionViewModel(nextQuestion);
            if (nextQuestionViewModel.isSkipped()) {
                return this.getNextQuestion(originalCurrent, nextQuestion, reverse, unanswered, required);
            }
            if (unanswered && nextQuestionViewModel.isAnswered() && nextQuestion !== current) {
                return this.getNextQuestion(originalCurrent, nextQuestion, reverse, unanswered, required);
            }
            return nextQuestion;
        };
        Assessment.prototype.getDefaultFocusTarget = function (question) {
            var key = 'q' + question.SCREENSCALEID.toString();
            var $formGroup = $('#' + key, this.view);
            if ($formGroup.length === 0)
                return null;
            var target = null;
            if (this.questionViewModels[key] instanceof SingleChoiceControl || this.questionViewModels[key] instanceof MultipleChoiceControl) {
                target = $formGroup.find('input:checked:first');
            }
            if (target === null || target.length === 0) {
                target = $formGroup.find('input:visible:first');
            }
            if (target === null || target.length === 0) {
                target = $formGroup.find('select:visible:first');
            }
            if (target === null || target.length === 0) {
                target = $formGroup.find('textarea:visible:first');
            }
            if (target.length === 0) {
                target = $formGroup.find('div[contenteditable=\'true\'].form-control:first');
            }
            if (target.length === 0) {
                target = $formGroup.find('button:visible:first');
            }
            if (target.length === 0) {
                target = $formGroup.find('a:visible:first');
            }
            if (target.length === 0)
                return $formGroup[0];
            return target[0];
        };
        Assessment.prototype.focusFindQuestion = function () {
            $('div.find input', this.view).focus();
        };
        Assessment.prototype.focusSectionList = function () {
            $('.nav-list-container a:visible:first', this.view).focus();
        };
        Assessment.prototype.toggleNarrative = function () {
            this.narrative(!this.narrative());
            if (this.narrative() && this.editSession()) {
                this.cancelEditSession();
            }
            if (this.narrative()) {
                $('.narrative textarea:first', this.view).focus().putCursorAtEnd();
            }
            else {
                $('.form-content input:visible:first', this.view).focus();
            }
        };
        Assessment.prototype.toggleEditSession = function () {
            if (this.editSession()) {
                this.cancelEditSession();
            }
            else {
                if (this.narrative()) {
                    this.narrative(false);
                }
                this.editSessionSnapshot = new Snapshot(this.entity);
                this.editSession(true);
                $('.edit-session .autofocus', this.view)[1].focus();
            }
        };
        Assessment.prototype.submitEditSession = function () {
            if (!this.editSession()) {
                return;
            }
            if (this.entity.Status() === 'Draft') {
                this.validationErrors([]);
                for (var item in this.questionViewModels) {
                    this.questionViewModels[item].hasError(false);
                }
                this.closeEditSession(false);
                return;
            }
            if (this.isReadOnly() || this.entity.Status() !== 'Draft') {
                this.validate();
                this.closeEditSession(false);
            }
        };
        Assessment.prototype.cancelEditSession = function () {
            if (!this.editSession()) {
                return;
            }
            this.closeEditSession(true);
        };
        Assessment.prototype.closeEditSession = function (restore) {
            this.editSession(false);
            if (restore) {
                this.editSessionSnapshot.restore();
            }
            this.editSessionSnapshot.dispose();
            this.editSessionSnapshot = null;
            $('.form-content input:visible:first', this.view).focus();
        };
        Assessment.prototype.toggleHistory = function () {
            this.responseHistory.active(!this.responseHistory.active());
            if (this.responseHistory.active()) {
                app.statusBar.success('Displaying response history in the navigation panel.', 4000);
            }
            this.findQuestion.searchString('');
        };
        Assessment.prototype.toggleHelp = function () {
            this.help(!this.help());
            if (this.help()) {
                app.statusBar.success('Displaying question instructions beneath each question.', 4000);
            }
        };
        Assessment.prototype.toggleProperties = function () {
            this.properties(!this.properties());
            if (this.properties()) {
                app.statusBar.success('Displaying question properties.', 4000);
            }
        };
        Assessment.prototype.triggerClickOnEnterOrSpacebar = function (d, e) {
            if (e.which === 13 || e.which === 32) {
                e.preventDefault();
                $(e.target).trigger('click');
                return false;
            }
            return true;
        };
        Assessment.prototype.dispose = function () {
            this.disposed = true;
            clearInterval(this.scrollspyRefreshInterval);
            $(window).off('scroll.bs.affix.data-api').off('click.bs.affix.data-api').off('resize.assessments.ui.assessment');
            $('.h-sidenav li a', this.view).off('click.assessments.ui.assessment');
            $('.form-group', this.view).find('input').off('focus.assessments.ui.assessment').off('keydown.assessments.ui.assessment');
            this.entityManager.rejectedChanges.unsubscribe(this.rejectedChangesSubscription);
            this.indicatorsManager.dispose();
            this.conditionsManager.dispose();
            _super.prototype.dispose.call(this);
        };
        Assessment.prototype.setFormReadOnly = function (child) {
            var _this = this;
            if (this.isReadOnly()) {
                $('.content .form-content .form-group input', child).prop('readonly', true);
                $('.content .form-content .form-group select', child).prop('readonly', true);
                $('.content .form-content .form-group textarea', child).prop('readonly', true);
                $('.content .form-content .form-group input[type=checkbox]', child).prop('disabled', true);
                $('.content .form-content .form-group input[type=radio]', child).prop('disabled', true);
                $('.content .form-content .form-group .input-group button', child).prop('disabled', true);
                $('.content .narrative textarea', child).prop('readonly', true);
            }
            else {
                var content = $('.content .form-content', child)[0];
                this.questions.forEach(function (q) {
                    var isAdd = _this.entity.entityAspect.entityState.isAdded();
                    var readOnly = equalsIgnoreCase(q.ReadOnlyState, 'Both') || isAdd && equalsIgnoreCase(q.ReadOnlyState, 'Add') || !isAdd && equalsIgnoreCase(q.ReadOnlyState, 'Edit') || _this.screenDesignIsReadOnly;
                    _this.isReadOnlyField[q.SCREENSCALEID] = readOnly;
                    if (!readOnly) {
                        return;
                    }
                    var formGroup = $('#q' + q.SCREENSCALEID.toString(), content)[0];
                    if (!formGroup) {
                        return;
                    }
                    $('input', formGroup).prop('readonly', true);
                    $('select', formGroup).prop('readonly', true);
                    $('textarea', formGroup).prop('readonly', true);
                    $('input[type=checkbox]', formGroup).prop('disabled', true);
                    $('input[type=radio]', formGroup).prop('disabled', true);
                    $('.input-group button', formGroup).prop('disabled', true);
                });
            }
        };
        Assessment.prototype.afterRenderProcessing = function () {
            sessionStorage.removeItem('IsFirstFocus');
        };
        return Assessment;
    })(AssessmentBase);
    return Assessment;
});

define('assessments/screen-repo',["require", "exports", 'core/constants', 'core/util', 'core/storage', 'assessments/scales', 'assessments/assessment'], function (require, exports, constants, util, storage, scales, AssessmentViewModel) {
    var storageOptions = { shared: false, hipaa: false };
    function getStorageKey(id) {
        return 'screen-design5/' + id.toString(10);
    }
    exports.screenConstants = [];
    function getScreenDesign(id) {
        return storage.getItem(getStorageKey(id), storageOptions).then(function (result) { return fixup(result.data); }, function (reason) { return getScreenDesignFromServer(id); });
    }
    exports.getScreenDesign = getScreenDesign;
    function getScreenDesignFromServer(id) {
        return Q($.getJSON(constants.services.serviceBaseUrl + 'ScreenDesigns/ScreenDesign/' + id.toString(10))).then(function (sd) { return storage.setItem(getStorageKey(sd.SCREENDESIGNID), sd, storageOptions, sd.DATETIMESTAMP).then(function () { return sd; }); }).then(function (sd) { return fixup(sd); });
    }
    exports.getScreenDesignFromServer = getScreenDesignFromServer;
    function getScreenDesignFromServerByScreenId(id) {
        return Q($.getJSON(constants.services.serviceBaseUrl + 'ScreenDesigns/GetScreenDesignByScreenID/' + id)).then(function (sd) { return storage.setItem(getStorageKey(sd.SCREENDESIGNID), sd, storageOptions, sd.DATETIMESTAMP).then(function () { return sd; }); }).then(function (sd) { return fixup(sd); });
    }
    exports.getScreenDesignFromServerByScreenId = getScreenDesignFromServerByScreenId;
    function getGroupSetupConfigRace(id, controlid) {
        return Q($.getJSON(constants.services.serviceBaseUrl + 'ScreenDesigns/GetGroupSetupConfigRace?' + $.param({ groupid: id, controlid: controlid }))).then(function (items) {
            return items;
        }).fail(function (reason) {
            return '';
        });
    }
    exports.getGroupSetupConfigRace = getGroupSetupConfigRace;
    function initialize() {
        return Q.all([syncScreenDesigns(), syncConstants()]);
    }
    exports.initialize = initialize;
    function syncConstants() {
        return Q($.getJSON(constants.services.serviceBaseUrl + 'ScreenDesigns/Constants')).then(function (screenConstants) { return storage.setItem('screen-constants', screenConstants, storageOptions); }).fail(function (reason) {
            if (!util.isConnectionFailure(reason)) {
                return Q.reject(reason);
            }
            return storage.getItem('screen-constants', storageOptions).then(function (result) {
                exports.screenConstants = result.data;
            });
        });
    }
    exports.syncConstants = syncConstants;
    function fixup(screenDesign) {
        screenDesign.SCREENQUESTIONS = screenDesign.SCREENQUESTIONS;
        screenDesign.SCREENQUESTIONS.forEach(function (q) {
            if (/^file$/i.test(q.QUESTIONID) && (q.CONTROLSCREENSCALE === scales.keys.ctlHeader || q.CONTROLSCREENSCALE === scales.keys.ctlLineSpace)) {
                q.CONTROLSCREENSCALE = scales.keys.ctlFiles;
            }
            else if (/^DocManage/i.test(q.QUESTIONID) && (q.CONTROLSCREENSCALE === scales.keys.ctlLineSpace)) {
                q.CONTROLSCREENSCALE = scales.keys.ctlFiles;
            }
            else if (q.CONTROLSCREENSCALE === scales.keys.ctlRichText) {
                q.CONTROLSCREENSCALE = scales.keys.ctlRichText;
            }
        });
        return screenDesign;
    }
    function getScreenDesignsByPackage(packageName) {
        var screenDesigns = util.Arrays.selectMany(util.Arrays.selectMany(User.Current.Roles, function (x) { return x.Role.GroupPackages; }), function (x) { return x.ConfigPackage.ScreenDesignConfigPackages; }).filter(function (x) { return x.ConfigPackage.ConfigPackageType.PackageTypeName === packageName && x.Restricted === false; }).map(function (x) { return x.SCREENDESIGN; }).filter(function (value, index, self) { return self.indexOf(value) === index; }).sort(function (a, b) { return util.stringComparisonOrdinalIgnoreCase(a.SCREENDESIGNNAME, b.SCREENDESIGNNAME); });
        return screenDesigns;
    }
    function isInPackage(packageName, id) {
        return util.Arrays.any(getScreenDesignsByPackage(packageName), function (sd) { return sd.SCREENDESIGNID === id; });
    }
    exports.isInPackage = isInPackage;
    function syncScreenDesigns() {
        var screenDesigns = getScreenDesignsByPackage('ConsumerAssessments'), promise = Q.resolve(null), stamps = [];
        screenDesigns.forEach(function (sd) { return stamps[sd.SCREENDESIGNID] = moment(sd.DATETIMESTAMP).toDate(); });
        promise.then(function () {
            return getGroupSetupConfigRace(User.Current.Role.Role.GroupID, 'lblRACE').then(function (items) {
                if (!isNullOrEmpty(items)) {
                    localStorage.setItem("GroupSetupConfigRace", JSON.stringify(items));
                }
            }).fail(function (reason) {
                if (!util.isConnectionFailure(reason)) {
                    return Q.reject(reason);
                }
            });
        });
        screenDesigns.forEach(function (screenDesign) {
            promise = promise.then(function () {
                app.statusBar.download('Downloading screen designs...');
                return storage.getItem(getStorageKey(screenDesign.SCREENDESIGNID), storageOptions, true).fail(function (reason) { return { timestamp: new Date(1900, 0, 1) }; }).then(function (result) {
                    if (result.timestamp.getTime() === stamps[screenDesign.SCREENDESIGNID].getTime()) {
                        return Q.resolve(null);
                    }
                    app.statusBar.download('Downloading screen designs... ' + screenDesign.SCREENDESIGNNAME);
                    return getScreenDesignFromServer(screenDesign.SCREENDESIGNID).fail(function (reason) {
                        if (!util.isConnectionFailure(reason)) {
                            return Q.reject(reason);
                        }
                    });
                });
            });
        });
        return promise;
    }
    exports.syncScreenDesigns = syncScreenDesigns;
    function getAssessmentViewModel() {
        return new AssessmentViewModel();
    }
    exports.getAssessmentViewModel = getAssessmentViewModel;
});

define('security/login',["require", "exports", 'durandal/app', 'core/constants', 'core/util', 'core/storage', 'afterLoginBootstrapper', 'entities/api'], function (require, exports, durandalApp, constants, util, storage, afterLoginBootstrapper, entities) {
    var storageOptions = { global: true, hipaa: false };
    var LoginArgs = (function () {
        function LoginArgs(UserName, Password) {
            this.UserName = UserName;
            this.Password = Password;
            this.CultureName = constants.globalization.defaultCulture;
        }
        return LoginArgs;
    })();
    exports.LoginArgs = LoginArgs;
    function unlock(password) {
        var userId = User.IsLoggedIn ? User.Current.UserId : null;
        return Q($.post(constants.services.serviceBaseUrl + 'Authentication/Login', new LoginArgs(userId, password))).then(function (result) {
            if (result.Error) {
                return Q.reject(result);
            }
            return result;
        }).then(function (result) {
            AuthorizationHeader.Current = result.AuthorizationHeader;
        }).fail(function (reason) {
            if (util.isConnectionFailure(reason)) {
                return validateOfflinePassword(User.Current, password);
            }
            return Q.reject(reason);
        });
    }
    exports.unlock = unlock;
    function extendSSO() {
        return Q($.post(app.hostUrl + 'api/Authentication/ExtendSSOTimeout')).fail(function (reason) {
            if (util.isConnectionFailure(reason))
                return;
            return Q.reject(reason);
        });
    }
    exports.extendSSO = extendSSO;
    function login(args, method) {
        if (method === void 0) { method = 'Authentication/Login'; }
        var loginResult;
        return Q($.post(constants.services.serviceBaseUrl + method, args)).then(function (result) {
            if (result.Error) {
                return Q.reject(result);
            }
            $.extend(result.SystemSettings, result.SystemSetup);
            WebIntakeSettings = result.WebIntakeSettings;
            return result;
        }).then(function (result) {
            loginResult = result;
            AuthorizationHeader.Current = loginResult.AuthorizationHeader;
        }).then(function () { return loadMetadata(loginResult.SecurityProfile); }).then(function () { return enableOfflineLogin(loginResult, args); }).then(function () { return storage.unlock(loginResult.OfflineStorageEncryptionKey); }).then(function () { return finishLoginProcess(loginResult.SecurityProfile, loginResult.SystemSettings); });
    }
    exports.login = login;
    function checkIfAlreadyLoggedIn() {
        var loginResult;
        return Q($.get(constants.services.serviceBaseUrl + "Authentication/CheckIfAlreadyLoggedIn")).then(function (result) {
            if (!result) {
                redirectToLogin();
            }
            else {
                if (result.Error) {
                    return Q.reject(result);
                }
                else {
                    loginResult = result;
                    AuthorizationHeader.Current = loginResult.AuthorizationHeader;
                }
            }
        }).then(function () { return loadMetadata(loginResult.SecurityProfile); }).then(function () { return enableOfflineLogin(loginResult, new LoginArgs(loginResult.SecurityProfile.UserId, "")); }).then(function () { return storage.unlock(loginResult.OfflineStorageEncryptionKey); }).then(function () { return finishLoginProcess(loginResult.SecurityProfile, loginResult.SystemSettings); }).then(function () { return setRoot(); });
    }
    exports.checkIfAlreadyLoggedIn = checkIfAlreadyLoggedIn;
    function attemptRecover() {
        return login({}, 'Authentication/Recover');
    }
    exports.attemptRecover = attemptRecover;
    function attemptWebIntakeLogin() {
        var loginResult;
        return Q($.post(constants.services.serviceBaseUrl + 'Authentication/WebIntakeLogin?name=' + app.webIntakeConfigurationName)).then(function (result) {
            loginResult = result;
            AuthorizationHeader.Current = loginResult.AuthorizationHeader;
            $.extend(result.SystemSettings, result.SystemSetup);
            WebIntakeSettings = result.WebIntakeSettings;
            if (app.webIntake) {
                document.title = result.WebIntakeSettings.BrowserTabTitle;
            }
        }).then(function () { return loadMetadata(loginResult.SecurityProfile); }).then(function () { return finishLoginProcess(loginResult.SecurityProfile, loginResult.SystemSettings); }).fail(function (reason) {
            if (reason.status === 500 && reason.responseJSON && /^The WebIntake configuration setting/.test(reason.responseJSON.ExceptionMessage)) {
                console.log('Invalid web-intake configuration name or the configuration is incomplete.\nConfigurationName = "' + app.webIntakeConfigurationName + '"\n' + reason.responseJSON.ExceptionMessage);
                alert('The site address you are trying to access is incorrect.  Please check the URL and try again.');
                return Q.defer().promise;
            }
            return Q.reject(reason);
        });
    }
    exports.attemptWebIntakeLogin = attemptWebIntakeLogin;
    function attemptCfWebIntakeLogin() {
        var loginResult;
        return Q($.post(constants.services.serviceBaseUrl + 'Authentication/CfWebIntakeLogin?name=' + app.CfWebIntakeName)).then(function (result) {
            loginResult = result;
            AuthorizationHeader.Current = loginResult.AuthorizationHeader;
            $.extend(result.SystemSettings, result.SystemSetup);
            CfWebIntakeSettings = result.CfWebIntakeSettings;
            document.title = result.CfWebIntakeSettings.CfWebIntakeName;
        }).then(function () { return loadMetadata(loginResult.SecurityProfile); }).then(function () { return finishLoginProcess(loginResult.SecurityProfile, loginResult.SystemSettings); }).fail(function (reason) {
            if (reason.status === 500 && reason.responseJSON && /^The WebIntake configuration setting/.test(reason.responseJSON.ExceptionMessage)) {
                console.log('Invalid web-intake configuration name or the configuration is incomplete.\nConfigurationName = "' + app.webIntakeConfigurationName + '"\n' + reason.responseJSON.ExceptionMessage);
                alert('The site address you are trying to access is incorrect.  Please check the URL and try again.');
                return Q.defer().promise;
            }
            return Q.reject(reason);
        });
    }
    exports.attemptCfWebIntakeLogin = attemptCfWebIntakeLogin;
    function attemptConsumerModuleLogin() {
        return this.login({}, 'Authentication/SsoConsumerApp').fail(function (reason) {
            alert(reason);
            debugger;
        });
    }
    exports.attemptConsumerModuleLogin = attemptConsumerModuleLogin;
    function redirectToLogin() {
        window.location.replace(constants.services.serviceBaseUrl + 'Authentication/initiatelogin');
    }
    exports.redirectToLogin = redirectToLogin;
    function checkIfSessionActive() {
        return Q($.get(constants.services.serviceBaseUrl + "Authentication/CheckIfSessionActive"));
    }
    exports.checkIfSessionActive = checkIfSessionActive;
    function getUserStorageKey(context) {
        var a = context;
        return 'user/' + a.UserId + '/' + a.SqlServer + '/' + a.Database;
    }
    function getRolesStorageKey(context) {
        var a = context;
        return 'user-roles/' + a.UserId + '/' + a.SqlServer + '/' + a.Database;
    }
    function getSystemSettingsStorageKey(context) {
        var a = context;
        return 'system-settings/' + a.SqlServer + '/' + a.Database;
    }
    function getCiphersStorageKey(userName) {
        return 'ciphers/' + userName;
    }
    function loadMetadata(securityProfile) {
        var immediateServerLoad = false;
        if (!app.webIntake && !app.consumerModule && !app.CfWebIntake) {
            app.busyIndicator.setBusy('Loading metadata...');
        }
        return loadMetadataFromStorage(securityProfile).fail(function (reason) {
            if (!/^key not found/.test(reason)) {
                return Q.reject(reason);
            }
            immediateServerLoad = true;
        }).then(function () {
            var serverPromise = loadMetadataFromServer(securityProfile);
            if (immediateServerLoad) {
                return serverPromise.then(function () {
                    if (!app.webIntake && !app.consumerModule && !app.CfWebIntake) {
                        app.busyIndicator.setBusyLoading();
                    }
                });
            }
            else {
                if (!app.webIntake && !app.consumerModule && !app.CfWebIntake) {
                    app.busyIndicator.setBusyLoading();
                }
                serverPromise.done();
            }
        });
    }
    function loadMetadataFromServer(securityProfile) {
        var rolesStorageKey = getRolesStorageKey(securityProfile);
        console.log('METADATA: start load');
        return entities.createBreezeEntityManager('Metadata').then(function (entityManager) {
            return entityManager.executeQuery(new breeze.EntityQuery('Roles').noTracking(true)).then(function (queryResult) {
                securityProfile.Roles = queryResult.results;
                console.log('METADATA: end load');
                setTimeout(function () {
                    console.log('METADATA: start store');
                    storage.setItem(rolesStorageKey, queryResult.results, storageOptions).then(function () { return console.log('METADATA: end store'); }).done();
                }, 5000);
            });
        });
    }
    function loadMetadataFromStorage(securityProfile) {
        var rolesStorageKey = getRolesStorageKey(securityProfile);
        return storage.getItem(rolesStorageKey, storageOptions).then(function (result) {
            securityProfile.Roles = result.data;
        });
    }
    function enableOfflineLogin(loginResult, loginArgs) {
        if (loginArgs.Password === undefined) {
            return;
        }
        var ciphers = {
            encryptionKeyCipher: sjcl.encrypt(loginArgs.Password, loginResult.OfflineStorageEncryptionKey),
            validatePasswordCipher: sjcl.encrypt(loginArgs.Password, 'test')
        };
        var ciphersStorageKey = getCiphersStorageKey(loginResult.SecurityProfile.UserId);
        var userStorageKey = getUserStorageKey(loginResult.SecurityProfile);
        var systemSettingsStorageKey = getSystemSettingsStorageKey(loginResult.SecurityProfile);
        var rolesStorageKey = getRolesStorageKey(loginResult.SecurityProfile);
        return storage.setItem(ciphersStorageKey, ciphers, storageOptions).then(function () { return storage.setItem(userStorageKey, {
            UserId: loginResult.SecurityProfile.UserId,
            SqlServer: loginResult.SecurityProfile.SqlServer,
            Database: loginResult.SecurityProfile.Database,
            UserStamp: loginResult.SecurityProfile.UserStamp,
            MemberID: loginResult.SecurityProfile.MemberID,
            DefaultFundCode: loginResult.SecurityProfile.DefaultFundCode
        }, storageOptions); }).then(function () { return storage.setItem(systemSettingsStorageKey, loginResult.SystemSettings, storageOptions); });
    }
    function validateOfflinePassword(userInfo, password) {
        var ciphersStorageKey = getCiphersStorageKey(userInfo.UserId);
        return storage.getItem(ciphersStorageKey, storageOptions).then(function (result) {
            if (sjcl.decrypt(password, result.data.validatePasswordCipher)) {
                var encryptionKey = sjcl.decrypt(password, result.data.encryptionKeyCipher);
                return storage.unlock(encryptionKey);
            }
            throw new Error('Incorrect Password');
        });
    }
    function offlineLogin(userInfo, password) {
        var userStorageKey = getUserStorageKey(userInfo);
        return validateOfflinePassword(userInfo, password).then(function () { return storage.getItem(userStorageKey, storageOptions); }).then(function (result) {
            var systemSettingsStorageKey = getSystemSettingsStorageKey(result.data);
            return loadMetadataFromStorage(result.data).then(function () { return storage.getItem(systemSettingsStorageKey, storageOptions); }).then(function (result2) { return finishLoginProcess(result.data, result2.data); });
        });
    }
    exports.offlineLogin = offlineLogin;
    function logout() {
        app.busyIndicator.setBusy('Logging out...');
        if (app.IsSSOEnabled) {
            localStorage.setItem("sessionStartTime", new Date().toString());
            window.location.replace(constants.services.serviceBaseUrl + 'Authentication/SSOLogout');
        }
        else {
            Q($.post(constants.services.serviceBaseUrl + 'Authentication/Logout')).fail(function (reason) {
                app.busyIndicator.setReady();
                if (util.isConnectionFailure(reason))
                    return;
                return Q.reject(reason);
            }).then(function () {
                User.Current = null;
                User.IsLoggedIn = false;
                AuthorizationHeader.Current = null;
                window.location.hash = '';
                window.location.reload();
            }).done();
        }
    }
    exports.logout = logout;
    function finishLoginProcess(securityProfile, systemSettings) {
        User.Current = securityProfile;
        User.Current.Role = util.Arrays.firstOrDefault(securityProfile.Roles, function (r) { return r.DefaultRole; });
        if (User.Current.Role === null) {
            throw new Error('No default role was found');
        }
        User.IsLoggedIn = true;
        SystemSettings = systemSettings;
        return afterLoginBootstrapper.initialize().then(setRoot);
    }
    function setRoot() {
        if (app.CfWebIntake) {
            durandalApp.setRoot('cfshell');
            return;
        }
        if (app.webIntake || app.consumerModule) {
            durandalApp.setRoot('webIntakeShell');
            return;
        }
        durandalApp.setRoot('shell');
    }
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('security/ui/unlock',["require", "exports", 'security/login', 'core/util', 'core/viewmodels'], function (require, exports, login, util, viewmodels) {
    var Unlock = (function (_super) {
        __extends(Unlock, _super);
        function Unlock() {
            _super.call(this);
            this.password = '';
            this.isLoggingIn = ko.observable(false);
            this.errorMessage = ko.observable('');
            if (app.debugUserId && app.debugPassword) {
                this.password = app.debugPassword;
            }
        }
        Unlock.prototype.submit = function () {
            var _this = this;
            if (this.isLoggingIn())
                return;
            if (isNullOrEmpty(this.password)) {
                this.errorMessage($.i18n.t('security.passwordIsRequired'));
                return;
            }
            this.isLoggingIn(true);
            app.busyIndicator.setBusy($.i18n.t('security.authenticating'));
            this.errorMessage('');
            login.unlock(this.password).then(function () {
                _super.prototype.submit.call(_this);
            }).fail(function (reason) {
                if (reason.Error) {
                    _this.errorMessage(reason.Error);
                    return;
                }
                if (util.isConnectionFailure(reason)) {
                    login.offlineLogin(User.Current, _this.password);
                    return;
                }
                return Q.reject(reason);
            }).finally(function () {
                _this.isLoggingIn(false);
                app.busyIndicator.setReady();
            }).done();
        };
        return Unlock;
    })(viewmodels.ModalViewModelBase);
    return Unlock;
});

define('security/ssoSessionHandler',["require", "exports", 'core/durability', './login'], function (require, exports, durability, login) {
    var lastSlide = new Date(1900, 0, 1);
    var startDate = new Date();
    var interval;
    function initialize() {
        if (!app.webIntake && !app.CfWebIntake) {
            startDate.setSeconds(startDate.getSeconds() + getLogoutSeconds());
            localStorage.setItem("sessionStartTime", startDate.toString());
            updatedisplayTimerTick();
            $(document).on('mousemove keyup touchmove touchend', throttle(onActivity, 900));
        }
    }
    exports.initialize = initialize;
    function updatedisplayTimerTick() {
        interval = setInterval(function () {
            var sessionStartTime = localStorage.getItem("sessionStartTime");
            var differenceSeconds = Math.round((new Date(sessionStartTime).getTime() - new Date().getTime()) / 1000);
            if (differenceSeconds > 0 && differenceSeconds <= 180 && !durability.isSSOSessionExpiryPopupVisible) {
                onInactivityTimeout();
            }
            else if (differenceSeconds <= 0) {
                onSessionTimeout();
                clearInterval(interval);
            }
            else if (differenceSeconds > 180 && durability.isSSOSessionExpiryPopupVisible) {
                durability.closeSessionDialog();
            }
            durability.displayTimer(formatTimeLeft(differenceSeconds));
        }, 1000);
    }
    function getLogoutSeconds() {
        return (SystemSettings.InactivityTimeout * 60);
    }
    function onActivity() {
        var lastSlidSeconds = moment().diff(moment(lastSlide), 'seconds');
        if (lastSlidSeconds > 60) {
            if (!durability.isSSOSessionExpiryPopupVisible) {
                resetCountdown();
                lastSlide = new Date();
                login.extendSSO();
            }
        }
        else {
            return;
        }
    }
    function onInactivityTimeout() {
        if (app.isOffline()) {
            resetCountdown();
        }
        else {
            durability.displaySSOSessionExpiryWarning();
        }
    }
    function onSessionTimeout() {
        login.logout();
    }
    function throttle(action, rateMilliseconds) {
        var lastInvoke = null;
        return function () {
            var now = +new Date();
            if (lastInvoke !== null && now - rateMilliseconds < lastInvoke)
                return;
            lastInvoke = now;
            action();
        };
    }
    function formatTimeLeft(seconds) {
        var min = 0;
        if (seconds >= 60) {
            min = Math.floor(seconds / 60);
            seconds -= (min * 60);
        }
        return "" + padLeadingZeros(min, 2) + ":" + padLeadingZeros(seconds, 2) + "";
    }
    function padLeadingZeros(num, size) {
        var s = num + '';
        while (s.length < size) {
            s = '0' + s;
        }
        return s;
    }
    function resetCountdown() {
        startDate = new Date();
        startDate.setSeconds(startDate.getSeconds() + getLogoutSeconds());
        localStorage.setItem("sessionStartTime", startDate.toString());
    }
    exports.resetCountdown = resetCountdown;
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('security/ui/ssoTimeout',["require", "exports", 'core/viewmodels', 'security/login', 'core/durability', 'security/ssoSessionHandler', 'core/util'], function (require, exports, viewmodels, login, durability, ssoHandler, util) {
    var SSOTimeout = (function (_super) {
        __extends(SSOTimeout, _super);
        function SSOTimeout() {
            _super.call(this);
            this.isLoggingIn = ko.observable(false);
            this.errorMessage = ko.observable('');
            this.popupDisplayTimer = ko.observable('');
            this.subscriber = null;
            this.updateDisplayTimer();
        }
        SSOTimeout.prototype.updateDisplayTimer = function () {
            var self = this;
            this.subscriber = durability.displayTimer.subscribe(function (newValue) {
                self.popupDisplayTimer(newValue);
            });
        };
        SSOTimeout.prototype.continueSession = function () {
            var _this = this;
            if (this.isLoggingIn())
                return;
            this.isLoggingIn(true);
            app.busyIndicator.setBusy($.i18n.t('security.authenticating'));
            login.extendSSO().then(function (res) {
                if (res) {
                    ssoHandler.resetCountdown();
                    _super.prototype.submit.call(_this);
                }
            }).fail(function (reason) {
                if (reason.Error) {
                    _this.errorMessage(reason.Error);
                    return;
                }
                if (util.isConnectionFailure(reason)) {
                    app.isOffline(true);
                    localforage.setItem('isOffline', app.isOffline());
                    return;
                }
                return Q.reject(reason);
            }).finally(function () {
                _this.isLoggingIn(false);
                app.busyIndicator.setReady();
                _this.subscriber.dispose();
            }).done();
        };
        SSOTimeout.prototype.logout = function () {
            _super.prototype.cancel.call(this);
            this.subscriber.dispose();
            login.logout();
        };
        SSOTimeout.prototype.closePopup = function () {
            _super.prototype.cancel.call(this);
            this.subscriber.dispose();
        };
        return SSOTimeout;
    })(viewmodels.ModalViewModelBase);
    return SSOTimeout;
});

define('core/durability',["require", "exports", 'core/constants', 'durandal/app', 'core/messageBox', 'security/ui/unlock', 'security/ui/ssoTimeout'], function (require, exports, constants, durandalApp, messageBox, Unlock, SSOTimeout) {
    exports.signInDialogIsShowing = false;
    exports.isSSOSessionExpiryPopupVisible = false;
    exports.displayTimer = ko.observable('');
    exports.sessionDialog;
    var retryQueue = [], appRestartTimeoutHandle;
    function ajaxInternal(state) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        var xhr = jQueryAjax.apply(this, args);
        if (state)
            xhr._retryState = state;
        else
            xhr._retryState.deferred = $.Deferred();
        xhr.then = xhr._retryState.deferred.then;
        xhr.fail = xhr._retryState.deferred.fail;
        xhr.always = xhr._retryState.deferred.always;
        return xhr;
    }
    var jQueryAjax = $.ajax;
    function proxiedAjax() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i - 0] = arguments[_i];
        }
        args.unshift(null);
        return ajaxInternal.apply(this, args);
    }
    $.ajax = proxiedAjax;
    function retry(jqXHR) {
        var state = jqXHR._retryState;
        state.attempts++;
        ajaxInternal(state, state.options);
    }
    function ajaxPrefilter(options, originalOptions, jqXHR) {
        jqXHR._retryState = {
            options: originalOptions,
            attempts: 1,
            error: originalOptions.error,
            success: originalOptions.success,
            deferred: null
        };
        options.timeout = constants.ajax.defaultTimeout;
        options.error = handleError;
        options.success = handleSuccess;
        var newOptions = {
            xhrFields: {
                withCredentials: true
            },
            headers: {
                contextCookie: false,
                timezone: jstz.determine().name()
            }
        };
        if (AuthorizationHeader.Current) {
            newOptions.headers['Authorization'] = AuthorizationHeader.Current;
        }
        $.extend(true, options, newOptions);
    }
    function displaySessionLockedMessage() {
        function displaySignIn() {
            app.busyIndicator.setReady();
            durandalApp.showDialog(new Unlock()).then(function (result) {
                clearTimeout(appRestartTimeoutHandle);
                exports.signInDialogIsShowing = false;
                while (retryQueue.length > 0) {
                    var jqXHR = retryQueue.shift();
                    retry(jqXHR);
                }
            }).done();
        }
        if (exports.signInDialogIsShowing)
            return;
        exports.signInDialogIsShowing = true;
        appRestartTimeoutHandle = setTimeout(function () { return window.location.reload(); }, 4 * 60 * 60 * 1000);
        if (app.webIntake) {
            messageBox.show('webIntake.notAuthorizedTitle', 'webIntake.notAuthorizedMessage', []);
        }
        else if (moment().diff(moment(app.startDateTime), 'seconds') >= 60) {
            messageBox.show('sessionLocked.title', 'sessionLocked.message', messageBox.buttons.okOnly).then(displaySignIn);
        }
        else {
            displaySignIn();
        }
    }
    exports.displaySessionLockedMessage = displaySessionLockedMessage;
    function handle401Unauthorized(jqXHR) {
        retryQueue.push(jqXHR);
        displaySessionLockedMessage();
    }
    function displaySSOSessionExpiryWarning() {
        app.busyIndicator.setReady();
        exports.sessionDialog = new SSOTimeout();
        durandalApp.showDialog(exports.sessionDialog).then(function (result) {
            clearTimeout(appRestartTimeoutHandle);
            exports.isSSOSessionExpiryPopupVisible = false;
            while (retryQueue.length > 0) {
                var jqXHR = retryQueue.shift();
                retry(jqXHR);
            }
        }).done();
        exports.isSSOSessionExpiryPopupVisible = true;
    }
    exports.displaySSOSessionExpiryWarning = displaySSOSessionExpiryWarning;
    function closeSessionDialog() {
        if (exports.sessionDialog != null) {
            exports.sessionDialog.closePopup();
            exports.isSSOSessionExpiryPopupVisible = false;
        }
    }
    exports.closeSessionDialog = closeSessionDialog;
    function raiseError(jqXHR, textStatus, errorThrown) {
        if (jqXHR._retryState.error) {
            jqXHR._retryState.error(jqXHR, textStatus, errorThrown);
        }
        if (jqXHR._retryState.deferred) {
            jqXHR._retryState.deferred.reject(jqXHR, textStatus, errorThrown);
        }
    }
    function handleError(jqXHR, textStatus, errorThrown) {
        updateConnectionStatus(jqXHR);
        if (jqXHR.status === 401) {
            handle401Unauthorized(jqXHR);
            return;
        }
        if (textStatus !== constants.ajax.timeoutTextStatus) {
            raiseError(jqXHR, textStatus, errorThrown);
            return;
        }
        if (jqXHR._retryState.attempts <= constants.ajax.maxAttempts) {
            retry(jqXHR);
            return;
        }
        messageBox.show('ajaxRetry.title', 'ajaxRetry.message', messageBox.buttons.yesNo).then(function (r) {
            if (r === messageBox.yes) {
                retry(jqXHR);
                return;
            }
            raiseError(jqXHR, textStatus, errorThrown);
        });
    }
    function handleSuccess(data, textStatus, jqXHR) {
        updateConnectionStatus(jqXHR);
        if (jqXHR._retryState.success)
            jqXHR._retryState.success(data, textStatus, jqXHR);
        jqXHR._retryState.deferred.resolve(data, textStatus, jqXHR);
    }
    function initialize() {
        $.ajaxPrefilter(ajaxPrefilter);
    }
    exports.initialize = initialize;
    function updateConnectionStatus(jqXHR) {
        if (jqXHR.status !== 0) {
            app.connection(constants.connection.connected);
        }
        else {
            app.connection(constants.connection.disconnected);
        }
    }
});

define('security/CountDown',["require", "exports"], function (require, exports) {
    var CountDown = (function () {
        function CountDown(count, callback) {
            this.callback = callback;
            this.intervalHandle = null;
            this.remaining = ko.observable(count);
            this.intervalHandle = setInterval(this.tick.bind(this), 1000);
        }
        CountDown.prototype.reset = function (count) {
            if (this.intervalHandle === null)
                this.intervalHandle = setInterval(this.tick.bind(this), 1000);
            if (this.remaining() === count)
                return;
            this.remaining(count);
        };
        CountDown.prototype.tick = function () {
            if (this.remaining() > 1) {
                this.remaining(this.remaining() - 1);
                return;
            }
            if (this.remaining() === 1) {
                clearInterval(this.intervalHandle);
                this.intervalHandle = null;
                this.remaining(0);
                this.callback();
            }
        };
        return CountDown;
    })();
    exports.CountDown = CountDown;
});

define('security/idleLock',["require", "exports", 'core/durability', 'core/util', './CountDown'], function (require, exports, durability, util, CountDownTimer) {
    var countDown, lastSlide = new Date(1900, 0, 1);
    exports.secondsUntilSessionLocks;
    function initialize() {
        if (!app.webIntake && !app.CfWebIntake) {
            countDown = new CountDownTimer.CountDown(getTimeoutSeconds(), onInactivityTimeout);
            exports.secondsUntilSessionLocks = countDown.remaining;
            $(document).on('mousemove keyup touchmove touchend', throttle(onActivity, 900));
        }
    }
    exports.initialize = initialize;
    function getTimeoutSeconds() {
        return SystemSettings.InactivityTimeout * 60;
    }
    function onActivity() {
        if (!durability.signInDialogIsShowing) {
            countDown.reset(getTimeoutSeconds());
        }
        if (moment().diff(moment(lastSlide), 'seconds') < 60)
            return;
        lastSlide = new Date();
        Q($.post(app.hostUrl + 'api/Authentication/Renew')).then(function (header) { return AuthorizationHeader.Current = header; }).fail(function (reason) {
            if (util.isConnectionFailure(reason))
                return;
            return Q.reject(reason);
        }).done();
    }
    function onInactivityTimeout() {
        AuthorizationHeader.Current = null;
        durability.displaySessionLockedMessage();
    }
    function throttle(action, rateMilliseconds) {
        var lastInvoke = null;
        return function () {
            var now = +new Date();
            if (lastInvoke !== null && now - rateMilliseconds < lastInvoke)
                return;
            lastInvoke = now;
            action();
        };
    }
});

define('afterLoginBootstrapper',["require", "exports", 'entities/api', 'core/lookups', 'entities/sync', 'security/loginHistory', 'entities/softsave', 'core/util', 'assessments/screen-repo', 'security/idleLock', 'core/logger', 'security/ssoSessionHandler'], function (require, exports, entities, lookups, entitySync, loginHistory, softsave, util, screenDesignRepo, idleLock, logger, ssoSessionHandler) {
    var correlationId;
    function initialize() {
        if (app.IsSSOEnabled) {
            ssoSessionHandler.initialize();
        }
        else {
            idleLock.initialize();
        }
        app.secondsUntilSessionLocks = idleLock.secondsUntilSessionLocks;
        if (!app.CfWebIntake) {
            registerEntityTypes();
        }
        entities.registerMetadataStoreInitializer('Consumers', function (metadataStore) {
            registerValidators(metadataStore);
        });
        var softSaveInit = softsave.SoftSaveManager.loadState();
        if (app.webIntake) {
            softSaveInit.then(screenDesignRepo.syncConstants).done();
        }
        else if (!app.CfWebIntake) {
            softSaveInit.then(screenDesignRepo.initialize).then(entitySync.sync).then(loginHistory.update).done();
        }
        var appWasPreviouslyOffline = Q(localforage.getItem('isOffline')).then(function (value) {
            if (value) {
                app.isOffline(value);
            }
            else {
                app.isOffline(false);
                localforage.setItem('isOffline', false);
            }
        });
        return Q.all([softSaveInit, lookups.bootstrap(), appWasPreviouslyOffline]);
    }
    exports.initialize = initialize;
    function registerEntityTypes() {
        var reponseCtor = function (entityPrototype) {
            entityPrototype.isAnswered = function () {
                var r = entityPrototype, a = r.Assessment();
                var isAnswered = !isNullOrEmpty(r.Item()) || a && a.Medications && a.Medications() && util.Arrays.any(a.Medications(), function (m) { return m.ScreenScaleID() === r.ScaleID(); }) || a && a.Relations && a.Relations() && util.Arrays.any(a.Relations(), function (m) { return m.ScreenScaleID() === r.ScaleID(); });
                return isAnswered;
            };
        };
        var assessmentCtor = function (entityPrototype) {
            entityPrototype.files = ko.observable('[]');
        };
        if (security.canAccessPage('Demographics') && security.canAccessPage('ConsumerAssessments')) {
            entities.registerRootType({
                name: entities.entityTypes.DEMOGRAPHIC,
                controllerName: 'Consumers',
                getTitle: function (entity) { return '#' + entity.CASENO().toString(10) + ' - ' + (entity.CONTACT().LASTNAME().trim() + ', ' + entity.CONTACT().FIRSTNAME().trim() + ' ' + (entity.CONTACT().MIDDLENAME() || '')).trim(); },
                initialize: function (entity, entityFactory) {
                    entity.CONTACT(entityFactory(entity, 'CONTACT'));
                },
                loadById: function (id, q) { return q.from('Consumers').withParameters({ caseno: id }).orderBy('CASENO'); },
                icon: 'glyphicon glyphicon-user',
                moduleId: 'assessments/assessment-owner',
                singularName: 'Consumer',
                assessmentType: entities.entityTypes.ConsumerAssessment,
                pageName: 'Demographics',
            });
            entities.registerType({
                name: entities.entityTypes.CONTACT,
                initialize: function (entity, entityFactory) {
                },
                singularName: 'Contact',
                getTitle: function (entity) { return 'Contact'; }
            });
            entities.registerRootType({
                name: entities.entityTypes.ConsumerAssessment,
                controllerName: 'Consumers',
                getTitle: function (entity) { return entity['ownerTitle'] + ' - ' + entity.Assessment() + ' - ' + moment(entity.ReviewDate()).format('l'); },
                initialize: initializeConsumerAssessment,
                loadById: function (id, q) { return q.from('Assessments').withParameters({ assessid: id }).orderBy('AssessmentID'); },
                deleteById: function (id) { return util.deleteById(id, 'Consumers/DeleteAssessment'); },
                icon: 'glyphicon glyphicon-list-alt',
                moduleId: 'assessments/assessment',
                singularName: security.getPageLabel('ConsumerAssessments'),
                adderModuleId: 'assessments/new',
                copierModuleId: 'assessments/copy',
                pageName: 'ConsumerAssessments',
                beforeSave: function (em) {
                    correlationId = Math.random().toString(36).substr(2, 9).toUpperCase();
                    logger.logInfo('Client : BeforeSave has started. CorrelationId : ' + correlationId);
                    em.entity.DateTimeStamp(new Date());
                    em.entity.Responses().filter(function (r) { return !r.entityAspect.entityState.isDetached(); }).forEach(function (r) {
                        if (r.entityAspect.entityState.isModified()) {
                            r.DateTimeStamp(new Date());
                            return;
                        }
                        r.entityAspect.setModified();
                    });
                    em.entity.Medications().filter(function (r) { return !r.entityAspect.entityState.isDetached(); }).forEach(function (r) {
                        if (r.entityAspect.entityState.isModified()) {
                            return;
                        }
                        r.entityAspect.setModified();
                    });
                    em.entity.Relations().filter(function (r) { return !r.entityAspect.entityState.isDetached(); }).forEach(function (r) {
                        if (r.entityAspect.entityState.isModified()) {
                            return;
                        }
                        r.entityAspect.setModified();
                    });
                    return Q.resolve(null);
                },
                afterSave: function (em, saveResult) {
                    em.getChanges().filter(function (x) { return x.entityAspect.entityState.isDeleted(); }).forEach(function (x) { return x.entityAspect.acceptChanges(); });
                    logger.logInfo('Client : AfterSave has completed. CorrelationId : ' + correlationId);
                    return Q.resolve(null);
                },
                getIsReadOnly: function (entity) { return entity.entityAspect.entityState.isUnchanged() && security.likeComplete(entity.Status()); }
            });
            entities.registerEntityTypeCtor(entities.entityTypes.ConsumerAssessment, assessmentCtor);
            entities.registerDisplayType({
                rootEntityType: entities.entityTypes.ConsumerAssessment,
                name: entities.displayTypes.assessmentListItem,
                getTitle: function (entity) { return entity.Assessment + ' - ' + moment(entity.ReviewDate).format('l'); },
                singularName: security.getPageLabel('ConsumerAssessments'),
                getKey: function (entity) {
                    return entity.EntityID;
                },
                deleteMetadata: {
                    promptReplacements: function (entity) {
                        return [entity.Assessment + ' - ' + moment(entity.ReviewDate).format('l')];
                    }
                }
            });
            entities.registerType({
                name: entities.entityTypes.ConsumerAssessmentResponse,
                getTitle: function (entity) { return 'Response'; },
                initialize: function (entity) {
                },
                singularName: 'Response'
            });
            entities.registerEntityTypeCtor(entities.entityTypes.ConsumerAssessmentResponse, reponseCtor);
            entities.registerType({
                name: entities.entityTypes.Medication,
                getTitle: function (entity) { return 'Medication'; },
                initialize: function (entity) {
                },
                singularName: 'Medication'
            });
            entities.registerEntityTypeCtor(entities.entityTypes.ConsumerAssessmentResponse, reponseCtor);
            entities.registerType({
                name: entities.entityTypes.AssessmentRelation,
                getTitle: function (entity) { return 'AssessmentRelation'; },
                initialize: function (entity) {
                },
                singularName: 'AssessmentRelation'
            });
            entities.registerEntityTypeCtor(entities.entityTypes.ConsumerAssessmentResponse, reponseCtor);
        }
        if ((app.webIntake && WebIntakeSettings.Type !== 'VendorScreen' && security.canAccessPage('Inquiry') && security.canAccessPage('Inquiries')) || (app.webIntake && WebIntakeSettings.Type === 'APSWebIntake')) {
            entities.registerRootType({
                name: entities.entityTypes.INQUIRY,
                controllerName: 'Inquiries',
                getTitle: function (entity) { return '#' + entity.INQUIRYID().toString(10) + ' - ' + moment(entity.INQDATE()).format('l') + (' - ' + entity.InquiryParticipants().filter(function (p) { return p.PrimaryYN() === 1; }).map(function (p) { return (p.LastName().trim() + ', ' + p.FirstName().trim() + ' ' + (p.MiddleName() || '')).trim(); })[0] || ''); },
                initialize: function () {
                },
                loadById: function (id, q) { return q.from('Inquiries').where('INQUIRYID', '==', id); },
                icon: 'glyphicon-pro glyphicon-pro-bug',
                moduleId: 'assessments/assessment-owner',
                singularName: security.getPageLabel('Inquiry'),
                assessmentType: entities.entityTypes.InquiryAssessment,
                pageName: 'Inquiry',
            });
            entities.registerRootType({
                name: entities.entityTypes.InquiryAssessment,
                controllerName: 'Inquiries',
                getTitle: function (entity) { return entity['ownerTitle'] + ' - ' + 'Screen Design #' + entity.ScreenDesignID().toString(10) + ' - ' + moment(entity.DocDate()).format('l'); },
                initialize: initializeInquiryAssessment,
                loadById: function (id, q) { return q.from('Assessments').where('AssessmentID', '==', id); },
                icon: 'glyphicon glyphicon-list-alt',
                moduleId: 'assessments/assessment',
                singularName: security.getPageLabel('Inquiries'),
                adderModuleId: 'assessments/new',
                pageName: 'Inquiries',
                beforeSave: function (em) {
                    em.entity.DateTimeStamp(new Date());
                    em.entity.Responses().filter(function (r) { return !r.entityAspect.entityState.isDetached(); }).forEach(function (r) {
                        if (!r.isAnswered()) {
                            r.entityAspect.setDeleted();
                            return;
                        }
                        if (r.entityAspect.entityState.isModified()) {
                            r.DateTimeStamp(new Date());
                            return;
                        }
                        r.entityAspect.setModified();
                    });
                    return Q.resolve(null);
                }
            });
            entities.registerEntityTypeCtor(entities.entityTypes.InquiryAssessment, assessmentCtor);
            entities.registerType({
                name: entities.entityTypes.InquiryAssessmentResponse,
                getTitle: function (entity) { return 'Response'; },
                initialize: function (entity) {
                },
                singularName: 'Response'
            });
            entities.registerEntityTypeCtor(entities.entityTypes.InquiryAssessmentResponse, reponseCtor);
        }
        if (app.webIntake && WebIntakeSettings.Type === 'VendorScreen' && security.canAccessPage('Provider Detail') && security.canAccessPage('ProviderAssessments')) {
            entities.registerRootType({
                name: entities.entityTypes.Vendor,
                controllerName: 'Providers',
                getTitle: function (entity) { return '#' + entity.VendorID().toString(10) + ' - ' + entity.AGENCY(); },
                initialize: function () {
                },
                loadById: function (id, q) { return q.from('Providers').where('VendorID', '==', id); },
                icon: 'glyphicon-pro glyphicon-pro-bug',
                moduleId: 'assessments/assessment-owner',
                singularName: security.getPageLabel('Provider Detail'),
                assessmentType: entities.entityTypes.VendorAssessment,
                pageName: 'Provider Detail',
            });
            entities.registerRootType({
                name: entities.entityTypes.VendorAssessment,
                controllerName: 'Providers',
                getTitle: function (entity) { return entity['ownerTitle'] + ' - ' + 'Screen Design #' + entity.ScreenDesignID().toString(10) + ' - ' + moment(entity.ReviewDate()).format('l'); },
                initialize: initializeVendorAssessment,
                loadById: function (id, q) { return q.from('Assessments').where('AssessmentID', '==', id); },
                icon: 'glyphicon glyphicon-list-alt',
                moduleId: 'assessments/assessment',
                singularName: security.getPageLabel('ProviderAssessments'),
                adderModuleId: 'assessments/new',
                pageName: 'ProviderAssessments',
                beforeSave: function (em) {
                    em.entity.DateTimeStamp(new Date());
                    em.entity.Responses().filter(function (r) { return !r.entityAspect.entityState.isDetached(); }).forEach(function (r) {
                        if (!r.isAnswered()) {
                            r.entityAspect.setDeleted();
                            return;
                        }
                        if (r.entityAspect.entityState.isModified()) {
                            r.DateTimeStamp(new Date());
                            return;
                        }
                        r.entityAspect.setModified();
                    });
                    return Q.resolve(null);
                }
            });
            entities.registerEntityTypeCtor(entities.entityTypes.VendorAssessment, assessmentCtor);
            entities.registerType({
                name: entities.entityTypes.VendorAssessmentResponse,
                getTitle: function (entity) { return 'Response'; },
                initialize: function (entity) {
                },
                singularName: 'Response'
            });
            entities.registerEntityTypeCtor(entities.entityTypes.VendorAssessmentResponse, reponseCtor);
        }
    }
    function initializeAssessment(entity, entityFactory) {
        var type = entities.getRootType(entity.entityType.name), screenDesign = security.getScreenDesignHeaders(type.pageName).filter(function (sd) { return sd.ACTIVE !== 0; })[0] || null;
        if (screenDesign) {
            entity.ScreenDesignID(screenDesign.SCREENDESIGNID);
        }
        entity.DateTimeStamp(new Date());
        setInitialValue(type.pageName, 'status', entity.Status);
    }
    function initializeInquiryAssessment(entity, entityFactory) {
        var type = entities.getRootType(entity.entityType.name);
        initializeAssessment(entity, entityFactory);
        setInitialValue(type.pageName, 'docdate', entity.DocDate);
        entity.DocBy(User.Current.UserStamp);
        setInitialValue(type.pageName, 'fundcode', entity.FundCode);
    }
    function initializeVendorAssessment(entity, entityFactory) {
        var type = entities.getRootType(entity.entityType.name);
        initializeAssessment(entity, entityFactory);
        setInitialValue(type.pageName, 'reviewdate', entity.ReviewDate);
        entity.Rater(User.Current.MemberID);
        setInitialValue(type.pageName, 'fundcode', entity.FundCode);
    }
    function initializeConsumerAssessment(entity, entityFactory) {
        var type = entities.getRootType(entity.entityType.name);
        initializeAssessment(entity, entityFactory);
        entity.Rater(User.Current.MemberID);
        setInitialValue(type.pageName, 'review', entity.Review);
        setInitialValue(type.pageName, 'reviewdate', entity.ReviewDate);
        setInitialValue(type.pageName, 'fundcode', entity.FundCode);
        setInitialValue(type.pageName, 'program', entity.Program);
    }
    function setInitialValue(pageName, dbFieldName, assign, options) {
        var lookupItems = lookups.getLookup(pageName, dbFieldName), required = security.getIsFieldRequired(pageName, dbFieldName), defaultValue = security.getFieldControlPropertyValue(pageName, dbFieldName, security.FieldControlPropertyName.DefaultValue), specialValueRegex = /^\{[^}]+\}$/;
        options = options || (lookupItems ? lookupItems.map(function (x) { return x.Description; }) : null);
        if (isNullOrEmpty(defaultValue)) {
            if (required && options && options.length === 1) {
                assign(options[0]);
            }
            return;
        }
        if (specialValueRegex.test(defaultValue)) {
            switch (defaultValue) {
                case security.DefaultValue.Today:
                    assign(util.getDate());
                    return;
                case security.DefaultValue.UserDefault:
                    assign(User.Current.DefaultFundCode);
                    return;
                case security.DefaultValue.SingleFC:
                    assign(User.Current.DefaultFundCode);
                    return;
                default:
                    throw new Error('DefaultValue \'' + defaultValue + '\' is not implemented.');
            }
        }
        if (options) {
            if (util.Arrays.any(options, function (x) { return equalsIgnoreCase(x, defaultValue); })) {
                defaultValue = util.Arrays.first(options, function (x) { return equalsIgnoreCase(x, defaultValue); });
                assign(defaultValue);
            }
            else if (required && options.length) {
                assign(options[0]);
            }
            return;
        }
        assign(defaultValue);
    }
    exports.setInitialValue = setInitialValue;
    function registerValidators(metadataStore) {
        var medicationEntityType = metadataStore.getEntityType(entities.entityTypes.Medication);
        ['MEDICATION', 'OTHERMEDICATION', 'STATUS', 'STARTDATE', 'ENDDATE', 'DOSAGE', 'FREQUENCY', 'ROUTEADMIN', 'MEDMANAGER', 'MedsObtained', 'MailOrder', 'Packaging', 'AssistanceType', 'MedicationAssistance', 'MEDMANAGEMENTBY', 'PRESCRIBEDBY', 'COMMENTS', 'Gentext1', 'Gentext2', 'Gentext3', 'Gentext4', 'MedUnit'].forEach(function (dbField) {
            if (security.getIsFieldRequired('Medications Detail', dbField) && dbField !== 'OTHERMEDICATION') {
                medicationEntityType.getProperty(dbField).validators.push(breeze.Validator.required());
            }
            medicationEntityType.getProperty(dbField).displayName = security.getFieldLabel('Medications Detail', dbField);
        });
        medicationEntityType.validators.push(new breeze.Validator('eventListResponseStartDateBeforeEndDate', function (entity, context) { return entity.STARTDATE() === null || entity.ENDDATE() === null || entity.STARTDATE().getTime() <= entity.ENDDATE().getTime(); }, { messageTemplate: 'End Date must be on or after Start Date' }));
        var assessmentRelationEntityType = metadataStore.getEntityType(entities.entityTypes.AssessmentRelation);
        assessmentRelationEntityType.getProperty('TabType').validators.push(breeze.Validator.required());
        assessmentRelationEntityType.getProperty('Relationship').validators.push(breeze.Validator.required());
        assessmentRelationEntityType.getProperty('LastName').validators.push(breeze.Validator.required());
        assessmentRelationEntityType.getProperty('FirstName').validators.push(breeze.Validator.required());
        var entityType;
        entityType = metadataStore.getEntityType(entities.entityTypes.ConsumerAssessment);
        if (security.getIsFieldRequired('ConsumerAssessments', 'review')) {
            entityType.getProperty('Review').validators.push(breeze.Validator.required());
        }
        entityType.getProperty('Review').displayName = security.getFieldLabel('ConsumerAssessments', 'review');
        if (security.getIsFieldRequired('ConsumerAssessments', 'reviewdate')) {
            entityType.getProperty('ReviewDate').validators.push(breeze.Validator.required());
        }
        entityType.getProperty('ReviewDate').displayName = security.getFieldLabel('ConsumerAssessments', 'reviewdate');
        if (security.getIsFieldRequired('ConsumerAssessments', 'fundcode')) {
            entityType.getProperty('FundCode').validators.push(breeze.Validator.required());
        }
        entityType.getProperty('FundCode').displayName = security.getFieldLabel('ConsumerAssessments', 'fundcode');
        if (security.getIsFieldRequired('ConsumerAssessments', 'status')) {
            entityType.getProperty('Status').validators.push(breeze.Validator.required());
        }
        entityType.getProperty('Status').displayName = security.getFieldLabel('ConsumerAssessments', 'status');
    }
});

define('text',{load: function(id){throw new Error("Dynamic load not allowed: " + id);}});

define('text!assessments/assessment-owner.html',[],function () { return '<section class="container-fluid rootEntityViewModel">\r\n    <div class="command-bar btn-toolbar" role="toolbar">\r\n        <div class="btn-group btn-group-sm">\r\n            <button type="button" class="btn btn-info" data-bind="click: makeAvailableOffline, visible: !isAvailableOffline()">\r\n                <span class="glyphicon glyphicon-cloud-download hidden-xs"></span>\r\n                <span data-i18n="common.makeAvailableOffline"></span>\r\n            </button>\r\n            <button type="button" class="btn" data-bind="click: removeFromDevice, visible: isAvailableOffline">\r\n                <span class="glyphicon-pro glyphicon-pro-disk-remove"></span>\r\n                <span data-i18n="common.removeFromDevice"></span>\r\n            </button>\r\n        </div>\r\n    </div>\r\n\r\n    <div class="content">\r\n        <h3 data-bind="text: type.singularName + \' \' + getTitle()"></h3>\r\n\r\n        <div class="table-responsive" data-bind="responsiveDropdown: \'\', visible: assessmentListItems().length > 0">\r\n            <table class="table table-striped table-hover">\r\n                <thead>\r\n                    <tr>\r\n                        <th>\r\n                            <a type="button" class="btn btn-info btn-sm h-grid-btn"\r\n                               data-bind="attr: { href: newAssessmentSlug }"\r\n                               href="#" data-i18n="common.new"></a>\r\n                        </th>\r\n                        <th data-bind="text: security.getFieldLabel(\'ConsumerAssessments\', \'reviewdate\')"></th>\r\n                        <th>Form</th>\r\n                        <th data-bind="text: security.getFieldLabel(\'ConsumerAssessments\', \'rater\')"></th>\r\n                        <th>Last Updated</th>\r\n                        <th data-bind="text: security.getFieldLabel(\'ConsumerAssessments\', \'status\')"></th>\r\n                    </tr>\r\n                </thead>\r\n                <tbody data-bind="foreach: assessmentListItems">\r\n                    <tr data-bind="visible: $root.shouldShowDesign(Assessment)">\r\n                        <td>\r\n                            <div class="h-grid-btn-group">\r\n                                <div class="btn-group">\r\n                                    <div class="btn-group">\r\n                                        <a class="btn btn-primary btn-sm" href="#" data-bind="attr: { href: $root.openAssessmentSlug + $data.EntityID.toString(10) }" data-i18n="common.open"></a>\r\n                                        <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">\r\n                                            <span class="caret"></span>\r\n                                        </button>\r\n                                        <ul class="dropdown-menu" role="menu">\r\n                                            <li><a href="#" data-bind="click: $root.copyAssessment.bind($root), visible: $root.canCopyAssessment.bind($root)($data)" data-i18n="common.copy"></a></li>\r\n                                            <li><a href="#" data-bind="click: $root.deleteAssessment.bind($root), visible: $root.canDeleteAssessment.bind($root)($data)" data-i18n="common.delete"></a></li>\r\n                                        </ul>\r\n                                        <span class="glyphicon glyphicon-cloud-download" data-bind="visible: $data.IsAvailableOffline()"></span>\r\n                                    </div>\r\n                                </div>\r\n                            </div>\r\n                        </td>\r\n                        <td data-bind="dateText: ReviewDate"></td>\r\n                        <td data-bind="text: Assessment"></td>\r\n                        <td data-bind="text: RaterName"></td>\r\n                        <td data-bind="dateText: DateTimeStamp, datePattern: \'MM/DD/YYYY h:mm a\'"></td>\r\n                        <td data-bind="text: Status"></td>\r\n                    </tr>\r\n                </tbody>\r\n            </table>\r\n        </div>\r\n\r\n        <div data-bind="visible: assessmentListItems().length === 0">\r\n            <table class="table table-striped table-hover table-condensed">\r\n                <thead>\r\n                    <tr>\r\n                        <th>\r\n                            <a type="button" class="btn btn-info btn-sm h-grid-btn"\r\n                               data-bind="attr: { href: newAssessmentSlug }"\r\n                               href="#" data-i18n="common.new"></a>\r\n                        </th>\r\n                    </tr>\r\n                </thead>\r\n                <tbody>\r\n                    <tr>\r\n                        <td>\r\n                            0 Assessments\r\n                        </td>\r\n                    </tr>\r\n                </tbody>\r\n            </table>\r\n        </div>\r\n\r\n    </div>\r\n</section>\r\n';});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/assessment-owner',["require", "exports", 'entities/api', 'entities/softsave', 'entities/sync', 'core/util', 'core/viewmodels', 'plugins/router', 'core/messageBox'], function (require, exports, entities, softsave, entitySync, util, viewmodels, durandalRouter, messageBox) {
    var AssessmentOwner = (function (_super) {
        __extends(AssessmentOwner, _super);
        function AssessmentOwner() {
            _super.apply(this, arguments);
            this.assessmentListItems = ko.observableArray([]);
        }
        AssessmentOwner.prototype.beforeFinishActivate = function () {
            var _this = this;
            var deferred = Q.defer();
            this.isAvailableOffline = ko.computed(function () {
                return util.Arrays.any(entitySync.versions(), function (v) { return v.ID === entities.getEntityId(_this.entity) && equalsIgnoreCase(v.Type, _this.entity.entityType.name); });
            }, this);
            this.isScreenDesignInPackage = util.Arrays.selectMany(util.Arrays.selectMany(User.Current.Roles, function (x) { return x.Role.GroupPackages; }), function (x) { return x.ConfigPackage.ScreenDesignConfigPackages; }).filter(function (x) { return x.ConfigPackage.ConfigPackageType.PackageTypeName === 'ConsumerAssessments' && x.Restricted === false; }).map(function (x) { return x.SCREENDESIGN.SCREENDESIGNNAME; }).filter(function (value, index, self) { return self.indexOf(value) === index; });
            this.openAssessmentSlug = '#' + entities.getFragment(this.entityManager) + '/' + entities.convertToShortName(this.entityManager.type.assessmentType) + '/';
            this.newAssessmentSlug = this.openAssessmentSlug + 'new';
            this.getAssessmentList().fail(function (reason) {
                if (!util.isConnectionFailure(reason)) {
                    deferred.reject(reason);
                    return Q.reject(reason);
                }
                if (!app.isOffline()) {
                    var results = entitySync.versions().filter(function (v) { return v.Type === entities.entityTypes.ConsumerAssessment && v.ParentID === entities.getEntityId(_this.entity); }).map(function (v) { return JSON.parse(v.Data); }).map(function (x) { return {
                        isUnsaved: false,
                        Assessment: x.ScreenDesignName,
                        ChapterEntityID: x.OwnerID,
                        ChapterName: '',
                        DateTimeStamp: moment(x.DateTimeStamp).toDate(),
                        EntityID: x.AssessmentID,
                        PageName: '',
                        ParentEntityID: x.OwnerID,
                        RaterName: x.Rater,
                        ReviewDate: moment(x.DateTimeStamp).toDate(),
                        Status: x.Status
                    }; });
                    _this.assessmentListItems(results);
                }
            }).then(function () {
                return entities.getUnsavedEntities(entities.entityTypes.ConsumerAssessment, entities.entityTypes.DEMOGRAPHIC, entities.getEntityId(_this.entity));
            }).then(function (unsavedEntities) {
                var items = unsavedEntities.map(function (x) { return {
                    isUnsaved: true,
                    Assessment: x.Assessment(),
                    ChapterEntityID: x.OwnerID(),
                    ChapterName: '',
                    DateTimeStamp: x.DateTimeStamp(),
                    EntityID: x.AssessmentID(),
                    PageName: '',
                    ParentEntityID: x.OwnerID(),
                    RaterName: User.Current.UserId,
                    ReviewDate: x.ReviewDate(),
                    Status: x.Status()
                }; });
                items.filter(function (item) { return !util.Arrays.any(_this.assessmentListItems(), function (x) { return x.EntityID === item.EntityID; }); }).forEach(function (item) { return _this.assessmentListItems.splice(0, 0, item); });
                _this.assessmentListItems().forEach(function (x) {
                    var id = x.EntityID, typeName = entities.entityTypes.ConsumerAssessment;
                    x['IsAvailableOffline'] = ko.computed(function () {
                        return util.Arrays.any(entitySync.versions(), function (v) { return v.ID === id && equalsIgnoreCase(v.Type, typeName); });
                    }, _this);
                });
                _this.assessmentListItems.sort(function (a, b) { return util.dateComparison(a.DateTimeStamp, b.DateTimeStamp); });
                deferred.resolve(null);
            }).fail(function (reason) {
                deferred.reject(reason);
                return Q.reject(reason);
            }).done();
            return deferred.promise;
        };
        AssessmentOwner.prototype.getAssessmentList = function () {
            var _this = this;
            var deferred = Q.defer();
            var query = new breeze.EntityQuery().from('AssessmentListItems').withParameters({ ownerid: entities.getEntityId(this.entity) }).orderByDesc('ReviewDate').noTracking(true);
            if (app.isOffline()) {
                return entitySync.getClientVersions().then(function (clientVersions) {
                    var temp = clientVersions.filter(function (v) { return v.Type === entities.entityTypes.ConsumerAssessment && v.ParentID === entities.getEntityId(_this.entity); }).map(function (v) { return JSON.parse(v.Data); }).map(function (x) { return {
                        isUnsaved: false,
                        Assessment: x.ScreenDesignName,
                        ChapterEntityID: x.OwnerID,
                        ChapterName: '',
                        DateTimeStamp: moment(x.DateTimeStamp).toDate(),
                        EntityID: x.AssessmentID,
                        PageName: '',
                        ParentEntityID: x.OwnerID,
                        RaterName: x.Rater,
                        ReviewDate: moment(x.DateTimeStamp).toDate(),
                        Status: x.Status
                    }; });
                    _this.assessmentListItems(temp);
                });
            }
            else {
                return this.entityManager.executeQuery(query).then(function (queryResult) {
                    _this.assessmentListItems(queryResult.results);
                });
            }
        };
        AssessmentOwner.prototype.deleteAssessment = function (assessmentListItem) {
            var _this = this;
            entities.removeDisplayInstance(assessmentListItem, entities.displayTypes.assessmentListItem).then(function (result) {
                if (result.isCanceled) {
                    return;
                }
                var index = _this.assessmentListItems.indexOf(assessmentListItem);
                _this.assessmentListItems.splice(index, 1);
            });
        };
        AssessmentOwner.prototype.shouldShowDesign = function (designName) {
            return this.isScreenDesignInPackage.indexOf(designName) >= 0;
        };
        AssessmentOwner.prototype.canDeleteAssessment = function (assessmentListItem) {
            return security.canDeletePage('ConsumerAssessments');
        };
        AssessmentOwner.prototype.copyAssessment = function (assessmentListItem) {
            var slug = '#' + entities.getFragment(this.entityManager) + '/' + entities.convertToShortName(this.entityManager.type.assessmentType) + '/' + assessmentListItem.EntityID.toString(10) + '/copy';
            durandalRouter.navigate(slug);
        };
        AssessmentOwner.prototype.canCopyAssessment = function (assessmentListItem) {
            return true;
        };
        AssessmentOwner.prototype.makeAvailableOffline = function () {
            app.busyIndicator.setBusyLoading();
            entitySync.makeConsumerAvailableOffline(entities.getEntityId(this.entity)).fail(function (reason) {
                if (util.isConnectionFailure(reason)) {
                    messageBox.show('common.makeAvailableOffline', 'common.unableToConnect', messageBox.buttons.okOnly);
                    return;
                }
                return Q.reject(reason);
            }).finally(function () {
                app.busyIndicator.setReady();
            }).done();
        };
        AssessmentOwner.prototype.removeFromDevice = function () {
            var id = entities.getEntityId(this.entity);
            messageBox.show('common.removeFromDevice', 'common.removeFromDeviceMessage', messageBox.buttons.removeCancel, [this.type.getTitle(this.entity)]).then(function (button) {
                if (button !== messageBox.remove)
                    return;
                app.busyIndicator.setBusy($.i18n.t('common.removing'));
                return entitySync.makeConsumerUnvailableOffline(id).then(function () {
                    softsave.SoftSaveManager.removeFromUnsavedEntitiesAndRemoveNotification(id, entities.entityTypes.DEMOGRAPHIC);
                }).fail(function (reason) {
                    if (util.isConnectionFailure(reason)) {
                        messageBox.show('common.removeFromDevice', 'common.unableToConnect', messageBox.buttons.okOnly);
                        return;
                    }
                    return Q.reject(reason);
                }).finally(function () { return app.busyIndicator.setReady(); }).done();
            });
        };
        AssessmentOwner.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.isAvailableOffline.dispose();
            this.assessmentListItems().forEach(function (x) { return x['IsAvailableOffline'].dispose(); });
        };
        return AssessmentOwner;
    })(viewmodels.RootEntityViewModel);
    return AssessmentOwner;
});


define('text!assessments/assessment.html',[],function () { return '<section class="container-fluid rootEntityViewModel assessment" data-preprocess="true"\r\n         data-bind="css: { \'show-properties\': properties, \'show-narrative\': narrative, \'show-help\': help, \'show-edit-session\': editSession }">\r\n\r\n    <div class="command-bar btn-toolbar" role="toolbar">\r\n        <!-- ko compose: \'core/rootEntityCommands.html\' --><!-- /ko -->\r\n\r\n        <div class="btn-group btn-group-sm">\r\n            <button type="button" class="btn btn-info hidden-xs"\r\n                    data-bind="click: toggleEditSession, css: { toggled: editSession }">\r\n                <span class="glyphicon glyphicon-list-alt hidden-xs"></span> Details\r\n            </button>\r\n            <button type="button" class="btn btn-info hidden-xs"\r\n                    data-bind="click: toggleHistory, css: { toggled: responseHistory.active }, visible: SystemSettings.ShowResponseHistory">\r\n                <span class="glyphicon glyphicon-time hidden-xs"></span> History\r\n            </button>\r\n            <button type="button" class="btn btn-info hidden-xs"\r\n                    data-bind="click: reverseStatus, visible: isReadOnly() && (security.hasPermission(security.Permission.Administrator) || security.hasPermission(security.Permission.Supervisor))">\r\n                <span class="glyphicon-pro glyphicon-pro-undo hidden-xs"></span> Reverse Status\r\n            </button>\r\n            <button type="button" class="btn btn-info hidden-xs"\r\n                    data-bind="click: toggleProperties, css: { toggled: properties }, visible: SystemSettings.ShowProperties">\r\n                <span class="glyphicon glyphicon-cog hidden-xs"></span> Properties\r\n            </button>\r\n        </div>        \r\n    </div>\r\n\r\n    <!-- ko compose: \'core/validationSummary.html\' --><!-- /ko -->\r\n\r\n    <div class="content">\r\n\r\n        <!-- ko compose: \'assessments/data-entry.html\' --><!-- /ko -->\r\n\r\n        <div class="edit-session">\r\n            <div class="row">\r\n                <div class="col-sm-7 col-sm-offset-2" data-bind="compose: \'assessments/details.html\'">\r\n                </div>\r\n\r\n                <div class="col-sm-2">\r\n                    <button type="button" class="btn btn-primary h-width-100-percent" data-bind="click: submitEditSession" data-i18n="common.ok"></button>\r\n                    <button type="button" class="btn h-width-100-percent" data-bind="click: cancelEditSession, visible: !isReadOnly()" data-i18n="common.cancel"></button>\r\n                </div>\r\n            </div>\r\n        </div>\r\n\r\n        <div class="sidebar hidden-print hidden-xs" role="complementary">\r\n            <div class="find">\r\n                <!-- this div is to clip an artifact that only appears in IE -->\r\n                <div>\r\n                    <div class="input-group input-group-sm">\r\n                        <span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span>\r\n                        <input type="text"\r\n                               data-bind="value: findQuestion.searchString, valueUpdate: \'input\',\r\n                                          attr: { placeholder: $.i18n.t(\'assessment.findQuestion\') }"\r\n                               class="form-control"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n            </div>\r\n\r\n            <div class="nav-list-container nav-tree" data-bind="visible: !findQuestion.active() && !responseHistory.active()">\r\n                <ul class="tree nav sidenav">\r\n                    <% var viewModel = this, screenDesign = this.screenDesign, question, i; %>\r\n                    <li>\r\n                        <a href="#top" data-bind="event: { keydown: $root.triggerClickOnEnterOrSpacebar }"><%= screenDesign.SCREENDESIGNNAME %></a>\r\n                    </li>\r\n                    <% for(i = 0; i < screenDesign.SCREENQUESTIONS.length; i++) {\r\n                    question = screenDesign.SCREENQUESTIONS[i];\r\n\r\n                    if (question.CONTROLSCREENSCALE !== \'ctlHeader\' && question.CONTROLSCREENSCALE !== \'ctlInstructionalText\') continue;\r\n                    if (question.DefaultValue === \'NAV:HIDE\') continue; %>\r\n                    <li>\r\n                        <a href="#section-<%= question.SCREENSCALEID %>"\r\n                           data-bind="event: { keydown: $root.triggerClickOnEnterOrSpacebar }"><%= question.SCREENSCALE %></a>\r\n                    </li>\r\n                    <% } %>\r\n                </ul>\r\n            </div>\r\n\r\n            <div class="nav-list-container" data-bind="visible: findQuestion.active">\r\n                <label for="find-results">Find Question Results:</label>\r\n                <ul id="find-results" class="find-results nav sidenav">\r\n                    <!-- ko foreach: findQuestion.results -->\r\n                    <li data-bind="css: question.CONTROLSCREENSCALE">\r\n                        <a data-bind="click: function(result) { $root.focusQuestion(result.question, true); }, event: { keydown: $root.triggerClickOnEnterOrSpacebar }" href="#">\r\n                            <strong data-bind="html: nameHtml"></strong>\r\n                            <br />\r\n                            <small class="text-muted" data-bind="html: propertiesHtml"></small>\r\n                        </a>\r\n                    </li>\r\n                    <!-- /ko -->\r\n                    <li data-bind="visible: findQuestion.showNoResultsMessage">\r\n                        <i>No questions found.</i>\r\n                    </li>\r\n                </ul>\r\n            </div>\r\n\r\n            <div class="nav-list-container" data-bind="visible: responseHistory.active() && !findQuestion.active()">\r\n                <label for="response-history">Response History:</label>\r\n                <ul id="response-history" class="response-history nav sidenav">\r\n                    <!-- ko foreach: responseHistory.history -->\r\n                    <li>\r\n                        <a data-bind="click: function(item) {  $root.responseHistory.applyValueFromHistory(item); }, event: { keydown: $root.triggerClickOnEnterOrSpacebar }" href="#">\r\n                            <strong data-bind="text: htmlEncode(displayValue), visible: !isLocked()"></strong>\r\n                            <strong data-bind="visible: isLocked">\r\n                                <small class="glyphicon glyphicon-lock"></small>&nbsp;\r\n                                <em>[Enter assessment password]</em>\r\n                            </strong>\r\n                            <br />\r\n                            <span data-bind="text: response.LUpdateUserName"></span>\r\n                            -\r\n                            <span data-bind="dateText: response.LUpdateDateTime"></span>\r\n                            <br />\r\n                            <small class="text-muted" data-bind="text: response.Session.AssessFormName"></small>\r\n                            -\r\n                            <small class="text-muted" data-bind="dateText: response.Session.SessionDate"></small>\r\n                        </a>\r\n                    </li>\r\n                    <!-- /ko -->\r\n                    <li data-bind="visible: responseHistory.unableToLoad">\r\n                        <i class="text-danger">Unable to load response history.</i>\r\n                    </li>\r\n                    <li data-bind="visible: responseHistory.isLoading">\r\n                        <i>Loading...</i>\r\n                    </li>\r\n                    <li data-bind="visible: responseHistory.history().length === 0 && !responseHistory.unableToLoad() && !responseHistory.isLoading()">\r\n                        <i>There is no response history for this question.</i>\r\n                    </li>\r\n                </ul>\r\n            </div>\r\n\r\n            <div class="nav-commands btn-toolbar" role="toolbar">\r\n                <div class="btn-group btn-group-sm btn-group-justified">\r\n                    <div class="btn-group">\r\n                        <button type="button" class="btn"\r\n                                data-bind="click: questionFocusHistory.goBack.bind(questionFocusHistory),\r\n                                           enable: questionFocusHistory.canGoBack">\r\n                            Go Back\r\n                        </button>\r\n                    </div>\r\n                    <div class="btn-group">\r\n                        <button type="button" class="btn"\r\n                                data-bind="click: function() { gotoNextUnanswered(true); }">\r\n                            Previous<br />Unanswered\r\n                        </button>\r\n                    </div>\r\n                    <div class="btn-group">\r\n                        <button type="button" class="btn"\r\n                                data-bind="click: function() { gotoNextRequired(true); }">\r\n                            Previous<br />Required\r\n                        </button>\r\n                    </div>\r\n                </div>\r\n                <div class="btn-group btn-group-sm btn-group-justified">\r\n                    <div class="btn-group">\r\n                        <button type="button" class="btn"\r\n                                data-bind="click: questionFocusHistory.goForward.bind(questionFocusHistory),\r\n                                           enable: questionFocusHistory.canGoForward">\r\n                            Go Forward\r\n                        </button>\r\n                    </div>\r\n                    <div class="btn-group">\r\n                        <button type="button" class="btn"\r\n                                data-bind="click: function() { gotoNextUnanswered(false); }">\r\n                            Next<br />Unanswered\r\n                        </button>\r\n                    </div>\r\n                    <div class="btn-group">\r\n                        <button type="button" class="btn"\r\n                                data-bind="click: function() { gotoNextRequired(false); }">\r\n                            Next<br />Required\r\n                        </button>\r\n                    </div>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</section>\r\n';});

define('assessments/consumer-mapper',["require", "exports", 'assessments/scales', 'core/util'], function (require, exports, scales, util) {
    function mapToAssessment(consumer, assessmentEntityManager, screenDesign) {
        var d = scales.DemographicField, e = scales.EnrollmentField, assessmentID = assessmentEntityManager.entity.AssessmentID(), ca = assessmentEntityManager.entity;
        var enrollment = security.getEnrollmentOfOpenCloseForVendor(consumer, ca.OpenCloseID(), ca.Program());
        function fillResponse(question, value) {
            if (isNullOrEmpty(value)) {
                return;
            }
            if (value instanceof Date) {
                value = moment(value).format('MM/DD/YYYY');
            }
            assessmentEntityManager.createChildEntity(assessmentEntityManager.entity, 'Responses', {
                ScaleID: question.SCREENSCALEID,
                QuestionID: question.QUESTIONID,
                Scale: question.SCREENSCALE,
                DateTimeStamp: new Date(),
                UserStamp: User.Current.UserStamp,
                Item: value.toString()
            });
        }
        screenDesign.SCREENQUESTIONS.filter(function (q) { return equalsIgnoreCase(q.CONTROLSCREENSCALE, scales.keys.ctlDemographicDataLookup); }).forEach(function (q) {
            switch (q.DemographicLookupField) {
                case d.ADDRESSTYPE:
                    fillResponse(q, consumer.CONTACT().ADDRESSTYPE());
                    break;
                case d.StudentWithADisability:
                    fillResponse(q, consumer.StudentWithADisability());
                    break;
                case d.IndividualWithADisability:
                    fillResponse(q, consumer.IndividualWithADisability());
                    break;
                case d.PrimaryDisabilityType:
                    fillResponse(q, consumer.PrimaryDisabilityType());
                    break;
                case d.PrimaryDisabilitySource:
                    fillResponse(q, consumer.PrimaryDisabilitySource());
                    break;
                case d.SecondaryDisabilityType:
                    fillResponse(q, consumer.SecondaryDisabilityType());
                    break;
                case d.SecondaryDisabilitySource:
                    fillResponse(q, consumer.SecondaryDisabilitySource());
                    break;
                case d.SignificanceOfDisability:
                    fillResponse(q, consumer.SignificanceOfDisability());
                    break;
                case d.DegreeOfVisualImpairment:
                    fillResponse(q, consumer.DegreeOfVisualImpairment());
                    break;
                case d.MajorCauseOfVisualImpairment:
                    fillResponse(q, consumer.MajorCauseOfVisualImpairment());
                    break;
                case d.OtherAgeRelatedImpairments:
                    fillResponse(q, consumer.OtherAgeRelatedImpairments());
                    break;
                case d.MultiRace:
                    fillResponse(q, consumer.CONTACT().MultiRace());
                    break;
                case d.AGE:
                    if (consumer.CONTACT().DOB()) {
                        fillResponse(q, util.getAge(util.removeOffsetFromDate(consumer.CONTACT().DOB())));
                    }
                    break;
                case d.ALIAS:
                    fillResponse(q, consumer.CONTACT().ALIAS());
                    break;
                case d.CELLPHONE:
                    fillResponse(q, consumer.CONTACT().CELLPHONE());
                    break;
                case d.CITIZENSHIP:
                    fillResponse(q, consumer.CONTACT().CITIZENSHIP());
                    break;
                case d.CITY:
                    fillResponse(q, consumer.CONTACT().CITY());
                    break;
                case d.CURMARSTATUS:
                    fillResponse(q, consumer.CONTACT().CURMARSTATUS());
                    break;
                case d.DescriptiveAddress:
                    break;
                case d.DOB:
                    fillResponse(q, util.removeOffsetFromDate(consumer.CONTACT().DOB()));
                    break;
                case d.EMAIL:
                    fillResponse(q, consumer.CONTACT().EMAIL());
                    break;
                case d.ETHNICITYLOOKUP:
                    fillResponse(q, consumer.CONTACT().ETHNICITYLOOKUP());
                    break;
                case d.FAMILYSIZE:
                    fillResponse(q, consumer.CONTACT().FAMILYSIZE());
                    break;
                case d.FIRSTNAME:
                    fillResponse(q, consumer.CONTACT().FIRSTNAME());
                    break;
                case d.GENDER:
                    fillResponse(q, consumer.CONTACT().GENDER());
                    break;
                case d.LASTNAME:
                    fillResponse(q, consumer.CONTACT().LASTNAME());
                    break;
                case d.MedicareID:
                    fillResponse(q, consumer.MedicareID());
                    break;
                case d.MIDDLENAME:
                    fillResponse(q, consumer.CONTACT().MIDDLENAME());
                    break;
                case d.PHONE:
                    fillResponse(q, consumer.CONTACT().PHONE());
                    break;
                case d.PLANGUAGE:
                    fillResponse(q, consumer.CONTACT().PLANGUAGE());
                    break;
                case d.RACE:
                    fillResponse(q, consumer.CONTACT().RACE());
                    break;
                case d.REFERRALSOURCE:
                    fillResponse(q, consumer.REFERRALSOURCE());
                    break;
                case d.RESCOUNTY:
                    fillResponse(q, consumer.CONTACT().RESCOUNTY());
                    break;
                case d.RESIDENCETYPE:
                    fillResponse(q, consumer.CONTACT().RESIDENCETYPE());
                    break;
                case d.SALUTATION:
                    fillResponse(q, consumer.CONTACT().SALUTATION());
                    break;
                case d.SECID:
                    fillResponse(q, consumer.SECID());
                    break;
                case d.SSN:
                    fillResponse(q, consumer.CONTACT().SSN());
                    break;
                case d.STATE:
                    fillResponse(q, consumer.CONTACT().STATE());
                    break;
                case d.STREET:
                    fillResponse(q, consumer.CONTACT().STREET());
                    break;
                case d.STREET2:
                    fillResponse(q, consumer.CONTACT().STREET2());
                    break;
                case d.Suffix:
                    fillResponse(q, consumer.CONTACT().Suffix());
                    break;
                case d.VeteranStatus:
                    fillResponse(q, consumer.CONTACT().VeteranStatus());
                    break;
                case d.WORKPHONE:
                    fillResponse(q, consumer.CONTACT().WORKPHONE());
                    break;
                case d.ZIPCODE:
                    fillResponse(q, consumer.CONTACT().ZIPCODE());
                    break;
            }
        });
        if (enrollment) {
            screenDesign.SCREENQUESTIONS.filter(function (q) { return equalsIgnoreCase(q.CONTROLSCREENSCALE, scales.keys.ctlEnrollmentDataLookup); }).forEach(function (q) {
                switch (q.EnrollmentLookupField) {
                    case e.ADMITDATE:
                        fillResponse(q, enrollment.ADMITDATE());
                        break;
                    case e.DateOfEligibilityDetermination:
                        fillResponse(q, enrollment.DateOfEligibilityDetermination());
                        break;
                    case e.EligibilityDeterminationExtension:
                        fillResponse(q, enrollment.EligibilityDeterminationExtension());
                        break;
                    case e.MedicalInsuranceCoverageAtApplication:
                        fillResponse(q, enrollment.MedicalInsuranceCoverageAtApplication());
                        break;
                    case e.MonthlyPublicSupportAtApplication:
                        fillResponse(q, enrollment.MonthlyPublicSupportAtApplication());
                        break;
                    case e.ReferralSource:
                        fillResponse(q, enrollment.ReferralSource());
                        break;
                }
            });
        }
    }
    exports.mapToAssessment = mapToAssessment;
});


define('text!assessments/controls/copy-address-from-list.html',[],function () { return '﻿<div class="modal-content">\r\n    <div class="modal-header">\r\n        <div class="row">\r\n            <div class="col-sm-6 col-md-9">\r\n                <h5>Copy Address From</h5>\r\n            </div>\r\n\r\n        </div>\r\n    </div>\r\n    <div class="modal-body">\r\n        <div class="table-responsive" style="max-height: 500px; overflow-y: auto">\r\n            <table class="table table-striped table-bordered table-hover table-condensed w-auto small">\r\n                <thead style="background: #3498db;color: white; text-align:left;vertical-align:top">\r\n                    <tr>\r\n                        <th style="vertical-align:top;font-size:small;color:white;white-space: nowrap;font-weight:normal">First Name</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">Last Name</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">Participant Type</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">Street Address</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">Apartment/PO Box No</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">City</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">State</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">County</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">ZipCode</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">Home Phone</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">Cell Phone</th>\r\n                        <th style="vertical-align:top;font-size:small;white-space: nowrap;font-weight:normal">Work Phone</th>\r\n                    </tr>\r\n                </thead>\r\n                <tbody data-bind="if: participantsAddressData().length === 0">\r\n                    <tr>\r\n                        <td colspan="12">No records to display.</td>\r\n                    </tr>\r\n                </tbody>\r\n                <tbody data-bind="foreach: participantsAddressData">\r\n                    <tr style="cursor: pointer" tabindex="-1" data-bind="click: $root.addressSelected">\r\n                        <td data-bind="text: FirstName" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: LastName" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: ParticipantType" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: Street" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: Street2" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: City" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: State" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: County" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: ZipCode" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: HomePhone" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: CellPhone" style="white-space: nowrap;font-size:16px"></td>\r\n                        <td data-bind="text: WorkPhone" style="white-space: nowrap;font-size:16px"></td>\r\n                    </tr>\r\n                </tbody>\r\n            </table>\r\n        </div>\r\n    </div>\r\n    <div class="modal-footer">\r\n        <div >\r\n            <div >\r\n                <div >\r\n                    <button type="button" class="btn" data-bind="click: cancel" data-i18n="common.cancel"></button>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</div>\r\n ';});


define('text!assessments/controls/medication-list-control.html',[],function () { return '<div data-preprocess="true">\r\n    <div class="form-control h-complex-form-control h-complex-form-control-modal" data-preprocess="true">\r\n        <div class="table-responsive" data-bind="visible: entities().length">\r\n            <table class="table table-striped table-hover table-condensed">\r\n                <thead>\r\n                    <tr>\r\n                        <th>\r\n                            <% if (this.screenDesignIsReadOnly) { %>\r\n                            <button tabindex="0" type="button" disabled="disabled" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: add">\r\n                                <span class="glyphicon glyphicon-plus"></span> <span data-i18n="common.new"></span>\r\n                            </button>\r\n                            <button tabindex="0" type="button" disabled="disabled" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: search">\r\n                                <span class="glyphicon glyphicon-link"></span> <span data-i18n="common.attach"></span>\r\n                            </button>\r\n                            <% } else if (!this.screenDesignIsReadOnly) { %>\r\n                            <button tabindex="0" type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: add">\r\n                                <span class="glyphicon glyphicon-plus"></span> <span data-i18n="common.new"></span>\r\n                            </button>\r\n                            <button tabindex="0" type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: search">\r\n                                <span class="glyphicon glyphicon-link"></span> <span data-i18n="common.attach"></span>\r\n                            </button>\r\n                            <% } %>\r\n                        </th>\r\n\r\n                        <!-- ko foreach: visibleColumnsMedication -->\r\n                        <th data-bind="text: $data"></th>\r\n                        <!-- /ko -->\r\n                    </tr>\r\n                </thead>\r\n                \r\n                <tbody data-bind="foreach: {data: entities, as: \'entity\'}">\r\n                    <tr>\r\n                        <td>\r\n                            <% if (this.screenDesignIsReadOnly) { %>\r\n                            <div class="btn-toolbar" role="toolbar">\r\n                                <div class="btn-group">\r\n                                    <button tabindex="0" type="button" disabled="disabled" class="btn btn-primary btn-xs h-add-open-delete-button" data-bind="click: $parent.open.bind($parent)">\r\n                                        <span class="glyphicon glyphicon-folder-open"></span> <span data-i18n="common.open"></span>\r\n                                    </button>\r\n                                </div>\r\n\r\n                                <div class="btn-group">\r\n                                    <button tabindex="0" type="button" disabled="disabled" class="btn btn-primary btn-xs h-add-open-delete-button" data-bind="click: $parent.remove.bind($parent)">\r\n                                        <span class="glyphicon glyphicon-trash"></span> <span data-i18n="common.delete"></span>\r\n                                    </button>\r\n                                </div>\r\n                            </div>\r\n                            <% } else if (!this.screenDesignIsReadOnly) { %>\r\n                            <div class="btn-toolbar" role="toolbar">\r\n                                <div class="btn-group">\r\n                                    <button tabindex="0" type="button" class="btn btn-primary btn-xs h-add-open-delete-button" data-bind="click: $parent.open.bind($parent)">\r\n                                        <span class="glyphicon glyphicon-folder-open"></span> <span data-i18n="common.open"></span>\r\n                                    </button>\r\n                                </div>\r\n\r\n                                <div class="btn-group">\r\n                                    <button tabindex="0" type="button" class="btn btn-primary btn-xs h-add-open-delete-button" data-bind="click: $parent.remove.bind($parent)">\r\n                                        <span class="glyphicon glyphicon-trash"></span> <span data-i18n="common.delete"></span>\r\n                                    </button>\r\n                                </div>\r\n                            </div>\r\n                            <% } %>\r\n                        </td>\r\n                        <!-- ko foreach: { data: $root.visibleColumnsMedicationHeader, as : \'column\' } -->\r\n                        <!-- ko if: column === \'STARTDATE\' || column === \'ENDDATE\'-->\r\n                        <td data-bind="dateText: entity[column]"></td>\r\n                        <!-- /ko -->\r\n                        <!-- ko if: column === \'MEDMANAGEMENTBY\' -->\r\n                        <td data-bind="text: $root.getWorkersName(entity[column]())"></td>\r\n                        <!-- /ko -->\r\n                        <!-- ko if: column === \'OtherMedication\' -->\r\n                        <td data-bind="text: $root.medicationIsOther(entity)"></td>\r\n                        <!-- /ko -->\r\n                        <!-- ko ifnot: column === \'STARTDATE\' || column === \'ENDDATE\' || column === \'MEDMANAGEMENTBY\' || column === \'OtherMedication\' -->\r\n                        <td data-bind="text: entity[column]"></td>\r\n                        <!-- /ko -->\r\n                        <!-- /ko -->\r\n                    </tr>\r\n                </tbody>\r\n            </table>\r\n        </div>     \r\n        <div data-bind="visible: entities().length === 0">\r\n            <table class="table table-striped table-hover table-condensed">\r\n                <thead>\r\n                    <tr>\r\n                        <th>\r\n                            <% if (this.screenDesignIsReadOnly) { %>\r\n                            <button type="button" disabled="disabled" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: add">\r\n                                <span class="glyphicon glyphicon-plus"></span> <span data-i18n="common.new"></span>\r\n                            </button>\r\n                            <button tabindex="0" type="button" disabled="disabled" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: search">\r\n                                <span class="glyphicon glyphicon-link"></span> <span data-i18n="common.attach"></span>\r\n                            </button>\r\n                            <% } else if (!this.screenDesignIsReadOnly) { %>\r\n                            <button type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: add">\r\n                                <span class="glyphicon glyphicon-plus"></span> <span data-i18n="common.new"></span>\r\n                            </button>\r\n                            <button tabindex="0" type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: search">\r\n                                <span class="glyphicon glyphicon-link"></span> <span data-i18n="common.attach"></span>\r\n                            </button>\r\n                            <% } %>\r\n                        </th>\r\n                    </tr>\r\n                </thead>\r\n                <tbody>\r\n                    <tr>\r\n                        <td>\r\n                            <span data-i18n="common.empty"></span>\r\n                        </td>\r\n                    </tr>\r\n                </tbody>\r\n            </table>\r\n        </div>\r\n    </div>\r\n\r\n    <div class="modal" tabindex="-1" role="dialog" data-bind="modal: showSearch">\r\n        <div class="modal-dialog modal-lg">\r\n            <div class="modal-content messageBox">\r\n                <div class="modal-header">\r\n                    <button type="button" class="close" data-bind="click: hideSearch" aria-label="Close"><span aria-hidden="true">&times;</span></button>\r\n                    <h3 class="modal-title">Medication list</h3>\r\n                </div>\r\n                <div class="modal-body">\r\n                    <div class="form-control h-complex-form-control h-complex-form-control-modal">                    \r\n                        <div class="table-responsive" data-bind="visible: medicationReviews().length > 0">\r\n                            <table class="table table-striped table-hover table-condensed">\r\n                                <thead>\r\n                                    <tr>\r\n                                        <th></th>\r\n                                        <th>Review ID</th>\r\n                                        <th>Medication</th>\r\n                                        <th>Dosage</th>\r\n                                        <th>Frequency</th>\r\n                                        <th>Route Admin</th>\r\n                                        <th>Start Date</th>\r\n                                        <th>End Date</th>\r\n                                        <th>Status</th>\r\n                                    </tr>\r\n                                </thead>\r\n                                <tbody data-bind="foreach: medicationReviews">\r\n                                    <tr>\r\n                                        <td>\r\n                                            <div class="btn-toolbar" role="toolbar">\r\n                                                <div class="btn-group">\r\n                                                    <button tabindex="0" type="button" class="btn btn-primary btn-xs h-add-open-delete-button" data-bind="click: $parent.select.bind($parent, this)">\r\n                                                        <span class="glyphicon glyphicon-ok"></span> <span data-i18n="common.select"></span>\r\n                                                    </button>\r\n                                                </div>\r\n                                            </div>\r\n                                        </td>\r\n                                        <td data-bind="text: MEDICATIONREVIEWID"></td>\r\n                                        <td data-bind="text: MEDICATION"></td>\r\n                                        <td data-bind="text: DOSAGE"></td>\r\n                                        <td data-bind="text: FREQUENCY"></td>\r\n                                        <td data-bind="text: ROUTEADMIN"></td>\r\n                                        <td data-bind="dateText: STARTDATE"></td>\r\n                                        <td data-bind="dateText: ENDDATE"></td>\r\n                                        <td data-bind="text: STATUS"></td>\r\n                                    </tr>\r\n                                </tbody>\r\n                            </table>\r\n                        </div>\r\n                        <div data-bind="visible: medicationReviews().length === 0">\r\n                            <table class="table table-striped table-hover table-condensed">\r\n                                <thead>\r\n                                    <tr>\r\n                                        <th>\r\n                                        </th>\r\n                                    </tr>\r\n                                </thead>\r\n                                <tbody>\r\n                                    <tr>\r\n                                        <td>\r\n                                            <span data-i18n="common.empty"></span>\r\n                                        </td>\r\n                                    </tr>\r\n                                </tbody>\r\n                            </table>\r\n                        </div>\r\n                    </div>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</div>';});


define('text!assessments/controls/medication.html',[],function () { return '<div class="modal-content messageBox">\r\n    <div class="modal-header">\r\n        <h3>Medication</h3>\r\n    </div>\r\n    <div class="modal-body">\r\n\r\n        <!-- ko compose: \'core/validationSummary.html\' --><!-- /ko -->\r\n\r\n        <form class="form-horizontal" data-bind="submit: submit" role="form" novalidate>\r\n            <div class="row">\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'MEDICATION\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'MEDICATION\') }">\r\n                    <label for="medicationInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'MEDICATION\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <input type="text" class="form-control input-sm autofocus" id="medicationInput"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="false"\r\n                               maxlength="80"\r\n                               data-bind="value: entity.MEDICATION, valueUpdate: \'input\',\r\n                                          validateField: \'MEDICATION\',\r\n                                          disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'MEDICATION\', entity),\r\n                                          typeahead: { items: 15, autoSelect: true, source: medication }" />\r\n                    </div>\r\n                </div>\r\n                <div class="form-group col-md-6"\r\n                     data-bind="if: (shouldFieldShow && entity.MEDICATION() === \'Other\' && !security.getFieldVisible(\'Medications Detail\', \'OTHERMEDICATION\')),\r\n                                css: { required: security.getFieldRequired(\'Medications Detail\', \'MEDICATION\') }">\r\n                    <label for="OTHERMEDICATIONInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'OTHERMEDICATION\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <input type="text" class="form-control input-sm " id="OTHERMEDICATIONInput"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="false"\r\n                               maxlength="80"\r\n                               data-bind="value: entity.OTHERMEDICATION, valueUpdate: \'input\',\r\n                                          validateField: \'OTHERMEDICATION\',\r\n                                          disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'OTHERMEDICATION\', entity)" />\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'STATUS\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'STATUS\') }">\r\n                    <label for="statusInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'STATUS\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <select class="form-control input-sm" id="statusInput" data-bind="options: status,\r\n                           optionsValue: \'Description\',\r\n                           optionsText: \'Description\',\r\n                           value: entity.STATUS,\r\n                           css: { blank: isNullOrEmpty(entity.STATUS()) },\r\n                           validateField: \'STATUS\',\r\n                           optionsCaption: \'Choose...\',\r\n                           disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'STATUS\', entity)"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'STARTDATE\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'STARTDATE\') }">\r\n                    <label for="startDateInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'STARTDATE\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <div class="input-group input-group-sm">\r\n                            <span class="input-group-btn">\r\n                                <button tabindex="-1" class="btn" type="button" data-bind="disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'STARTDATE\', entity)">\r\n                                    <span class="glyphicon glyphicon-th"></span>\r\n                                </button>\r\n                            </span>\r\n                            <input class="form-control" id="startDateInput" spellcheck="false" type="text" min="1/1/1850" max="12/31/2250" placeholder="Enter Start Date"\r\n                                   data-bind="dateValue: entity.STARTDATE, validateField: \'STARTDATE\', nullable: true, disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'STARTDATE\', entity)" autocapitalize="off" autocorrect="off" autocomplete="off">\r\n                        </div>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'ENDDATE\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'ENDDATE\') }">\r\n                    <label for="endDateInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'ENDDATE\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <div class="input-group input-group-sm">\r\n                            <span class="input-group-btn">\r\n                                <button tabindex="-1" class="btn" type="button" data-bind="disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'ENDDATE\', entity)">\r\n                                    <span class="glyphicon glyphicon-th"></span>\r\n                                </button>\r\n                            </span>\r\n                            <input class="form-control" id="endDateInput" spellcheck="false" type="text" min="1/1/1850" max="12/31/2250" placeholder="Enter End Date"\r\n                                   data-bind="dateValue: entity.ENDDATE, validateField: \'ENDDATE\', nullable: true, disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'ENDDATE\', entity)" autocapitalize="off" autocorrect="off" autocomplete="off">\r\n                        </div>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'DOSAGE\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'DOSAGE\') }">\r\n                    <label for="dosageInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'DOSAGE\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <!-- ko if: dosageIsText -->\r\n                        <input class="form-control input-sm" id="dosageInput" type="text" placeholder="Enter dosage"\r\n                               data-bind="value: entity.DOSAGE, autocapitalize: true, validateField: \'DOSAGE\', disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'DOSAGE\', entity)"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                        <!-- /ko -->\r\n                        <!-- ko if: !dosageIsText -->\r\n                        <input class="form-control input-sm" id="dosageInput" type="text" placeholder="Enter dosage"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"\r\n                               min="0" max="99999.99"\r\n                               data-bind="numberValue: entity.DOSAGE, nullable: true, validateField: \'DOSAGE\', disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'DOSAGE\', entity)">\r\n                        <!-- /ko -->\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'MedUnit\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'MedUnit\') }">\r\n                    <label for="MedUnitInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'MedUnit\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <select class="form-control input-sm" id="MedUnitInput" data-bind="options: MedUnit,\r\n                            optionsValue: \'Description\',\r\n                            optionsText: \'Description\',\r\n                            value: entity.MedUnit,\r\n                            css: { blank: isNullOrEmpty(entity.MedUnit()) },\r\n                            validateField: \'MedUnit\',\r\n                            optionsCaption: \'Choose...\',\r\n                            disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'MedUnit\', entity)"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'FREQUENCY\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'FREQUENCY\') }">\r\n                    <label for="frequencyInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'FREQUENCY\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <input class="form-control input-sm" id="frequencyInput" type="text" placeholder="Enter frenquency"\r\n                               data-bind="value: entity.FREQUENCY, autocapitalize: true, validateField: \'FREQUENCY\', disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'FREQUENCY\', entity), visible: !frequencyIsLookup"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                        <select class="form-control input-sm" id="frequencyInput" data-bind="options: frequency,\r\n                            optionsValue: \'Description\',\r\n                            optionsText: \'Description\',\r\n                            value: entity.FREQUENCY,\r\n                            css: { blank: isNullOrEmpty(entity.FREQUENCY()) },\r\n                            validateField: \'FREQUENCY\',\r\n                            optionsCaption: \'Choose...\',\r\n                            disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'FREQUENCY\', entity),\r\n                            visible: frequencyIsLookup"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'ROUTEADMIN\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'ROUTEADMIN\') }">\r\n                    <label for="routeOfAdministrationInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'ROUTEADMIN\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <select class="form-control input-sm" id="routeOfAdministrationInput" data-bind="options: routeOfAdministration,\r\n                            optionsValue: \'Description\',\r\n                            optionsText: \'Description\',\r\n                            value: entity.ROUTEADMIN,\r\n                            css: { blank: isNullOrEmpty(entity.ROUTEADMIN()) },\r\n                            validateField: \'ROUTEADMIN\',\r\n                            optionsCaption: \'Choose...\',\r\n                            disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'ROUTEADMIN\', entity)"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'MEDMANAGER\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'MEDMANAGER\') }">\r\n                    <label for="medicationManagerInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'MEDMANAGER\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <input class="form-control input-sm" id="medicationManagerInput" type="text" placeholder="Enter medication manager"\r\n                               data-bind="value: entity.MEDMANAGER, autocapitalize: true, validateField: \'MEDMANAGER\', disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'MEDMANAGER\', entity), visible: !medmanagerIsLookup"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                        <select class="form-control input-sm" id="medicationManagerInput" data-bind="options: medmanager,\r\n                            optionsValue: \'Description\',\r\n                            optionsText: \'Description\',\r\n                            value: entity.MEDMANAGER,\r\n                            css: { blank: isNullOrEmpty(entity.MEDMANAGER()) },\r\n                            validateField: \'MEDMANAGER\',\r\n                            optionsCaption: \'Choose...\',\r\n                            disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'MEDMANAGER\', entity),\r\n                            visible: medmanagerIsLookup"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'MedsObtained\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'MedsObtained\') }">\r\n                    <label for="whereObtainedInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'MedsObtained\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <select class="form-control input-sm" id="whereObtainedInput" data-bind="options: whereObtained,\r\n                       optionsValue: \'Description\',\r\n                       optionsText: \'Description\',\r\n                       value: entity.MedsObtained,\r\n                       css: { blank: isNullOrEmpty(entity.MedsObtained()) },\r\n                       validateField: \'MedsObtained\',\r\n                       optionsCaption: \'Choose...\',\r\n                       disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'MedsObtained\', entity)"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'MailOrder\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'MailOrder\') }">\r\n                    <label for="mailOrderInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'MailOrder\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <select class="form-control input-sm" id="mailOrderInput" data-bind="options: mailOrder,\r\n                       optionsValue: \'Description\',\r\n                       optionsText: \'Description\',\r\n                       value: entity.MailOrder,\r\n                       css: { blank: isNullOrEmpty(entity.MailOrder()) },\r\n                       validateField: \'MailOrder\',\r\n                       optionsCaption: \'Choose...\',\r\n                       disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'MailOrder\', entity)"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'Packaging\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'Packaging\') }">\r\n                    <label for="packagingInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'Packaging\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <select class="form-control input-sm" id="packagingInput" data-bind="options: packaging,\r\n                       optionsValue: \'Description\',\r\n                       optionsText: \'Description\',\r\n                       value: entity.Packaging,\r\n                       css: { blank: isNullOrEmpty(entity.Packaging()) },\r\n                       validateField: \'Packaging\',\r\n                       optionsCaption: \'Choose...\',\r\n                       disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'Packaging\', entity)"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'AssistanceType\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'AssistanceType\') }">\r\n                    <label for="typeOfAssistanceInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'AssistanceType\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <select class="form-control input-sm" id="typeOfAssistanceInput" data-bind="options: typeOfAssistance,\r\n                       optionsValue: \'Description\',\r\n                       optionsText: \'Description\',\r\n                       value: entity.AssistanceType,\r\n                       css: { blank: isNullOrEmpty(entity.AssistanceType()) },\r\n                       validateField: \'AssistanceType\',\r\n                       optionsCaption: \'Choose...\',\r\n                       disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'AssistanceType\', entity)"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'MedicationAssistance\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'MedicationAssistance\') }">\r\n                    <label for="medicationAssistanceInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'MedicationAssistance\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <select class="form-control input-sm" id="medicationAssistanceInput" data-bind="options: medicationAssistance,\r\n                       optionsValue: \'Description\',\r\n                       optionsText: \'Description\',\r\n                       value: entity.MedicationAssistance,\r\n                       css: { blank: isNullOrEmpty(entity.MedicationAssistance()) },\r\n                       validateField: \'MedicationAssistance\',\r\n                       optionsCaption: \'Choose...\',\r\n                       disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'MedicationAssistance\', entity)"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     data-bind="visible: security.getFieldVisible(\'Medications Detail\', \'MEDMANAGEMENTBY\'),\r\n                        css: { required: security.getFieldRequired(\'Medications Detail\', \'MEDMANAGEMENTBY\') }">\r\n                    <label for="medmanagementByInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'MEDMANAGEMENTBY\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <select class="form-control input-sm" id="medmanagementByInput" data-bind="options: MEDMANAGEMENTBY,\r\n                            optionsValue: \'MemberID\',\r\n                            optionsText: \'Description\',\r\n                            value: entity.MEDMANAGEMENTBY,\r\n                            css: { blank: isNullOrEmpty(entity.MEDMANAGEMENTBY()) },\r\n                            validateField: \'MEDMANAGEMENTBY\',\r\n                            optionsCaption: \'Choose...\',\r\n                            disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'MEDMANAGEMENTBY\', entity)"></select>\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     css: { }">\r\n                    <label for="PRESCRIBEDBYInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'PRESCRIBEDBY\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <input type="text" class="form-control input-sm autofocus" id="PRESCRIBEDBYInput"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="false"\r\n                               maxlength="80"\r\n                               data-bind="value: entity.PRESCRIBEDBY, valueUpdate: \'input\',\r\n                              validateField: \'PRESCRIBEDBY\',\r\n                              disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'PRESCRIBEDBY\', entity)" />\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     css: { }">\r\n                    <label for="COMMENTSInput" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'COMMENTS\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <input type="text" class="form-control input-sm autofocus" id="COMMENTSInput"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="false"\r\n                               maxlength="80"\r\n                               data-bind="value: entity.COMMENTS, valueUpdate: \'input\',\r\n                      validateField: \'COMMENTS\',\r\n                    disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'COMMENTS\', entity)" />\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     css: { }">\r\n                    <label for="Gentext1Input" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'Gentext1\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <input type="text" class="form-control input-sm autofocus" id="Gentext1Input"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="false"\r\n                               maxlength="80"\r\n                               data-bind="value: entity.Gentext1, valueUpdate: \'input\',\r\n                              validateField: \'Gentext1\',\r\n                              disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'Gentext1\', entity)" />\r\n                    </div>\r\n                </div>\r\n                <div class="form-group col-md-6"\r\n                     css: { }">\r\n                    <label for="Gentext2Input" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'Gentext2\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <input type="text" class="form-control input-sm autofocus" id="Gentext2Input"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="false"\r\n                               maxlength="80"\r\n                               data-bind="value: entity.Gentext2, valueUpdate: \'input\',\r\n                              validateField: \'Gentext2\',\r\n                              disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'Gentext2\', entity)" />\r\n                    </div>\r\n                </div>\r\n                <div class="form-group col-md-6"\r\n                     css: { }">\r\n                    <label for="Gentext3Input" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'Gentext3\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <input type="text" class="form-control input-sm autofocus" id="Gentext3Input"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="false"\r\n                               maxlength="80"\r\n                               data-bind="value: entity.Gentext3, valueUpdate: \'input\',\r\n                              validateField: \'Gentext3\',\r\n                              disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'Gentext3\', entity)" />\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6"\r\n                     css: { }">\r\n                    <label for="Gentext3Input" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'Medications Detail\', \'Gentext4\')"></label>\r\n                    <div class="col-sm-8">\r\n                        <input type="text" class="form-control input-sm autofocus" id="Gentext4Input"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="false"\r\n                               maxlength="80"\r\n                               data-bind="value: entity.Gentext4, valueUpdate: \'input\',\r\n                              validateField: \'Gentext4\',\r\n                              disable: isDetailReadOnly || security.getFieldReadOnly(\'Medications Detail\', \'Gentext4\', entity)" />\r\n                    </div>\r\n                </div>\r\n            </div>\r\n        </form>\r\n    </div>\r\n    <div class="modal-footer">\r\n        <button type="submit" class="btn btn-primary" data-bind="click: submit" data-i18n="common.ok"></button>\r\n        <button type="button" class="btn" data-bind="click: cancel, visible: !isReadOnly()" data-i18n="common.cancel"></button>\r\n        <button type="button" class="btn" data-bind="click: addNext, visible: isAdd && !isReadOnly()" data-i18n="common.addNext"></button>\r\n    </div>\r\n</div>\r\n';});


define('text!assessments/controls/modal-participant.html',[],function () { return '<section class="container assessment web-intake"\r\n         data-bind="css: { \'show-properties\': properties, \'show-narrative\': narrative, \'show-help\': help, \'show-edit-session\': editSession }">\r\n\r\n    <div class="content">\r\n        <!-- ko compose: \'assessments/data-entry.html\' --><!-- /ko -->\r\n    </div>\r\n    <!-- ko compose: \'core/validationSummary.html\' --><!-- /ko -->\r\n</section>\r\n';});


define('text!assessments/controls/participant-list-control.html',[],function () { return '<div data-preprocess="true">\r\n    <div class="form-control h-complex-form-control h-complex-form-control-modal" data-preprocess="true">\r\n        <div class="table-responsive scroll">\r\n            <table class="table table-striped table-hover table-condensed">\r\n                <thead>\r\n                    <tr>\r\n                        <th>\r\n                            <button tabindex="0" type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: add" id="addparticipant" >\r\n                                <span class="glyphicon glyphicon-plus"></span> <span data-i18n="common.new"></span>\r\n                            </button>\r\n                        </th>\r\n                        <!-- ko foreach: visibleColumnsParticipant -->\r\n                        <th tabindex="0" data-bind="text: $data"></th>\r\n                        <!-- /ko -->\r\n                    </tr>\r\n                </thead>\r\n                <tbody data-bind="foreach: {data: participantEntities, as: \'entity\'}">\r\n                    <tr>\r\n                        <td>\r\n                            <button tabindex="0" type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: $root.open.bind($root)">\r\n                                <span class="glyphicon glyphicon-plus"></span> <span data-i18n="common.open"></span>\r\n                            </button>\r\n                            <button tabindex="0" type="button" class="btn btn-primary btn-xs h-add-open-delete-button" data-bind="click: $parent.remove.bind($parent)">\r\n                                <span class="glyphicon glyphicon-trash"></span> <span data-i18n="common.delete"></span>\r\n                            </button>\r\n                        </td>\r\n                        <!-- ko foreach: { data: entity.VisibleResponses , as: \'response\'} -->\r\n                        <!-- ko if: (response.IsBoolean() == false)-->\r\n                        <td tabindex="0" data-bind="text: response.Item"></td>\r\n                        <!-- /ko -->\r\n                        <!-- ko if: (response.IsBoolean() == true)-->\r\n                        <!-- ko if: (response.Item() == \'0\')-->\r\n                        <td tabindex="0">No</td>\r\n                        <!-- /ko -->\r\n                        <!-- ko if: (response.Item() == \'1\')-->\r\n                        <td tabindex="0">Yes</td>\r\n                        <!-- /ko -->\r\n                        <!-- ko if: (response.Item() != \'0\' && response.Item() != \'1\')-->\r\n                        <td tabindex="0"></td>\r\n                        <!-- /ko -->\r\n                        <!-- /ko -->\r\n                        <!-- /ko -->\r\n                    </tr>\r\n                </tbody>\r\n            </table>\r\n            <br />\r\n        </div>\r\n    </div>\r\n</div>\r\n';});


define('text!assessments/controls/participant.html',[],function () { return '<div class="modal-content messageBox">\r\n    <div class="modal-header">\r\n    </div>\r\n    <div class="modal-body">\r\n\r\n        <div data-bind="compose: { model: ParticipantViewModel, view: \'assessments/controls/modal-participant.html\'}" />\r\n    </div>\r\n\r\n    <div class="modal-footer">\r\n        <button type="button" class="btn" data-bind="click: cancel" data-i18n="common.cancel" participant-btn-cancel ></button>\r\n        <button type="submit" class="btn" data-bind="click: submit" data-i18n="common.ok"></button>\r\n    </div>\r\n</div>\r\n';});


define('text!assessments/controls/relation-attach.html',[],function () { return '<div class="modal-content messageBox">\r\n    <div class="modal-header">\r\n        <div class="row">\r\n            <div class="col-sm-6 col-md-9">\r\n                <h3>Attach Existing Relation</h3>\r\n            </div>\r\n            <div class="col-sm-6 col-md-3">\r\n                 <div class="btn-toolbar pull-right" role="toolbar">\r\n                    <div class="btn-group btn-group-sm" role="group">\r\n                        <button type="button" class="btn btn-primary" data-bind="click: search" data-i18n="common.search"></button>\r\n                        <button type="button" class="btn" data-bind="click: cancel" data-i18n="common.cancel"></button>\r\n                    </div>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n    <div class="modal-body">\r\n        <div class="table-responsive" style="max-height: 400px; overflow-y: auto">\r\n            <table class="table table-striped table-hover table-condensed">\r\n                <thead>\r\n                    <tr>\r\n                        <th>RecID</th>\r\n                        <th>Name</th>\r\n                        <th>Relationship</th>\r\n                        <th>Phone</th>\r\n                        <th>Date of Birth</th>\r\n                    </tr>\r\n                </thead>\r\n                <tbody data-bind="foreach: relations">\r\n                    <tr style="cursor: pointer" data-bind="click: $root.select.bind($root)" tabindex="-1">\r\n                        <td data-bind="text: RECID"></td>\r\n                        <td data-bind="text: LASTNAME"></td>\r\n                        <td data-bind="text: RELATIONSHIP"></td>\r\n                        <td data-bind="text: PHONE"></td>\r\n                        <td data-bind="dateText: DOB"></td>\r\n                    </tr>\r\n                </tbody>\r\n            </table>\r\n        </div>\r\n    </div>\r\n</div>';});


define('text!assessments/controls/relation-control.html',[],function () { return '<div class="form-control h-complex-form-control" data-preprocess="true">\r\n    <div class="table-responsive" data-bind="visible: entities().length">\r\n        <table class="table table-striped table-hover table-condensed">\r\n            <thead>\r\n                <tr>\r\n                    <th>\r\n                        <% if (this.screenDesignIsReadOnly) { %>\r\n                        <button tabindex="0" type="button" disabled="disabled" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: search">\r\n                            <span class="glyphicon glyphicon-search"></span> <span data-i18n="common.search"></span>\r\n                        </button>\r\n                        <button tabindex="0" type="button" disabled="disabled" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: attach">\r\n                            <span class="glyphicon glyphicon-link"></span> <span data-i18n="common.attach"></span>\r\n                        </button>\r\n                        <% } else if (!this.screenDesignIsReadOnly) { %>\r\n                        <button tabindex="0" type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: search">\r\n                            <span class="glyphicon glyphicon-search"></span> <span data-i18n="common.search"></span>\r\n                        </button>\r\n                        <button tabindex="0" type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: attach">\r\n                            <span class="glyphicon glyphicon-link"></span> <span data-i18n="common.attach"></span>\r\n                        </button>\r\n                        <% } %>\r\n                    </th>\r\n                </tr>\r\n            </thead>\r\n            <tbody data-bind="foreach: entities">\r\n                <tr>\r\n                    <td>\r\n                        <div class="row">\r\n                            <% if (this.screenDesignIsReadOnly) { %>\r\n                            <div class="btn-toolbar col-md-1" role="toolbar">\r\n                                <div class="btn-group">\r\n                                    <button tabindex="0" type="button" disabled="disabled" class="btn btn-primary btn-xs h-add-open-delete-button" data-bind="click: $parent.open.bind($parent)">\r\n                                        <span class="glyphicon glyphicon-folder-open"></span> <span data-i18n="common.open"></span>\r\n                                    </button>\r\n                                </div>\r\n                                <div class="btn-group">\r\n                                    <button tabindex="0" type="button" disabled="disabled" class="btn btn-primary btn-xs h-add-open-delete-button" data-bind="click: $parent.remove.bind($parent)">\r\n                                        <span class="glyphicon glyphicon-trash"></span> <span data-i18n="common.delete"></span>\r\n                                    </button>\r\n                                </div>\r\n                            </div>\r\n                            <% } else if (!this.screenDesignIsReadOnly) { %>\r\n                            <div class="btn-toolbar col-md-1" role="toolbar">\r\n                                <div class="btn-group">\r\n                                    <button tabindex="0" type="button" class="btn btn-primary btn-xs h-add-open-delete-button" data-bind="click: $parent.open.bind($parent)">\r\n                                        <span class="glyphicon glyphicon-folder-open"></span> <span data-i18n="common.open"></span>\r\n                                    </button>\r\n                                </div>\r\n                                <div class="btn-group">\r\n                                    <button tabindex="0" type="button" class="btn btn-primary btn-xs h-add-open-delete-button" data-bind="click: $parent.remove.bind($parent)">\r\n                                        <span class="glyphicon glyphicon-trash"></span> <span data-i18n="common.delete"></span>\r\n                                    </button>\r\n                                </div>\r\n                            </div>\r\n                            <% } %>\r\n                            <div class="col-md-11" style="padding-left: 40px">\r\n                                <p>\r\n                                    <strong data-bind="text: (FirstName() + \' \' + LastName()).trim()"></strong>\r\n                                    &nbsp;\r\n                                    <small data-bind="text: \'(\' + (Relationship() + \'|\' + (MultiRelationship() || \'\')).split(\'|\').filter(function(s) { return !isNullOrEmpty(s); }).join(\', \') + \')\'"></small>\r\n                                </p>\r\n                                <p>\r\n                                    <span data-bind="visible: Street"><span data-bind="text: Street"></span><br /></span>\r\n                                    <span data-bind="visible: Street2"><span data-bind="text: Street2"></span><br /></span>\r\n                                    <span data-bind="visible: City() + State() + Zipcode()  + ResCounty(), text: City() + \', \' + State() + \' \' + Zipcode() + \' \' + ResCounty()"></span>\r\n                                </p>\r\n                                <p>\r\n                                    <span data-bind="visible: WorkPhone" class="pull-left">\r\n                                        <small class="text-muted">work:</small> <span data-bind="text: WorkPhone"></span>&nbsp;&nbsp;\r\n                                    </span>\r\n                                    <span data-bind="visible: CellPhone" class="pull-left">\r\n                                        <small class="text-muted">cell:</small> <span data-bind="text: CellPhone"></span>&nbsp;&nbsp;\r\n                                    </span>\r\n                                    <span data-bind="visible: Phone" class="pull-left">\r\n                                        <small class="text-muted">phone:</small> <span data-bind="text: Phone"></span>&nbsp;&nbsp;\r\n                                    </span>\r\n                                </p>\r\n                                <p data-bind="visible: SystemSettings.RelationEmail && Email">\r\n                                    <small class="text-muted">email:</small> <span data-bind="text: Email"></span>\r\n                                </p>\r\n                            </div>\r\n                        </div>\r\n                    </td>\r\n                </tr>\r\n            </tbody>\r\n        </table>\r\n    </div>\r\n    <div data-bind="visible: entities().length === 0">\r\n        <table class="table table-striped table-hover table-condensed">\r\n            <thead>\r\n                <tr>\r\n                    <th>\r\n                        <% if (this.screenDesignIsReadOnly) { %>\r\n                        <button type="button" disabled="disabled" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: search">\r\n                            <span class="glyphicon glyphicon-search"></span> <span data-i18n="common.search"></span>\r\n                        </button>\r\n                        <button tabindex="0" disabled="disabled" type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: attach">\r\n                            <span class="glyphicon glyphicon-link"></span> <span data-i18n="common.attach"></span>\r\n                        </button>\r\n                        <% } else if (!this.screenDesignIsReadOnly) { %>\r\n                        <button type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: search">\r\n                            <span class="glyphicon glyphicon-search"></span> <span data-i18n="common.search"></span>\r\n                        </button>\r\n                        <button tabindex="0" type="button" class="btn btn-info btn-xs h-add-open-delete-button" data-bind="click: attach">\r\n                            <span class="glyphicon glyphicon-link"></span> <span data-i18n="common.attach"></span>\r\n                        </button>\r\n                        <% } %>\r\n                    </th>\r\n                </tr>\r\n            </thead>\r\n            <tbody>\r\n                <tr>\r\n                    <td>\r\n                        <span data-i18n="common.empty"></span>\r\n                    </td>\r\n                </tr>\r\n            </tbody>\r\n        </table>\r\n    </div>\r\n</div>';});


define('text!assessments/controls/relation-search.html',[],function () { return '<div class="modal-content messageBox">\r\n    <div class="modal-header">\r\n        <div class="row">\r\n            <div class="col-sm-6 col-md-9">\r\n                <h3>Search For Relation</h3>\r\n            </div>\r\n            <div class="col-sm-6 col-md-3">\r\n                 <div class="btn-toolbar pull-right" role="toolbar">\r\n                    <div class="btn-group btn-group-sm" role="group">\r\n                        <button type="button" class="btn btn-primary" data-bind="click: addNew, visible: enableAdd" data-i18n="common.new"></button>\r\n                        <button type="button" class="btn" data-bind="click: cancel" data-i18n="common.cancel"></button>\r\n                    </div>\r\n                </div>\r\n            </div>\r\n        </div>        \r\n    </div>\r\n    <div class="modal-body" style="min-height: 200px; max-height: 400px">\r\n        <form class="form-inline form-small" data-bind="submit: submit" role="form" novalidate>\r\n            <div class="row">\r\n                <div class="form-group">\r\n                    <label class="sr-only" for="lastName">Last name</label>\r\n                    <input id="lastName" type="text" class="form-control autofocus input-sm" data-bind="value: lastName, valueUpdate: \'input\'" placeholder="Last name">\r\n                </div>\r\n                <div class="form-group">\r\n                    <label class="sr-only" for="firstName">First name</label>\r\n                    <input id="firstName" type="text" class="form-control input-sm" data-bind="value: firstName, valueUpdate: \'input\'" placeholder="First name">\r\n                </div>\r\n                <div class="form-group">\r\n                    <label class="sr-only" for="tabType">Relation type</label>\r\n                    <select id="tabType" class="form-control input-sm" data-bind="value: tabType, valueUpdate: \'input\', options: tabTypes"></select>\r\n                </div>\r\n            </div>\r\n            <div class="row" data-bind="visible: connectionFailure">\r\n                <em>Unable to connect to Harmony Servers... Are you offline?</em>\r\n            </div>\r\n            <div class="row" data-bind="visible: !connectionFailure() && searchResults().length">\r\n                <div class="table-responsive" style="overflow-y: auto; max-height: 330px">\r\n                    <table class="table table-striped table-hover table-condensed">\r\n                        <thead>\r\n                            <tr>\r\n                                <th>Contact ID</th>\r\n                                <th>First Name</th>\r\n                                <th>Last Name</th>\r\n                                <th>Middle Name</th>\r\n                                <th>Street</th>\r\n                                <th>City</th>\r\n                                <th>State</th>\r\n                                <th>Zip Code</th>\r\n                                <th>Residence County</th>\r\n                                <th>Home Phone</th>\r\n                                <th>Vendor</th>\r\n                                <th>Relation</th>\r\n                            </tr>\r\n                        </thead>\r\n                        <tbody data-bind="foreach: searchResults">\r\n                            <tr style="cursor: pointer" data-bind="click: $root.select.bind($root)" tabindex="-1">\r\n                                <td data-bind="text: CONTACTID"></td>\r\n                                <td data-bind="text: FirstName"></td>\r\n                                <td data-bind="text: LastName"></td>\r\n                                <td data-bind="text: MiddleName"></td>\r\n                                <td data-bind="text: Street"></td>\r\n                                <td data-bind="text: City"></td>\r\n                                <td data-bind="text: State"></td>\r\n                                <td data-bind="text: Zipcode"></td>\r\n                                <td data-bind="text: ResCounty"></td>\r\n                                <td data-bind="text: Phone"></td>\r\n                                <td data-bind="text: Vendor"></td>\r\n                                <td data-bind="text: Relation"></td>\r\n                            </tr>\r\n                        </tbody>\r\n                    </table>\r\n                </div>\r\n            </div>\r\n        </form>\r\n    </div>\r\n</div>';});


define('text!assessments/controls/relation.html',[],function () { return '<div class="modal-content messageBox">\r\n    <div class="modal-header">\r\n        <h3>Relation</h3>\r\n    </div>\r\n    <div class="modal-body" style="max-height: 400px; overflow-y: auto">\r\n\r\n        <!-- ko compose: \'core/validationSummary.html\' --><!-- /ko -->\r\n\r\n        <form class="form-horizontal" data-bind="submit: submit" role="form" novalidate>\r\n            <div class="row">\r\n                <div class="form-group required col-md-6">\r\n                    <label for="relationCategoryInput" data-i18n="relation.relationCategory" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <select class="form-control input-sm" id="relationCategoryInput" data-bind="options: tabTypes, value: tabType, disable: true"></select>\r\n                    </div>\r\n                </div>\r\n                <div class="form-group required col-md-6">\r\n                    <label for="relationshipInput" data-i18n="relation.relationship" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <select class="form-control input-sm autofocus" id="relationshipInput" \r\n                                data-bind="options: relationships, value: entity.Relationship, validateField: \'Relationship\', optionsCaption: \'Choose...\', disable: isDetailReadOnly">\r\n                        </select>\r\n                    </div>\r\n                </div>\r\n            </div>\r\n            <div class="row">\r\n                <div class="form-group col-md-12">\r\n                    <label for="multipleRelationshipsInput" data-i18n="relation.multipleRelationships" class="col-md-2 control-label"></label>\r\n                    <div class="col-md-10" data-bind="foreach: multiRelationships()">\r\n                        <div class="col-sm-4">\r\n                            <div class="checkbox">                                \r\n                                <input type="checkbox" data-bind="value: $data, checked: $root.multiRelationship, attr: { id: $data }, disable: $root.isDetailReadOnly" class="h-bold-checked" />\r\n                                <label data-bind="text: $data, attr: { \'for\': $data}"></label>\r\n                            </div>\r\n                        </div>\r\n                    </div>\r\n                </div>\r\n            </div>\r\n            <div class="row">\r\n                <div class="form-group required col-md-6">\r\n                    <label for="lastNameInput" data-i18n="relation.lastName" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="lastNameInput" type="text" placeholder="Enter last name"\r\n                               data-bind="value: entity.LastName, autocapitalize: true, validateField: \'LastName\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n                <div class="form-group col-md-6">\r\n                    <label for="middleNameInput" data-i18n="relation.middleName" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="middleNameInput" type="text" placeholder="Enter middle name"\r\n                               data-bind="value: entity.MiddleName, autocapitalize: true, validateField: \'MiddleName\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n            </div>\r\n            <div class="row">\r\n                <div class="form-group required col-md-6">\r\n                    <label for="firstNameInput" data-i18n="relation.firstName" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="firstNameInput" type="text" placeholder="Enter first name"\r\n                               data-bind="value: entity.FirstName, autocapitalize: true, validateField: \'FirstName\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6">\r\n                    <label for="streetInput" data-i18n="relation.street" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="streetInput" type="text" placeholder="Enter street"\r\n                               data-bind="value: entity.Street, autocapitalize: true, validateField: \'Street\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n            </div>\r\n            <div class="row">\r\n                <div class="form-group col-md-6">\r\n                    <label for="street2Input" data-i18n="relation.street2" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="street2Input" type="text" placeholder="Enter street 2"\r\n                               data-bind="value: entity.Street2, autocapitalize: true, validateField: \'Street2\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n                <div class="form-group col-md-6">\r\n                    <label for="cityInput" data-i18n="relation.city" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="cityInput" type="text" placeholder="Enter city"\r\n                               data-bind="value: entity.City, autocapitalize: true, validateField: \'City\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n            </div>\r\n            <div class="row">\r\n                <div class="form-group col-md-6">\r\n                    <label for="stateInput" data-i18n="relation.state" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="stateInput" type="text" placeholder="Enter state"\r\n                               data-bind="value: entity.State, autocapitalize: true, validateField: \'State\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6">\r\n                    <label for="zipCodeInput" data-i18n="relation.zipCode" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="zipCodeInput" type="text" placeholder="Enter zip code"\r\n                               data-bind="maskedValue: entity.Zipcode, valueUpdate: \'input\', autocapitalize: true, validateField: \'Zipcode\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               data-inputmask="\'mask\': \'00000-0000\', \'delimiter\':\'-\'"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n            </div>\r\n            <div class="row">\r\n                <div class="form-group col-md-6">\r\n                    <label for="residenceCountyInput" data-i18n="relation.residenceCounty" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="residenceCountyInput" type="text" placeholder="Enter residence county"\r\n                               data-bind="value: entity.ResCounty, autocapitalize: true, validateField: \'ResCounty\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6">\r\n                    <label for="homePhoneInput" data-i18n="relation.homePhone" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="homePhoneInput" type="text" placeholder="Enter home phone"\r\n                               data-bind="maskedValue: entity.Phone, valueUpdate: \'input\', autocapitalize: true, validateField: \'PHONE\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               data-inputmask="\'mask\': \'9(000)000-0000\', \'delimiter\':\'[\\\\(|\\\\)|\\\\-| ]\'"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n            </div>\r\n            <div class="row">\r\n                <div class="form-group col-md-6">\r\n                    <label for="cellPhoneInput" data-i18n="relation.cellPhone" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="cellPhoneInput" type="text" placeholder="Enter cell phone"\r\n                               data-bind="maskedValue: entity.CellPhone, valueUpdate: \'input\', autocapitalize: true, validateField: \'CELLPHONE\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               data-inputmask="\'mask\': \'9(000)000-0000\', \'delimiter\':\'[\\\\(|\\\\)|\\\\-| ]\'"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="form-group col-md-6">\r\n                    <label for="workPhoneInput" data-i18n="relation.workPhone" class="col-md-4 control-label"></label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="workPhoneInput" type="text" placeholder="Enter work phone"\r\n                               data-bind="maskedValue: entity.WorkPhone, valueUpdate: \'input\', autocapitalize: true, validateField: \'WORKPHONE\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               data-inputmask="\'mask\': \'9(000)000-0000\', \'delimiter\':\'[\\\\(|\\\\)|\\\\-| ]\'"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n            </div>\r\n            <div class="row">\r\n                <div class="form-group col-md-6" data-bind="visible: SystemSettings.RelationEmail">\r\n                    <label for="emailInput" class="col-md-4 control-label">Email</label>\r\n                    <div class="col-md-8">\r\n                        <input class="form-control input-sm" id="emailInput" type="text" placeholder="Enter email"\r\n                               data-bind="email: entity.Email, valueUpdate: \'input\', validateField: \'EMAIL\', disable: isDetailReadOnly() || entity.ReadOnlyDueToWorkerOrDemographicLink()"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" maxlength="50" />\r\n                    </div>\r\n                </div>\r\n            </div>\r\n        </form>\r\n    </div>\r\n    <div class="modal-footer">\r\n        <button type="submit" class="btn btn-primary" data-bind="click: submit" data-i18n="common.ok"></button>\r\n        <button type="button" class="btn" data-bind="click: cancel" data-i18n="common.cancel"></button>\r\n    </div>\r\n</div>\r\n';});


define('text!assessments/copy.html',[],function () { return '<section class="container rootEntityViewModel">\r\n    <div class="command-bar btn-toolbar" role="toolbar"></div>\r\n\r\n    <!-- ko compose: \'core/validationSummary.html\' --><!-- /ko -->\r\n\r\n    <div class="content">\r\n        <div class="row">\r\n            <h3 class="text-center">\r\n                <span data-i18n="session.copyAssessment"></span>:\r\n                <span data-bind="text: entity.ownerTitle"></span>\r\n            </h3>\r\n\r\n            <div class="col-sm-7 col-sm-offset-2" data-bind="compose: \'assessments/details.html\'">\r\n            </div>\r\n\r\n            <div class="col-sm-2">\r\n                <button type="button" class="btn btn-primary h-width-100-percent" data-bind="click: submit, disable: busy" data-i18n="common.open"></button>\r\n                <!--<button type="button" class="btn h-width-100-percent" data-bind="click: submitAndClose, disable: busy" data-i18n="common.saveAndClose"></button>-->\r\n                <button type="button" class="btn h-width-100-percent" data-bind="click: cancel, disable: busy" data-i18n="common.cancel"></button>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</section>';});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/copy',["require", "exports", 'assessments/assessment-base', 'plugins/router', 'core/util', 'entities/api', 'core/viewmodels', 'assessments/consumer-mapper', 'assessments/screen-repo', 'assessments/scales'], function (require, exports, AssessmentBase, durandalRouter, util, entities, viewmodels, mapper, screenDesignRepo, scales) {
    var CopyAssessment = (function (_super) {
        __extends(CopyAssessment, _super);
        function CopyAssessment() {
            _super.call(this);
            this.busy = ko.observable(false);
            this.enableScreenDesignDropdown = false;
        }
        CopyAssessment.prototype.activate = function (sourceEntityManager, destinationEntityManager) {
            this.sourceEntityManager = sourceEntityManager;
            return _super.prototype.activate.call(this, destinationEntityManager);
        };
        CopyAssessment.prototype.canDeactivate = function () {
            return Q.resolve(true);
        };
        CopyAssessment.prototype.createCommands = function () {
            _super.prototype.createCommands.call(this);
            var Command = viewmodels.Command;
            this.commands.add('submit', new Command(this.submit.bind(this)));
            this.commands.add('submitAndClose', new Command(this.submitAndClose.bind(this)));
            this.commands.add('cancel', new Command(this.cancel.bind(this)));
        };
        CopyAssessment.prototype.beforeFinishActivate = function () {
            var _this = this;
            return _super.prototype.beforeFinishActivate.call(this).then(function () {
                if (_this.screenDesigns.length === 0) {
                    _this.screenDesigns.push({ SCREENDESIGNNAME: '[no screen designs available]', SCREENDESIGNID: -1 });
                }
                if (_this.entity.ScreenDesignID()) {
                    _this.selectedScreenDesign(_this.screenDesigns.filter(function (s) { return s.SCREENDESIGNID === _this.entity.ScreenDesignID(); })[0] || _this.screenDesigns[0]);
                }
                else {
                    _this.selectedScreenDesign(_this.screenDesigns[0]);
                }
                if (_this.entity.FundCode && !_this.entity.FundCode() && _this.fundCodes && _this.fundCodes.length) {
                    _this.entity.FundCode(_this.fundCodes[0]);
                }
                _this.selectedScreenDesign(util.Arrays.firstOrDefault(_this.screenDesigns, function (s) { return s.SCREENDESIGNID === _this.sourceEntityManager.entity.ScreenDesignID(); }));
            });
        };
        CopyAssessment.prototype.cancel = function () {
            this.close();
        };
        CopyAssessment.prototype.submit = function () {
            this.submitInternal(false);
        };
        CopyAssessment.prototype.submitAndClose = function () {
            this.submitInternal(true);
        };
        CopyAssessment.prototype.submitInternal = function (saveAndClose) {
            var _this = this;
            this.entity.OwnerID(entities.getEntityId(this.entityManager.parentEntityManager.entity));
            this.entity.ScreenDesignID(this.selectedScreenDesign().SCREENDESIGNID);
            if (this.entity.entityType.name === entities.entityTypes.ConsumerAssessment) {
                this.entity.Assessment(this.selectedScreenDesign().SCREENDESIGNNAME);
                this.entity.OpenCloseID(security.getOpenCloseId(this.entityManager.parentEntityManager.entity, this.entity.FundCode()));
            }
            if (this.validate()) {
                this.busy(true);
                screenDesignRepo.getScreenDesign(this.entityManager.entity.ScreenDesignID()).then(function (screenDesign) {
                    mapper.mapToAssessment(_this.parentEntityManager.entity, _this.entityManager, screenDesign);
                    _this.copyResponses(screenDesign);
                }).then(function () {
                    if (_this.validate()) {
                        if (saveAndClose) {
                            _this.save().then(function (saveResult) { return _this.cancel(); }).fail(function (reason) {
                                return Q.reject(reason);
                            }).done();
                            return;
                        }
                        durandalRouter.navigate('#' + entities.getFragment(_this.entityManager));
                    }
                }).finally(function () { return _this.busy(false); }).done();
            }
        };
        CopyAssessment.prototype.copyResponses = function (screenDesign) {
            var _this = this;
            screenDesign.SCREENQUESTIONS.forEach(function (q) {
                if (q.CONTROLSCREENSCALE === scales.keys.ctlMedicationDataForm || q.CONTROLSCREENSCALE === scales.keys.ctlRelationDataForm) {
                    return;
                }
                var existingResponse = util.Arrays.firstOrDefault(_this.entityManager.entity.Responses(), function (x) { return x.ScaleID() === q.SCREENSCALEID; });
                if (existingResponse) {
                    return;
                }
                var sourceResponse = util.Arrays.firstOrDefault(_this.sourceEntityManager.entity.Responses(), function (r) { return r.ScaleID() === q.SCREENSCALEID; });
                if (!sourceResponse || isNullOrEmpty(sourceResponse.Item())) {
                    return;
                }
                var destinationResponse = _this.entityManager.createChildEntity(_this.entityManager.entity, 'Responses', {
                    AssessmentID: _this.entityManager.entity.AssessmentID,
                    Item: sourceResponse.Item(),
                    ScaleID: q.SCREENSCALEID,
                    SecID: sourceResponse.SecID(),
                    DateTimeStamp: new Date(),
                    UserStamp: User.Current.UserStamp
                });
            });
        };
        return CopyAssessment;
    })(AssessmentBase);
    return CopyAssessment;
});


define('text!assessments/data-entry.html',[],function () { return '<div class="form-content" data-preprocess="true">\r\n    <% var viewModel = this, screenDesign = this.screenDesign, question, i, qvm, scaleId, screenDesignIsReadOnly, scale, isIndicator = false, hide = false, demographicField, enrollmentField; %>\r\n    <div data-bind = "template: {afterRender: afterRenderProcessing }">\r\n        <h1 id="top" data-bind="visible: !app.webIntake"><%= htmlEncode(screenDesign.SCREENDESIGNNAME) %><br class="text-info properties" /><small class="text-info properties">&nbsp;assessment: <%= viewModel.entity.AssessmentID() %>; screen-design: <%= viewModel.entity.ScreenDesignID() %></small></h1>\r\n        <form role="form" novalidate>\r\n            <% for(i = 0; i < this.questions.length; i++) {\r\n            question = this.questions[i];\r\n            if(question.CONTROLSCREENSCALE === "ctlLineSpace") {\r\n            continue;\r\n            }\r\n\r\n           if (question.CONTROLSCREENSCALE === \'ctlCopyAddressFrom\') {\r\n                var copyAddressDefaultValue = sessionStorage.getItem("copyAddressDefaultValue_" + viewModel.entity.AssessmentID());\r\n                if (copyAddressDefaultValue === null || copyAddressDefaultValue === undefined || copyAddressDefaultValue === \'\') {\r\n                    sessionStorage.setItem("copyAddressDefaultValue_" + viewModel.entity.AssessmentID() ,  question.DefaultValue + "," + question.QUESTIONID );\r\n                }\r\n                else {\r\n                    var index = copyAddressDefaultValue.indexOf(question.QUESTIONID);\r\n                    if (index === -1 ) {\r\n                        copyAddressDefaultValue = copyAddressDefaultValue + "~" +  question.DefaultValue + "," + question.QUESTIONID;\r\n                        sessionStorage.setItem("copyAddressDefaultValue_" + viewModel.entity.AssessmentID() , copyAddressDefaultValue );\r\n                    }\r\n                }\r\n            }\r\n\r\n            qvm = viewModel.getQuestionViewModel(question);\r\n            scaleId = question.SCREENSCALEID;\r\n\r\n            scale = question.CONTROLSCREENSCALE;\r\n            demographicField = question.DemographicLookupField || \'\';\r\n            enrollmentField = question.EnrollmentLookupField || \'\';\r\n            if (scale == \'ctlHeader\') {\r\n            if (/^(eligible)|(ineligible)$/i.test(question.QUESTIONID)) { %>\r\n            <div class="alert alert-primary" data-bind="css: { \'skipped\': questionViewModels[\'q<%= scaleId %>\'].isSkipped }">\r\n                <strong style="font-size: 18px"><%= htmlEncode(question.SCREENSCALE) %></strong>\r\n                <% if(!isNullOrEmpty(question.HELPLINE)) { %>\r\n                <br />\r\n                <span class="hidden-print"><%= htmlEncode(question.HELPLINE) %></span>\r\n                <% } %>\r\n            </div>\r\n            <%  } else { %>\r\n            <h2 id="section-<%= scaleId %>" class="<%= \'header-\' + (question.FONTSIZE || \'medium\').toLowerCase() %>" data-bind="css: { \'skipped\': questionViewModels[\'q<%= scaleId %>\'].isSkipped, \'initially-skipped\': questionViewModels[\'q<%= scaleId %>\'].initiallySkipped }"><%= htmlEncode(question.SCREENSCALE) %></h2>\r\n            <%  }\r\n            continue;\r\n            }\r\n            %>\r\n            \r\n            <% if (scale == \'ctlInstructionalText\') { %>\r\n                <h2 id="section-<%= scaleId %>"></h2>\r\n            <% } %>\r\n            \r\n            <div class="form-group"\r\n                 id="q<%= scaleId %>"\r\n                 data-bind="css: { \'has-error\': questionViewModels[\'q<%= scaleId %>\'].hasError, \'skipped\': questionViewModels[\'q<%= scaleId %>\'].isSkipped, \'initially-skipped\': questionViewModels[\'q<%= scaleId %>\'].initiallySkipped, \'answered\': questionViewModels[\'q<%= scaleId %>\'].isAnswered }, readOnlyQuestion: isReadOnlyField[\'<%= scaleId %>\']">\r\n                <% if (scale != \'ctlInstructionalText\' && scale != \'ctlCopyAddressFrom\') { %>\r\n                <div class="row">\r\n                    <div class="col-xs-11">\r\n                        <label for="<%= qvm.inputId %>" class="control-label question-label">\r\n                            <span data-bind="css: { \'required\': questionViewModels[\'q<%= scaleId %>\'].isRequired } "><%= htmlEncode(qvm.label) %></span>\r\n                            <% if(!isNullOrEmpty(question.HELPLINE)) { %>\r\n                            <br />\r\n                            <!--<small class="text-muted help glyphicon glyphicon-info-sign"></small>-->\r\n                            <small style="font-weight: normal" class="text-muted help hidden-print"><%= htmlEncode(question.HELPLINE) %></small>\r\n                            <% } %>\r\n                            <small class="text-info properties">&nbsp;[<%= scale.replace(\'ctl\', \'\') %>,&nbsp;<%= scaleId %>]</small>\r\n                        </label>\r\n                        <% if (qvm.isLinked) { %>\r\n                        <abbr class="hidden-print" aria-hidden="true" title="Consumer Linked"><small class="glyphicon glyphicon-link text-muted"></small></abbr>\r\n                        <% } %>\r\n                        <% if ((scale === \'ctlMultiSelectionListBox\' || scale === \'ctlMultiSelectionListBoxWithNeeds\') && !qvm.isReadOnly && this.screenDesignIsReadOnly) { %>\r\n                        &nbsp;\r\n                        <% } %>\r\n                        <% if ((scale === \'ctlMultiSelectionListBox\' || scale === \'ctlMultiSelectionListBoxWithNeeds\') && !qvm.isReadOnly && !this.screenDesignIsReadOnly) { %>\r\n                        &nbsp;\r\n                        <a href="#" class="all-none hidden-print" tabindex="-1"\r\n                           data-bind="click: function() { questionViewModels[\'q<%= scaleId %>\'].selectAll(); }"\r\n                           data-i18n="common.all"></a>\r\n                        <span class="hidden-print">/</span>\r\n                        <a href="#" class="all-none hidden-print" tabindex="-1"\r\n                           data-bind="click: function() { questionViewModels[\'q<%= scaleId %>\'].selectNone(); }"\r\n                           data-i18n="common.none"></a>\r\n                        <% } %>\r\n                    </div>\r\n                    <div class="col-xs-1 hidden-print">\r\n                        <div class="pull-right">\r\n                            <abbr aria-hidden="true" data-bind="visible: questionViewModels[\'q<%= scaleId %>\'].isAnswered" title="Answered"><small class="glyphicon glyphicon-ok text-success"></small></abbr>\r\n                        </div>\r\n                    </div>\r\n                </div>\r\n                <% } %>\r\n\r\n                <% if (scale === \'ctlFiles\') { %>\r\n                <div id="<%= qvm.inputId %>" class="input-group">\r\n                    <span class="input-group-btn">\r\n                        <span class="btn btn-file" style="background-color: rgb(245, 245, 245)">\r\n                            Browse&hellip; <input type="file" data-bind="files: questionViewModels[\'q<%= scaleId %>\'].value, attr: { multiple: questionViewModels[\'q<%= scaleId %>\'].options.multiple }" accept="<%= qvm.options.accept %>">\r\n                        </span>\r\n                    </span>\r\n                    <input type="text" class="form-control" placeholder="No files selected" readonly style="font-weight: normal">\r\n                    <span class="input-group-btn">\r\n                        <span class="btn files-clear-btn" style="background-color: rgb(245, 245, 245)">\r\n                            <i class="glyphicon glyphicon-remove"></i>\r\n                        </span>\r\n                    </span>\r\n                </div>\r\n                <% } else if(scale === \'ctlCopyAddressFrom\') { %>\r\n                <a href="#<%= qvm.inputId %>" data-bind="click: questionViewModels[\'q<%= scaleId %>\'].onCopyAddressFromClick"><%= htmlEncode(qvm.label) %></a>\r\n                <% } else if (scale === \'ctlCurrencyTextbox\') { %>\r\n                <span class="input-decoration">$</span>\r\n                <input id="<%= qvm.inputId %>" type="number" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"\r\n                       min="0" max="9999999.99"\r\n                       data-bind="numberValue: questionViewModels[\'q<%= scaleId %>\'].value, nullable: true" />\r\n                <% } else if (qvm && qvm instanceof viewModel.controlConstructors.DateControl) { %>\r\n                <div class="input-group">\r\n                    <span class="input-group-btn hidden-print">\r\n                        <button class="btn" type="button" tabindex="-1">\r\n                            <span class="glyphicon glyphicon-th"></span>\r\n                        </button>\r\n                    </span>\r\n                    <input id="<%= qvm.inputId %>" class="form-control" type="text" min="1/1/1850" max="12/31/2250"\r\n                           data-bind="dateValue: questionViewModels[\'q<%= scaleId %>\'].value, nullable: true" placeholder="<%= qvm.placeholder %>"\r\n                           autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                </div>\r\n                <% } else if (scale === \'ctlTimeControl\') { %>\r\n                <div class="input-group">\r\n                    <span class="input-group-btn hidden-print">\r\n                        <button class="btn" type="button" tabindex="-1">\r\n                            <span class="glyphicon glyphicon-time"></span>\r\n                        </button>\r\n                    </span>\r\n                    <input id="<%= qvm.inputId %>" class="form-control" type="text"\r\n                           data-bind="timeValue: questionViewModels[\'q<%= scaleId %>\'].value, nullable: true" placeholder="<%= qvm.placeholder %>"\r\n                           autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                </div>\r\n                <% } else if (scale === \'ctlDecimalTextbox\') { %>\r\n                <input id="<%= qvm.inputId %>" type="number" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"\r\n                       rmin="<%= qvm.minValue %>" max="<%= qvm.maxValue %>"\r\n                       data-bind="numberValue: questionViewModels[\'q<%= scaleId %>\'].value, nullable: true" />\r\n                <% } else if (scale === \'ctlNumericTextbox\') { %>\r\n                <input id="<%= qvm.inputId %>" type="number" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"\r\n                       rmin="<%= qvm.minValue %>" max="<%= qvm.maxValue %>"\r\n                       data-bind="numberValue: questionViewModels[\'q<%= scaleId %>\'].value, nullable: true" />\r\n                <% } else if (scale === \'ctlMultiSelectionListBox\' || scale === \'ctlMultiSelectionListBoxWithNeeds\'\r\n                || (scale === \'ctlDemographicDataLookup\' && (demographicField === \'lblMultiRace\' || (demographicField === \'lblRACE\' && JSON.parse(localStorage.getItem("GroupSetupConfigRace")) == \'ctlMultiSelectionListBox\')))\r\n                || (scale === \'ctlEnrollmentDataLookup\' && (enrollmentField === \'lblMonthlyPublicSupportAtApplication\' || enrollmentField === \'lblMedicalInsuranceCoverageAtApplication\'))\r\n                ) { %>\r\n                <div id="<%= qvm.inputId %>" class="form-control h-complex-form-control">\r\n                    <div class="row">\r\n                        <% for(l = 0; l < qvm.choices.length; l++) {\r\n                        choice = qvm.choices[l]; %>\r\n                        <div class="col-md-4" data-bind="visible: !hideChoice(<%= scaleId%>,<%= choice.screenLookupId%>)">\r\n                            <div class="checkbox">\r\n                                <input id="<%= choice.inputId %>" aria-labelledby="<%= choice.labelId %>"\r\n                                       type="checkbox" name="<%= qvm.inputId %>"\r\n                                       value="<%= choice.screenLookupId %>"\r\n                                       data-bind="checked: questionViewModels[\'q<%= scaleId %>\'].value"\r\n                                       class="h-bold-checked" />\r\n                                <label id="<%= choice.labelId %>"\r\n                                       for="<%= choice.inputId %>">\r\n                                    <span></span>\r\n                                    <%= choice.name %>\r\n                                    <% if (false) { %>\r\n                                    <small class="text-muted glyphicon glyphicon-share-alt"></small>\r\n                                    <% } %>\r\n                                    <small class="text-muted properties">\r\n                                        [<%= choice.choice.SCREENLOOKUPID\r\n                                        + (!isNullOrEmpty(choice.choice.SECONDARYVALUE) ? \'; SecondaryValue \' + choice.choice.SECONDARYVALUE : \'\')\r\n                                        + (choice.choice.NeedCodeID !== null ? \'; NeedCodeID: \' + choice.choice.NeedCodeID.toString() : \'\')\r\n                                        + (choice.choice.ValueID !== null ? \'; ValueID: \' + choice.choice.ValueID.toString() : \'\')\r\n                                        %>]\r\n                                    </small>\r\n                                </label>\r\n                            </div>\r\n                        </div>\r\n                        <% } %>\r\n                    </div>\r\n                </div>\r\n                <% } else if (qvm && qvm instanceof viewModel.controlConstructors.SingleChoiceControl && qvm.choices.length <= 11) { %>\r\n                <div id="<%= qvm.inputId %>" class="form-control h-complex-form-control">\r\n                    <div class="row">\r\n                        <% if (!qvm.hasDefault && scale !== \'ctlCheckbox\') { %>\r\n                        <div class="<%= qvm.columnClass %> hidden-print">\r\n                            <div class="radio">\r\n                                <input id="input-<%= qvm.inputId %>-unanswered-input"\r\n                                       aria-labelledby="input-<%= qvm.inputId %>-unanswered-label"\r\n                                       type="radio" name="<%= qvm.inputId %>"\r\n                                       value=""\r\n                                       data-bind="checked: questionViewModels[\'q<%= scaleId %>\'].value" />\r\n                                <label id="input-<%= qvm.inputId %>-unanswered-label"\r\n                                       for="input-<%= qvm.inputId %>-unanswered-input"\r\n                                       class="h-unanswered">\r\n                                    Unanswered\r\n                                </label>\r\n                            </div>\r\n                        </div>\r\n                        <% } %>\r\n                        <% for(l = 0; l < qvm.choices.length; l++) {\r\n                        choice = qvm.choices[l]; %>\r\n                        <div class="<%= qvm.columnClass %>" data-bind="visible: !hideChoice(<%= scaleId%>,<%= choice.screenLookupId%>)">\r\n                            <div class="radio">\r\n                                <input id="<%= choice.inputId %>" aria-labelledby="<%= choice.labelId %>"\r\n                                       type="radio" name="<%= qvm.inputId %>" value="<%= choice.screenLookupId %>"\r\n                                       data-bind="checked: questionViewModels[\'q<%= scaleId %>\'].value"\r\n                                       class="h-bold-checked" />\r\n                                <label id="<%= choice.labelId %>"\r\n                                       for="<%= choice.inputId %>">\r\n                                    <%= choice.name %>\r\n                                    <% if (false) { %>\r\n                                    <small class="text-muted glyphicon glyphicon-share-alt"></small>\r\n                                    <% } %>\r\n                                    <small class="text-muted properties">\r\n                                        [<%= choice.choice.SCREENLOOKUPID\r\n                                        + (!isNullOrEmpty(choice.choice.SECONDARYVALUE) ? \'; SecondaryValue \' + choice.choice.SECONDARYVALUE : \'\')\r\n                                        + (choice.choice.NeedCodeID !== null ? \'; NeedCodeID: \' + choice.choice.NeedCodeID.toString() : \'\')\r\n                                        + (choice.choice.ValueID !== null ? \'; ValueID: \' + choice.choice.ValueID.toString() : \'\')\r\n                                        %>]\r\n                                    </small>\r\n                                </label>\r\n                            </div>\r\n                        </div>\r\n                        <% } %>\r\n                    </div>\r\n                </div>\r\n                <% } else if (qvm && qvm instanceof viewModel.controlConstructors.SingleChoiceControl) { %>\r\n                <select id="<%= qvm.inputId %>" class="form-control"\r\n                        data-bind="value: questionViewModels[\'q<%= scaleId %>\'].value,\r\n                                   css: { blank: isNullOrEmpty(questionViewModels[\'q<%= scaleId %>\'].value()) },\r\n                                   selectOptionQuestion: allowedChoices(<%= scaleId %>), scale: <%= scaleId %>"> ">\r\n                    <option value=""></option>\r\n                    <% for(l = 0; l < qvm.choices.length; l++) {\r\n                    choice = qvm.choices[l]; %>\r\n                    <option id="<%= choice.inputId %>" value="<%= choice.screenLookupId %>"><%= choice.name %></option>\r\n                    <% } %>\r\n                </select>\r\n                <% } else if(scale === \'ctlLabel\') { %>\r\n                <!--no code written inside else-if condition as no input control should be rendered for label control-->\r\n                <% } else if (scale === \'ctlSSNTextbox\' || (scale === \'ctlDemographicDataLookup\' && demographicField === \'lblSSN\')) { %>\r\n                <input id="<%= qvm.inputId %>" type="text" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"\r\n                       maxlength="11"\r\n                       data-bind="maskedValue: questionViewModels[\'q<%= scaleId %>\'].value, valueUpdate: \'input\', event: { blur: questionViewModels[\'q<%= scaleId %>\'].onBlur }"\r\n                       data-inputmask="\'mask\': \'XXX-XX-0000\', \'delimiter\':\'-\'" />\r\n                <a href="#" data-bind="visible: questionViewModels[\'q<%= scaleId %>\'].canUnmask, click: questionViewModels[\'q<%= scaleId %>\'].onUnmaskClick" class="ssn-unmask">Unmask</a>\r\n                <% } else if (scale === \'ctlEmailTextbox\' || (scale === \'ctlDemographicDataLookup\' && demographicField === \'lblEMAIL\')) { %>\r\n                <input id="<%= qvm.inputId %>" type="text" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="true"\r\n                       maxlength="<%= qvm.maxLength %>"\r\n                       data-bind="email: questionViewModels[\'q<%= scaleId %>\'].value, valueUpdate: \'input\'" />\r\n                <% } else if (scale === \'ctlPhoneTextbox\' || (scale === \'ctlDemographicDataLookup\' && [\'lblCELLPHONE\', \'lblWORKPHONE\', \'lblPHONE\'].indexOf(demographicField) !== -1)) { %>\r\n                <input id="<%= qvm.inputId %>" type="text" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"\r\n                       maxlength="14"\r\n                       data-bind="maskedValue: questionViewModels[\'q<%= scaleId %>\'].value, valueUpdate: \'input\'"\r\n                       data-inputmask="\'mask\': \'9(000)000-0000\', \'delimiter\':\'[\\\\(|\\\\)|\\\\-| ]\'" />\r\n                <% } else if (scale === \'ctlLookupDropDown\' && !this.screenDesignIsReadOnly && question.BEGINLEGEND === \'Worker\') { %>\r\n                <select id="<%= qvm.inputId %>" class="form-control"\r\n                        data-bind="options: workersLookup, optionsValue: \'MemberID\', optionsText: \'Description\', value : questionViewModels[\'q<%= scaleId %>\'].value, css: { blank: isNullOrEmpty(questionViewModels[\'q<%= scaleId %>\'].value()) }"></select>\r\n                <% } else if (qvm && qvm.typeaheadOptions && !this.screenDesignIsReadOnly && question.BEGINLEGEND === \'FundCodeProviders\' && (typeof WebIntakeSettings !== \'undefined\' && WebIntakeSettings != null) ? WebIntakeSettings.Type === \'APSWebIntake\' : false) { %>\r\n                <input id="<%= qvm.inputId %>"\r\n                       type="text" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="on" autocorrect="off" autocapitalize="yes" spellcheck="true"\r\n                       maxlength="<%= qvm.maxLength %>" minlength="0"\r\n                       data-bind="value: questionViewModels[\'q<%= scaleId %>\'].vendorID, valueUpdate: \'input\', autocapitalize: false, typeahead: questionViewModels[\'q<%= scaleId %>\'].typeaheadOptions, event: { blur: questionViewModels[\'q<%= scaleId %>\'].typeaheadOptions.blur }" />\r\n                <% } else if (qvm && qvm.typeaheadOptions && !this.screenDesignIsReadOnly && question.BEGINLEGEND === \'LawEnforcementAgency\' && (typeof WebIntakeSettings !== \'undefined\' && WebIntakeSettings != null) ? WebIntakeSettings.Type === \'APSWebIntake\' : false) { %>\r\n                <input id="<%= qvm.inputId %>"\r\n                       type="text" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="on" autocorrect="off" autocapitalize="yes" spellcheck="true"\r\n                       maxlength="<%= qvm.maxLength %>" minlength="0"\r\n                       data-bind="value: questionViewModels[\'q<%= scaleId %>\'].vendorID, valueUpdate: \'input\', autocapitalize: false, typeahead: questionViewModels[\'q<%= scaleId %>\'].typeaheadOptions, event: { blur: questionViewModels[\'q<%= scaleId %>\'].typeaheadOptions.blur }" />\r\n                <% } else if (qvm && qvm.typeaheadOptions && !this.screenDesignIsReadOnly && question.BEGINLEGEND !== \'Worker\') { %>\r\n                <input id="<%= qvm.inputId %>"\r\n                       type="text" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="true"\r\n                       maxlength="<%= qvm.maxLength %>"\r\n                       data-bind="value: questionViewModels[\'q<%= scaleId %>\'].value, valueUpdate: \'input\', autocapitalize: false, typeahead: questionViewModels[\'q<%= scaleId %>\'].typeaheadOptions, event: { blur: questionViewModels[\'q<%= scaleId %>\'].typeaheadOptions.blur }" />\r\n                <% } else if (qvm && qvm.typeaheadOptions && this.screenDesignIsReadOnly && question.BEGINLEGEND !== \'Worker\') { %>\r\n                <input id="<%= qvm.inputId %>" disabled="disabled" type="text" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="true"\r\n                       maxlength="<%= qvm.maxLength %>"\r\n                       data-bind="value: questionViewModels[\'q<%= scaleId %>\'].value, valueUpdate: \'input\', autocapitalize: false, typeahead: questionViewModels[\'q<%= scaleId %>\'].typeaheadOptions, event: { blur: questionViewModels[\'q<%= scaleId %>\'].typeaheadOptions.blur }" />\r\n                <% } else if (scale === \'ctlRichText\' && !this.screenDesignIsReadOnly) { %>\r\n                <div id="<%= qvm.inputId %>" contenteditable="true" class="form-control h-rich-text-form-control"\r\n                     maxlength="<%= qvm.maxLength %>"\r\n                     data-bind="richTextValue: questionViewModels[\'q<%= scaleId %>\'].value">\r\n                </div>\r\n                <% } else if (scale === \'ctlRichText\' && this.screenDesignIsReadOnly) { %>\r\n                <div id="<%= qvm.inputId %>" contenteditable="false" class="form-control h-rich-text-form-control"\r\n                     maxlength="<%= qvm.maxLength %>"\r\n                     data-bind="richTextValue: questionViewModels[\'q<%= scaleId %>\'].value">\r\n                </div>\r\n                <% } else if (qvm && qvm instanceof viewModel.controlConstructors.StringControl && (qvm.maxLength === null || qvm.maxLength === undefined || qvm.maxLength < 200)) { %>\r\n                <input id="<%= qvm.inputId %>" type="text" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="true"\r\n                       maxlength="<%= qvm.maxLength %>"\r\n                       data-bind="value: questionViewModels[\'q<%= scaleId %>\'].value, valueUpdate: \'input\', autocapitalize: false, maxlengthPopup: \'\'">\r\n                <% } else if (qvm && qvm instanceof viewModel.controlConstructors.StringControl) { %>\r\n                <textarea id="<%= qvm.inputId %>" type="text" placeholder="<%= qvm.placeholder %>"\r\n                          class="form-control" autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="true"\r\n                          maxlength="<%= qvm.maxLength %>" rows="3"\r\n                          data-bind="value: questionViewModels[\'q<%= scaleId %>\'].value, valueUpdate: \'input\', autocapitalize: false, maxlengthPopup: \'\'">\r\n                </textarea>\r\n                <% } else if (scale === \'ctlIndicatorField\' ||scale===\'ctlDateIndicatorField\' ||scale===\'ctlCommentIndicatorField\'||scale===\'ctlDecimalIndicatorField\'|| scale === \'ctlNumericIndicatorField\' || scale === \'ctlCalculatedField\' || scale === \'ctlRawScoreField\') { %>\r\n                <span class="input-decoration glyphicon-pro glyphicon-pro-calculator"\r\n                      data-bind="css: { \'text-success\': questionViewModels[\'q<%= scaleId %>\'].isAnswered, \'text-warning\': !questionViewModels[\'q<%= scaleId %>\'].isAnswered() }"></span>\r\n                <input id="<%= qvm.inputId %>" type="text" placeholder="<%= qvm.placeholder %>"\r\n                       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"\r\n                       readonly="readonly"\r\n                       data-bind="value: questionViewModels[\'q<%= scaleId %>\'].value" />\r\n                <small data-bind="visible: questionViewModels[\'q<%= scaleId %>\'].resolver.hasError" class=" text-danger">\r\n                    Unable to calculate indicator.&nbsp;&nbsp;<span data-bind="text: questionViewModels[\'q<%= scaleId %>\'].resolver.errorMessage"></span>\r\n                </small><br />\r\n                <% } else if(scale === \'ctlScreenDesignGridFieldControl\') { %>\r\n                <!-- ko compose: { model: questionViewModels[\'q<%= scaleId %>\'], view: \'assessments/controls/participant-list-control.html\' } --><!--/ko-->\r\n                <% } else if(scale === \'ctlMedicationDataForm\') { %>\r\n                <!-- ko compose: { model: questionViewModels[\'q<%= scaleId %>\'], view: \'assessments/controls/medication-list-control.html\' } --><!--/ko-->\r\n                <% } else if(scale === \'ctlRelationDataForm\') { %>\r\n                <!-- ko compose: { model: questionViewModels[\'q<%= scaleId %>\'], view: \'assessments/controls/relation-control.html\' } --><!--/ko-->\r\n                <% } else if(scale === \'ctlInstructionalText\') { %>\r\n                <div data-bind="html: questionViewModels[\'q<%= scaleId %>\'].value"></div>\r\n                <% } else { %>\r\n                <p><em class="text-warning">Unsupported control type: "<%= scale %>"</em></p>\r\n                <% } %>\r\n\r\n                <small class="text-muted properties glyphicon glyphicon-cog"></small>\r\n                <small class="text-muted properties"><%= htmlEncode(qvm.properties) %></small>\r\n            </div>\r\n            <% } %>\r\n        </form>\r\n    </div>\r\n</div>\r\n';});


define('text!assessments/details.html',[],function () { return '<form class="form-horizontal form-small" role="form" novalidate>\r\n    <fieldset>\r\n        <div class="form-group required">\r\n            <label for="ScreenDesign" class="col-sm-4 control-label">Assessment Form</label>\r\n            <div class="col-sm-8">\r\n                <select id="ScreenDesign" class="form-control input-sm no-watermark autofocus"\r\n                        data-bind="options: screenDesigns,\r\n                            optionsText: \'SCREENDESIGNNAME\',\r\n                            value: selectedScreenDesign,\r\n                            enable: enableScreenDesignDropdown && !isDetailReadOnly()"></select>\r\n                <small class="help-block">\r\n                    <span data-bind="visible: selectedScreenDesign().SCREENDESIGNHELP"><span data-bind="text: selectedScreenDesign().SCREENDESIGNHELP"></span><br /></span>\r\n                    Last Updated:&nbsp;<span data-bind="dateText: selectedScreenDesign().DATETIMESTAMP"></span>;\r\n                </small>\r\n            </div>\r\n        </div>\r\n        <div class="form-group"\r\n             data-bind="visible: security.getFieldVisible(\'ConsumerAssessments\', \'review\'),\r\n                        css: { required: security.getFieldRequired(\'ConsumerAssessments\', \'review\') }">\r\n            <label for="Review" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'ConsumerAssessments\', \'review\')"></label>\r\n            <div class="col-sm-8">\r\n                <select id="Review" class="form-control input-sm autofocus"\r\n                        data-bind="options: reviewTypes,\r\n                            optionsCaption: \'Enter \' + security.getFieldLabel(\'ConsumerAssessments\', \'review\'),\r\n                            value: detailsModel.Review,\r\n                            css: { blank: isNullOrEmpty(detailsModel.Review()) },\r\n                            enable: !isDetailReadOnly() && !security.getFieldReadOnly(\'ConsumerAssessments\', \'review\', entity)"></select>\r\n            </div>\r\n        </div>\r\n        <div class="form-group"\r\n             data-bind="visible: security.getFieldVisible(\'ConsumerAssessments\', \'reviewdate\'),\r\n                        css: { required: security.getFieldRequired(\'ConsumerAssessments\', \'reviewdate\') }">\r\n            <label for="ReviewDate" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'ConsumerAssessments\', \'reviewdate\')"></label>\r\n            <div class="col-sm-8">\r\n                <div class="input-group input-group-sm">\r\n                    <span class="input-group-btn">\r\n                        <button class="btn" type="button" tabindex="-1" data-bind="enable: !security.getFieldReadOnly(\'ConsumerAssessments\', \'reviewdate\', entity)">\r\n                            <span class="glyphicon glyphicon-th"></span>\r\n                        </button>\r\n                    </span>\r\n                    <input id="ReviewDate" class="form-control" type="text" min="1/1/1850" max="12/31/2250" placeholder="Enter Review Date"\r\n                           data-bind="dateValue: detailsModel.ReviewDate, enable: !isDetailReadOnly() && !security.getFieldReadOnly(\'ConsumerAssessments\', \'reviewdate\', entity)"\r\n                           autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                </div>\r\n            </div>\r\n        </div>\r\n        <div class="form-group"\r\n             data-bind="visible: security.getFieldVisible(\'ConsumerAssessments\', \'fundcode\'),\r\n                        css: { required: security.getFieldRequired(\'ConsumerAssessments\', \'fundcode\') }">\r\n            <label for="FundCode" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'ConsumerAssessments\', \'fundcode\')"></label>\r\n            <div class="col-sm-8">\r\n                <select id="FundCode" class="form-control input-sm"\r\n                        data-bind="options: fundCodes,\r\n                            optionsCaption: \'Enter \' + security.getFieldLabel(\'ConsumerAssessments\', \'fundcode\'),\r\n                            value: detailsModel.FundCode,\r\n                            css: { blank: isNullOrEmpty(detailsModel.FundCode()) },\r\n                            enable: !isDetailReadOnly() && !security.getFieldReadOnly(\'ConsumerAssessments\', \'fundcode\', entity)"></select>\r\n            </div>\r\n        </div>\r\n        <div class="form-group"\r\n             data-bind="visible: security.getFieldVisible(\'ConsumerAssessments\', \'program\'),\r\n                        css: { required: security.getFieldRequired(\'ConsumerAssessments\', \'program\') }">\r\n            <label for="Program" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'ConsumerAssessments\', \'program\')"></label>\r\n            <div class="col-sm-8">\r\n                <select id="Program" class="form-control input-sm"\r\n                        data-bind="options: programs,\r\n                            optionsText: \'Agency\',\r\n                            optionsValue: \'VendorID\',\r\n                            optionsCaption: \'Enter \' + security.getFieldLabel(\'ConsumerAssessments\', \'program\'),\r\n                            value: detailsModel.Program,\r\n                            css: { blank: isNullOrEmpty(detailsModel.Program()) },\r\n                            enable: !isDetailReadOnly() && !security.getFieldReadOnly(\'ConsumerAssessments\', \'program\', entity)"></select>\r\n            </div>\r\n        </div>\r\n        <div class="form-group"\r\n             data-bind="visible: security.getFieldVisible(\'ConsumerAssessments\', \'status\'),\r\n                        css: { required: security.getFieldRequired(\'ConsumerAssessments\', \'status\') }">\r\n            <label for="Status" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'ConsumerAssessments\', \'status\')"></label>\r\n            <div class="col-sm-8">\r\n                <select id="Status" class="form-control input-sm"\r\n                        data-bind="options: statuses,\r\n                            optionsCaption: \'Enter \' + security.getFieldLabel(\'ConsumerAssessments\', \'status\'),\r\n                            value: detailsModel.Status,\r\n                            css: { blank: isNullOrEmpty(detailsModel.Status()) },\r\n                            enable: !isDetailReadOnly() && !security.getFieldReadOnly(\'ConsumerAssessments\', \'status\', entity)"></select>\r\n            </div>\r\n        </div>\r\n        <!--MHFW-4045 Agency-->\r\n        <div class="form-group"\r\n             data-bind="visible: security.getFieldVisible(\'ConsumerAssessments\', \'agency\'),\r\n                        css: { required: security.getFieldRequired(\'ConsumerAssessments\', \'agency\') }">\r\n            <label for="Program" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'ConsumerAssessments\', \'agency\')"></label>\r\n            <div class="col-sm-8">\r\n                <select id="AgencySelect" class="form-control input-sm"\r\n                        data-bind="options: agencyPrograms,\r\n                            optionsText: \'Agency\',\r\n                            optionsValue: \'VendorID\',\r\n                            optionsCaption: \'Enter \' + security.getFieldLabel(\'ConsumerAssessments\', \'agency\'),\r\n                            value: detailsModel.Agency,\r\n                            css: { blank: isNullOrEmpty(detailsModel.Agency()) },\r\n                            enable: !isDetailReadOnly() && !security.getFieldReadOnly(\'ConsumerAssessments\', \'agency\', entity)"></select>\r\n            </div>\r\n        </div>\r\n        <!--MHFW-4045 Service Provider-->\r\n        <div class="form-group"\r\n             data-bind="visible: security.getFieldVisible(\'ConsumerAssessments\', \'serviceprovider\'),\r\n                        css: { required: security.getFieldRequired(\'ConsumerAssessments\', \'serviceprovider\') }">\r\n            <label for="Program" class="col-sm-4 control-label" data-bind="text: security.getFieldLabel(\'ConsumerAssessments\', \'serviceprovider\')"></label>\r\n            <div class="col-sm-8">\r\n                <select id="ServiceProvider" class="form-control input-sm"\r\n                        data-bind="options: serviceProviders,\r\n                            optionsText: \'Agency\',\r\n                            optionsValue: \'VendorID\',\r\n                            optionsCaption: \'Enter \' + security.getFieldLabel(\'ConsumerAssessments\', \'serviceprovider\'),\r\n                            value: detailsModel.ServiceProvider,\r\n                            css: { blank: isNullOrEmpty(detailsModel.ServiceProvider()) },\r\n                            enable: !isDetailReadOnly() && !security.getFieldReadOnly(\'ConsumerAssessments\', \'serviceprovider\', entity)"></select>\r\n            </div>\r\n        </div>\r\n    </fieldset>\r\n</form>\r\n';});


define('text!assessments/new.html',[],function () { return '<section class="container rootEntityViewModel">\r\n    <div class="command-bar btn-toolbar" role="toolbar"></div>\r\n\r\n    <!-- ko compose: \'core/validationSummary.html\' --><!-- /ko -->\r\n\r\n    <div class="content">\r\n        <div class="row">\r\n            <h3 class="text-center">\r\n                <span data-i18n="session.newAssessment"></span>:\r\n                <span data-bind="text: entity.ownerTitle"></span>\r\n            </h3>\r\n\r\n            <div class="col-sm-7 col-sm-offset-2" data-bind="compose: \'assessments/details.html\'">\r\n            </div>\r\n\r\n            <div class="col-sm-2">\r\n                <button type="button" class="btn btn-primary h-width-100-percent" data-bind="click: submit, disable: busy" data-i18n="common.open"></button>\r\n                <!--<button type="button" class="btn h-width-100-percent" data-bind="click: submitAndClose, disable: busy" data-i18n="common.saveAndClose"></button>-->\r\n                <button type="button" class="btn h-width-100-percent" data-bind="click: cancel, disable: busy" data-i18n="common.cancel"></button>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</section>';});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('assessments/new',["require", "exports", 'assessments/assessment-base', 'plugins/router', 'entities/api', 'core/viewmodels', 'assessments/consumer-mapper', 'assessments/screen-repo'], function (require, exports, AssessmentBase, durandalRouter, entities, viewmodels, mapper, screenDesignRepo) {
    var NewAssessment = (function (_super) {
        __extends(NewAssessment, _super);
        function NewAssessment() {
            _super.call(this);
            this.busy = ko.observable(false);
            this.enableScreenDesignDropdown = true;
        }
        NewAssessment.prototype.canDeactivate = function () {
            return Q.resolve(true);
        };
        NewAssessment.prototype.createCommands = function () {
            _super.prototype.createCommands.call(this);
            var Command = viewmodels.Command;
            this.commands.add('submit', new Command(this.submit.bind(this)));
            this.commands.add('submitAndClose', new Command(this.submitAndClose.bind(this)));
            this.commands.add('cancel', new Command(this.cancel.bind(this)));
        };
        NewAssessment.prototype.beforeFinishActivate = function () {
            var _this = this;
            return _super.prototype.beforeFinishActivate.call(this).then(function () {
                if (_this.screenDesigns.length === 0) {
                    _this.screenDesigns.push({ SCREENDESIGNNAME: '[no screen designs available]', SCREENDESIGNID: -1 });
                }
                if (_this.entity.ScreenDesignID()) {
                    _this.selectedScreenDesign(_this.screenDesigns.filter(function (s) { return s.SCREENDESIGNID === _this.entity.ScreenDesignID(); })[0] || _this.screenDesigns[0]);
                }
                else {
                    _this.selectedScreenDesign(_this.screenDesigns[0]);
                }
                if (_this.entity.FundCode && !_this.entity.FundCode() && _this.fundCodes && _this.fundCodes.length) {
                    _this.entity.FundCode(_this.fundCodes[0]);
                }
                if (_this.entity.Program && !_this.entity.Program() && _this.programs && _this.programs() && _this.programs().length === 1) {
                    _this.entity.Program(_this.programs()[0].VendorID);
                }
            });
        };
        NewAssessment.prototype.cancel = function () {
            this.close();
        };
        NewAssessment.prototype.submit = function () {
            this.submitInternal(false);
        };
        NewAssessment.prototype.submitAndClose = function () {
            this.submitInternal(true);
        };
        NewAssessment.prototype.submitInternal = function (saveAndClose) {
            var _this = this;
            this.entity.OwnerID(entities.getEntityId(this.entityManager.parentEntityManager.entity));
            this.entity.ScreenDesignID(this.selectedScreenDesign().SCREENDESIGNID);
            if (this.entity.entityType.name === entities.entityTypes.ConsumerAssessment) {
                this.entity.Assessment(this.selectedScreenDesign().SCREENDESIGNNAME);
                this.entity.OpenCloseID(security.getOpenCloseId(this.entityManager.parentEntityManager.entity, this.entity.FundCode()));
            }
            if (this.validate()) {
                this.busy(true);
                screenDesignRepo.getScreenDesign(this.entityManager.entity.ScreenDesignID()).then(function (form) { return mapper.mapToAssessment(_this.parentEntityManager.entity, _this.entityManager, form); }).then(function () {
                    if (_this.validate()) {
                        if (saveAndClose) {
                            _this.save().then(function (saveResult) { return _this.cancel(); }).fail(function (reason) {
                                return Q.reject(reason);
                            }).done();
                            return;
                        }
                        durandalRouter.navigate('#' + entities.getFragment(_this.entityManager));
                    }
                }).finally(function () { return _this.busy(false); }).done();
            }
        };
        return NewAssessment;
    })(AssessmentBase);
    return NewAssessment;
});


define('text!assessments/webIntake.html',[],function () { return '<section class="container assessment web-intake"\r\n         data-bind="css: { \'show-properties\': properties, \'show-narrative\': narrative, \'show-help\': help, \'show-edit-session\': editSession }">\r\n\r\n    <div class="alert alert-info" role="alert" data-bind="visible: app.consumerModule && isReadOnly()">\r\n        This record is no longer editable because it\'s status is <em data-bind="text: entity.Status"></em>.\r\n    </div>\r\n\r\n    <p class="lead" style="margin-top: 20px" data-bind="html: WebIntakeSettings.Instructions"></p>\r\n\r\n    <div class="content">\r\n        <!-- ko compose: \'assessments/data-entry.html\' --><!-- /ko -->\r\n    </div>\r\n\r\n    <!-- ko compose: \'core/validationSummary.html\' --><!-- /ko -->\r\n\r\n    <div>\r\n        <p class="lead" data-bind="html: WebIntakeSettings.FooterInstructions"></p>\r\n        <!--<div class="pull-left hidden-print" style="margin-bottom: 20px">\r\n            <div id="google_translate_element"></div>\r\n        </div>-->\r\n        <div class="pull-right hidden-print" style="margin-bottom: 20px">\r\n            <button type="button" class="btn btn-lg"\r\n                    data-bind="click: $parent.saveDraft, disable: $parent.isSubmitting, visible: webIntakeActionButtons.showSubmit() && app.consumerModule">\r\n                <span class="glyphicon glyphicon-pencil"></span> Save Draft\r\n            </button>\r\n            <button type="button" class="btn btn-lg btn-success"\r\n                    data-bind="click: $parent.savePending, disable: $parent.isSubmitting, visible: webIntakeActionButtons.showSubmit">\r\n                <span class="glyphicon glyphicon-ok"></span> Submit\r\n            </button>\r\n            <button type="button" class="btn btn-lg btn-danger"\r\n                    data-bind="click: $parent.cancel, disable: $parent.isSubmitting, visible: webIntakeActionButtons.showCancel" reporter-btn-cancel>\r\n                <span class="glyphicon glyphicon-remove"></span> Cancel\r\n            </button>\r\n            <button type="button" class="btn btn-lg hidden-xs"\r\n                    data-bind="click: $parent.print, visible: webIntakeActionButtons.showPrint">\r\n                <span class="glyphicon glyphicon-print"></span> Print\r\n            </button>\r\n        </div>\r\n    </div>\r\n</section>';});

define('bindings/autocapitalize',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers['autocapitalize'] = {
            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                var modelProperty = null, allWords = ko.utils.unwrapObservable(valueAccessor());
                if (allBindingsAccessor.has('value') && typeof allBindingsAccessor.get('value') === 'function') {
                    modelProperty = allBindingsAccessor.get('value');
                }
                $(element).on('keyup', function (e) {
                    if (element.value.match(/^[a-z]/) || allWords && element.value.match(/\s[a-z]/)) {
                        element.value = element.value.replace(/^[a-z]/, function (letter) { return letter.toUpperCase(); });
                        if (allWords) {
                            element.value = element.value.replace(/\s[a-z]/, function (letter) { return letter.toUpperCase(); });
                        }
                        if (modelProperty !== null && modelProperty() !== element.value) {
                            modelProperty(element.value);
                        }
                    }
                });
            },
            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/koUtil',["require", "exports"], function (require, exports) {
    function writeValueToProperty(property, allBindings, key, value, checkIfDifferent) {
        if (!property || !ko.isObservable(property)) {
            var propWriters = allBindings.get('_ko_property_writers');
            if (propWriters && propWriters[key])
                propWriters[key](value);
        }
        else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
            property(value);
        }
    }
    exports.writeValueToProperty = writeValueToProperty;
});

define('bindings/value',["require", "exports", 'bindings/koUtil'], function (require, exports, koUtil) {
    function initialize() {
        var originalInit = ko.bindingHandlers.value.init;
        function myInit(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            if (element.tagName.toLowerCase() === "input" && element.type === "text") {
                $(element).on('blur', function (event) {
                    var trimmedValue;
                    if (typeof element.value === 'string' && element.value && element.value !== '') {
                        trimmedValue = element.value.trim();
                        if (element.value === trimmedValue)
                            return;
                        element.value = trimmedValue;
                        koUtil.writeValueToProperty(valueAccessor(), allBindingsAccessor, 'trimmedValue', trimmedValue, true);
                    }
                });
            }
            originalInit(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
        }
        ;
        ko.bindingHandlers.value.init = myInit;
    }
    exports.initialize = initialize;
});

define('bindings/dateText',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers['dateText'] = {
            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            },
            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                var value = valueAccessor(), allBindings = allBindingsAccessor();
                var valueUnwrapped = ko.utils.unwrapObservable(value);
                var pattern = allBindings.datePattern || 'M/D/YYYY';
                var text = '';
                if (valueUnwrapped !== null) {
                    text = moment(valueUnwrapped).format(pattern);
                }
                $(element).text(text);
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/dateValue',["require", "exports", 'bindings/koUtil', 'core/constants'], function (require, exports, koUtil, constants) {
    function displayValidState(element, isElementValueValid) {
        var $formGroup = $(element).closest('.form-group');
        if (isElementValueValid) {
            $formGroup.removeClass('has-input-error');
        }
        else {
            $formGroup.addClass('has-input-error');
        }
    }
    function createMeta(element, valueAccessor, allBindingsAccessor) {
        var meta = {
            previousValue: null,
            nullable: true,
            min: moment(constants.date.min),
            max: moment(constants.date.max),
            parser: null,
            formatString: 'M/D/YYYY',
            datePickerMinViewMode: 0,
            valueType: ValueType.Date,
            ignoreChangeDateEvent: false
        };
        if (element.max) {
            meta.max = moment(element.max);
        }
        if (element.min) {
            meta.min = moment(element.min);
        }
        if (allBindingsAccessor().hasOwnProperty('valueType')) {
            meta.valueType = allBindingsAccessor().valueType === 'number' ? 'number' : 'Date';
        }
        var modelValue = getModelValue(valueAccessor, meta);
        if (modelValue !== null) {
            meta.previousValue = moment(modelValue);
        }
        if (allBindingsAccessor().hasOwnProperty('nullable')) {
            meta.nullable = allBindingsAccessor().nullable && true;
        }
        meta.parser = new DateInputParser(allBindingsAccessor().inputMode, meta.nullable, meta.min, meta.max);
        if (meta.parser.inputMode === InputMode.MonthYear) {
            meta.formatString = 'M/YYYY';
            meta.datePickerMinViewMode = 1;
        }
        else if (meta.parser.inputMode === InputMode.Year) {
            meta.formatString = 'YYYY';
            meta.datePickerMinViewMode = 2;
        }
        $(element).data('dateValue', meta);
        return meta;
    }
    function getModelValue(valueAccessor, meta) {
        var modelValue = ko.utils.unwrapObservable(valueAccessor()), m;
        if (modelValue === null)
            return null;
        if (meta.valueType === ValueType.Number) {
            m = moment([modelValue, 0, 1]);
        }
        else {
            m = moment(modelValue);
        }
        if (!m.isValid()) {
            if (meta.valueType === ValueType.Date) {
                throw new Error('The model value must be null or a valid date.');
            }
            else {
                throw new Error('The model value must be null or a valid year number.');
            }
        }
        return m.toDate();
    }
    function getModelValueString(valueAccessor, meta) {
        var modelValue = getModelValue(valueAccessor, meta), modelValueString;
        if (modelValue !== null && !moment(modelValue).isValid()) {
            throw new Error('The model value must be null or a valid date.');
        }
        if (modelValue === null) {
            modelValueString = '';
        }
        else {
            modelValueString = moment(modelValue).format(meta.formatString);
        }
        return modelValueString;
    }
    function preventFutureDate(inpitID) {
        if (inpitID !== null && inpitID !== '') {
            var num = inpitID.split('-');
            var sScaleID = parseInt(num[1]);
            var retrievedSqQuestionsJSON = localStorage.getItem("sqQuestionspre");
            var parseretrievedSqQuestionsJSON = JSON.parse(retrievedSqQuestionsJSON);
            if (parseretrievedSqQuestionsJSON != null) {
                for (var i = 0; i < parseretrievedSqQuestionsJSON.length; i++) {
                    if (parseretrievedSqQuestionsJSON[i].SCREENSCALEID === sScaleID) {
                        if (parseretrievedSqQuestionsJSON[i].PreventFutureDate === true)
                            return true;
                        else
                            return false;
                    }
                }
            }
        }
    }
    function updateElementValueUsingModelValue(element, valueAccessor, allBindingsAccessor) {
        var elementValue = ko.selectExtensions.readValue(element), meta = $(element).data('dateValue'), modelValueString = getModelValueString(valueAccessor, meta);
        if (typeof elementValue !== 'string') {
            throw new Error('elementValue is not of type "string"');
        }
        if (modelValueString !== elementValue) {
            ko.selectExtensions.writeValue(element, modelValueString);
            elementValue = ko.selectExtensions.readValue(element);
            displayValidState(element, true);
        }
        var sID = preventFutureDate(element.id);
        if (elementValue !== null && sID === true) {
            var strTextToParse = elementValue.split('/', 3);
            if (strTextToParse.length == 3 && strTextToParse != null) {
                var getMonth = strTextToParse[0].length;
                var getDay = strTextToParse[1].length;
                var getYear = strTextToParse[2].length;
                if ((getMonth === 2 && getDay === 2 && getYear === 4) || (getMonth === 2 && getDay === 1 && getYear === 4) || (getMonth === 1 && getDay === 2 && getYear === 4) || (getMonth === 1 && getDay === 1 && getYear === 4))
                    var myDate = new Date(elementValue);
                var today = new Date();
                if (myDate > today) {
                    alert("A future date is not allowed, please either enter today's date or a past date.");
                    element.value = '';
                    return { valid: false };
                }
            }
        }
    }
    function updateModelValueUsingElementValue(element, valueAccessor, allBindingsAccessor) {
        var meta = $(element).data('dateValue'), elementValue = ko.selectExtensions.readValue(element), parseResult = meta.parser.ParseDate(elementValue), modelValue = valueAccessor(), unwrappedModelValue = ko.utils.unwrapObservable(valueAccessor());
        if (parseResult.valid) {
            if (parseResult.date === null) {
                if (unwrappedModelValue === null)
                    return;
                koUtil.writeValueToProperty(modelValue, allBindingsAccessor, 'dateValue', null);
            }
            else if (meta.valueType === ValueType.Date) {
                if (unwrappedModelValue !== null && moment(unwrappedModelValue).isSame(parseResult.date))
                    return;
                koUtil.writeValueToProperty(modelValue, allBindingsAccessor, 'dateValue', parseResult.date.toDate());
            }
            else {
                if (unwrappedModelValue !== null && +unwrappedModelValue === parseResult.date.year())
                    return;
                koUtil.writeValueToProperty(modelValue, allBindingsAccessor, 'dateValue', parseResult.date.year());
            }
        }
        else {
            updateElementValueUsingModelValue(element, valueAccessor, allBindingsAccessor);
        }
    }
    function showPicker(meta, components) {
        var hideTimeoutHandle = 0;
        components.$element.tooltip('destroy');
        updateModelValueUsingElementValue(components.element, components.valueAccessor, components.allBindingsAccessor);
        meta.ignoreChangeDateEvent = true;
        components.$element.datepicker('update');
        meta.ignoreChangeDateEvent = false;
        components.$element.datepicker('show');
        components.$element.attr('tabIndex', '9999');
        $('div.datepicker').css('z-index', '2000').attr('tabindex', '9998').focus().focusout(function () {
            hideTimeoutHandle = setTimeout(function () {
                components.$element.datepicker('hide');
                components.$element.removeAttr('tabIndex');
            }, 200);
        }).focusin(function () { return clearTimeout(hideTimeoutHandle); }).on('click', function (e) {
            var target = $(e.target).closest('span, td, th');
            if (target[0].className == 'prev' || target[0].className == 'next') {
                document.getElementsByClassName('datepicker datepicker-dropdown')[0].focus();
            }
        });
    }
    function init(element, valueAccessor, allBindingsAccessor) {
        var meta = createMeta(element, valueAccessor, allBindingsAccessor), components = {
            $element: $(element),
            $button: $(element).closest('.input-group').find('.input-group-btn > button'),
            element: element,
            valueAccessor: valueAccessor,
            allBindingsAccessor: allBindingsAccessor
        }, tooltipOptions = { placement: 'top', trigger: 'manual', animation: false, title: '' };
        components.$element.datepicker({
            format: meta.formatString.toLowerCase(),
            keyboardNavigation: false,
            forceParse: false,
            autoclose: true,
            todayHighlight: true,
            minViewMode: meta.datePickerMinViewMode,
            startDate: meta.min.toDate(),
            endDate: meta.max.toDate()
        });
        components.$element.datepicker().off('focus').on('keydown', function (event) {
            if (event.which !== 32 || element.readOnly || element.isDisabled) {
                return;
            }
            event.preventDefault();
            showPicker(meta, components);
        }).on('changeDate', function (event) {
            if (meta.ignoreChangeDateEvent)
                return;
            updateModelValueUsingElementValue(element, valueAccessor, allBindingsAccessor);
            components.$element.removeAttr('tabIndex');
            setTimeout(function () { return components.$element.focus(); }, 100);
        });
        components.$button.on('click', function () { return showPicker(meta, components); });
        var eventsToCatch = ['change', 'keyup', 'keypress', 'paste'];
        var propertyChangedFired = false;
        var valueUpdateHandler = function () {
            propertyChangedFired = false;
            var elementValue = ko.selectExtensions.readValue(element);
            if (typeof elementValue !== 'string') {
                throw new Error('elementValue is not of type "string"');
            }
            var parseResult = meta.parser.ParseDate(elementValue);
            if (parseResult.valid) {
                if (parseResult.date === null) {
                    tooltipOptions.title = '(blank)';
                }
                else {
                    tooltipOptions.title = parseResult.date.format(meta.formatString);
                }
                displayValidState(element, true);
            }
            else {
                tooltipOptions.title = '(invalid)';
                displayValidState(element, false);
            }
            components.$element.tooltip(tooltipOptions);
            components.$element.tooltip('hide').attr('data-original-title', tooltipOptions.title).tooltip('fixTitle').tooltip('show');
        };
        components.$element.on('blur', function (e) {
            setTimeout(function () { return $(element).tooltip('destroy'); }, 10);
            updateModelValueUsingElementValue(element, valueAccessor, allBindingsAccessor);
        });
        var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == 'input' && element.type == 'text' && element.autocomplete != 'off' && (!element.form || element.form.autocomplete != 'off');
        if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, 'propertychange') == -1) {
            ko.utils.registerEventHandler(element, 'propertychange', function () {
                propertyChangedFired = true;
            });
            ko.utils.registerEventHandler(element, 'focus', function () {
                propertyChangedFired = false;
            });
            ko.utils.registerEventHandler(element, 'blur', function () {
                if (propertyChangedFired) {
                    valueUpdateHandler();
                }
            });
        }
        var updateTimeoutHandle = 0;
        var changeHandler = function () {
            clearTimeout(updateTimeoutHandle);
            updateTimeoutHandle = setTimeout(valueUpdateHandler, 10);
        };
        ko.utils.arrayForEach(eventsToCatch, function (eventName) {
            ko.utils.registerEventHandler(element, eventName, changeHandler);
        });
    }
    function initialize() {
        ko.bindingHandlers['dateValue'] = {
            'after': ['options', 'foreach'],
            'init': init,
            'update': updateElementValueUsingModelValue
        };
    }
    exports.initialize = initialize;
    var InputMode = {
        Date: 'Date',
        MonthYear: 'MonthYear',
        Year: 'Year'
    };
    var ValueType = {
        Date: 'Date',
        Number: 'number'
    };
    var DateInputParser = (function () {
        function DateInputParser(inputMode, nullable, min, max) {
            this.inputMode = inputMode;
            this.nullable = nullable;
            this.min = min;
            this.max = max;
            this.daysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
            if (!inputMode) {
                this.inputMode = InputMode.Date;
            }
        }
        DateInputParser.prototype.ParseDate = function (textToParse) {
            var year = (new Date()).getFullYear(), month = 1, day = 1, hour = 0, minute = 0, second = 0, millisecond = 0, nextIndex = 0, temp, part;
            if (typeof textToParse !== 'string') {
                throw new Error('elementValue is not of type "string"');
            }
            if (textToParse === '') {
                return { valid: this.nullable, date: null };
            }
            if (this.inputMode === InputMode.Date) {
                temp = this.tryParseSpecialText(textToParse);
                if (temp.valid) {
                    return temp;
                }
            }
            if (this.inputMode !== InputMode.Year) {
                part = this.tryParseMonth(textToParse);
                if (!part.valid) {
                    return { valid: false };
                }
                month = part.value;
                nextIndex = part.nextIndex;
            }
            if (nextIndex < textToParse.length && this.inputMode !== InputMode.MonthYear && this.inputMode !== InputMode.Year) {
                part = this.tryParseDay(textToParse, month, nextIndex);
                if (!part.valid) {
                    return { valid: false };
                }
                day = part.value;
                nextIndex = part.nextIndex;
            }
            if (nextIndex < textToParse.length) {
                part = this.tryParseYear(textToParse, nextIndex);
                if (!part.valid) {
                    return { valid: false };
                }
                year = part.value;
                nextIndex = part.nextIndex;
            }
            if (nextIndex < textToParse.length) {
                return { valid: false };
            }
            var m = moment([year, month - 1, day]);
            if (m.isValid()) {
                if (m.isAfter(this.max) || m.isBefore(this.min)) {
                    return { valid: false };
                }
                return { valid: true, date: m };
            }
            return { valid: false };
        };
        DateInputParser.prototype.tryParseSpecialText = function (s) {
            s = s.toLowerCase();
            if (s.length <= 8 && "tomorrow".substr(0, s.length) === s && s.length > 2) {
                return { valid: true, date: moment().add('days', 1) };
            }
            if (s.length <= 5 && "today".substr(0, s.length) === s) {
                return { valid: true, date: moment() };
            }
            if (s.length <= 9 && "yesterday".substr(0, s.length) === s) {
                return { valid: true, date: moment().add('days', -1) };
            }
            return { valid: false };
        };
        DateInputParser.prototype.tryParseMonth = function (s) {
            if (/^1[0-2]\//.test(s) || /^0[1 - 9]\//.test(s)) {
                return {
                    valid: true,
                    nextIndex: 3,
                    value: parseInt(s.substr(0, 2))
                };
            }
            if (/^[1-9]\//.test(s) || /^1[0-2]/.test(s) || /^0[1-9]/.test(s)) {
                return {
                    valid: true,
                    nextIndex: 2,
                    value: parseInt(s.substr(0, 2).replace('/', ''))
                };
            }
            if (/^[2-9]/.test(s)) {
                return {
                    valid: true,
                    nextIndex: 1,
                    value: parseInt(s.substr(0, 1))
                };
            }
            if (/^1$/.test(s)) {
                return {
                    valid: true,
                    nextIndex: 1,
                    value: 1
                };
            }
            if (/^0$/.test(s)) {
                return {
                    valid: true,
                    nextIndex: 1,
                    value: 1
                };
            }
            return { valid: false };
        };
        DateInputParser.prototype.tryParseDay = function (s, month, index) {
            var days = this.daysInMonth[month - 1];
            s = s.substr(index);
            if (/^[1-2][0-9]\//.test(s) || /^0[1-9]\//.test(s) || /^3[0-1]\//.test(s) && days == 31 || /^30\//.test(s) && days >= 30) {
                return {
                    valid: true,
                    nextIndex: index + 3,
                    value: parseInt(s.substr(0, 2))
                };
            }
            if (/^[1-2][0-9]/.test(s) || /^0[1-9]/.test(s) || /^3[0-1]/.test(s) && days == 31 || /^30/.test(s) && days >= 30 || /^[1-9]\//.test(s)) {
                return {
                    valid: true,
                    nextIndex: index + 2,
                    value: parseInt(s.substr(0, 2).replace('/', ''))
                };
            }
            if (/^0$/.test(s)) {
                return {
                    valid: true,
                    nextIndex: index + 1,
                    value: 1
                };
            }
            if (/^[3-9][0-9]/.test(s) && parseInt(s.substr(0, 2)) > days) {
                return {
                    valid: true,
                    nextIndex: index + 1,
                    value: parseInt(s.substr(0, 1))
                };
            }
            if (/^[1-9]$/.test(s)) {
                return {
                    valid: true,
                    nextIndex: index + 1,
                    value: parseInt(s.substr(0, 1))
                };
            }
            return { valid: false };
        };
        DateInputParser.prototype.tryParseYear = function (s, index) {
            s = s.substr(index);
            if (/^19[0-9][0-9]/.test(s) || /^2[0-1][0-9][0-9]/.test(s) || /^22[0-5][0-9]/.test(s)) {
                return {
                    valid: true,
                    nextIndex: index + 4,
                    value: parseInt(s.substr(0, 4))
                };
            }
            if (/^19[0-9]/.test(s) || /^2[0-1][0-9]/.test(s) || /^22[0-5]/.test(s)) {
                return {
                    valid: true,
                    nextIndex: index + 3,
                    value: parseInt(s.substr(0, 3)) * 10
                };
            }
            if (/^19$/.test(s) || /^20$/.test(s)) {
                return {
                    valid: true,
                    nextIndex: index + 2,
                    value: parseInt(s.substr(0, 2)) * 100
                };
            }
            if (/^[0-9]{1,2}$/.test(s)) {
                return {
                    valid: true,
                    nextIndex: index + s.length,
                    value: 2000 + parseInt(s)
                };
            }
            return { valid: false };
        };
        return DateInputParser;
    })();
});

define('bindings/fadeVisible',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers['fadeVisible'] = {
            init: function (element, valueAccessor) {
                var value = valueAccessor();
                $(element).toggle(ko.unwrap(value));
            },
            update: function (element, valueAccessor) {
                var value = valueAccessor();
                ko.unwrap(value) ? $(element).toggle(true) : $(element).fadeOut();
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/focusin',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers['focusin'] = {
            init: function (element, valueAccessor) {
                $(element).focusin(function () {
                    var value = valueAccessor();
                    value(true);
                });
                $(element).focusout(function () {
                    var value = valueAccessor();
                    value(false);
                });
            },
            update: function (element, valueAccessor) {
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/maskedValue',["require", "exports"], function (require, exports) {
    function displayValidState(element, valid, silent) {
        var $formGroup = $(element).closest('.form-group');
        $formGroup.toggleClass('has-warning', !valid);
        if (valid && !silent) {
            $formGroup.addClass('has-success');
            setTimeout(function () { return $formGroup.removeClass('has-success'); }, 1000);
        }
        else {
            $formGroup.removeClass('has-success');
        }
    }
    function validate(value, pattern) {
        return StringMask.validate(value, pattern);
    }
    function partialMask(value, pattern) {
        var index = getSubstringIndex(pattern.replace(/[9X]/g, '0'), '0', value.length - 1);
        var partialPattern = pattern.substr(0, index + 1);
        return StringMask.apply(value, partialPattern);
    }
    function getSubstringIndex(str, substring, n) {
        var times = 0, index = null;
        while (times < n && index !== -1) {
            index = str.indexOf(substring, index + 1);
            times++;
        }
        return index;
    }
    function valueUpdateHandler(element, valueAccessor, allBindings, resetInvalid) {
        var newValue = "";
        var modelValue = ko.utils.unwrapObservable(valueAccessor());
        var elementValue = ko.selectExtensions.readValue(element);
        if (modelValue === elementValue) {
            displayValidState(element, true, true);
            return;
        }
        if (elementValue === "") {
            displayValidState(element, true, true);
            valueAccessor()(elementValue);
            return;
        }
        var maskOptions = getMaskOptions(element);
        var regDelimiter = new RegExp(maskOptions.delimiter, 'gi');
        elementValue = elementValue.replace(regDelimiter, '');
        if (validate(elementValue, maskOptions.mask)) {
            displayValidState(element, true, false);
            newValue = StringMask.apply(elementValue, maskOptions.mask);
            valueAccessor()(newValue);
            element.value = newValue;
        }
        else {
            if (!resetInvalid) {
                element.value = partialMask(elementValue, maskOptions.mask);
                displayValidState(element, false, false);
            }
            else {
                element.value = modelValue;
                displayValidState(element, true, true);
            }
        }
    }
    function bindEvents(element, valueAccessor, allBindings) {
        var eventsToCatch = ["change"];
        var requestedEventsToCatch = allBindings['get']("valueUpdate");
        var propertyChangedFired = false;
        if (requestedEventsToCatch) {
            if (typeof requestedEventsToCatch == "string") {
                requestedEventsToCatch = [requestedEventsToCatch];
            }
            ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
            eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
        }
        $(element).blur(function () {
            valueUpdateHandler(element, valueAccessor, allBindings, true);
        });
        var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text" && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
        if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
            ko.utils.registerEventHandler(element, "propertychange", function () {
                propertyChangedFired = true;
            });
            ko.utils.registerEventHandler(element, "focus", function () {
                propertyChangedFired = false;
            });
            ko.utils.registerEventHandler(element, "blur", function () {
                if (propertyChangedFired) {
                    propertyChangedFired = false;
                    valueUpdateHandler(element, valueAccessor, allBindings, true);
                }
            });
        }
        ko.utils.arrayForEach(eventsToCatch, function (eventName) {
            var handler = function () {
                valueUpdateHandler(element, valueAccessor, allBindings);
            };
            if (ko.utils.stringStartsWith(eventName, "after")) {
                handler = function () {
                    setTimeout(function () {
                        valueUpdateHandler(element, valueAccessor, allBindings);
                    }, 0);
                };
                eventName = eventName.substring("after".length);
            }
            ko.utils.registerEventHandler(element, eventName, handler);
        });
    }
    function getMaskOptions(element) {
        var rawMaskOptions = $(element).data("inputmask");
        var maskOptions;
        if (rawMaskOptions && rawMaskOptions != "") {
            try {
                rawMaskOptions = rawMaskOptions.replace(new RegExp("'", "g"), '"');
                maskOptions = $.parseJSON("{" + rawMaskOptions + "}");
            }
            catch (ex) {
            }
        }
        return maskOptions;
    }
    function numericOnly(e) {
        var decimal = $.data(this, "numeric.decimal");
        var negative = $.data(this, "numeric.negative");
        var decimalPlaces = $.data(this, "numeric.decimalPlaces");
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13 && this.nodeName.toLowerCase() == "input") {
            return true;
        }
        else if (key == 13) {
            return false;
        }
        var allow = false;
        if ((e.ctrlKey && key == 97) || (e.ctrlKey && key == 65)) {
            return true;
        }
        if ((e.ctrlKey && key == 120) || (e.ctrlKey && key == 88)) {
            return true;
        }
        if ((e.ctrlKey && key == 99) || (e.ctrlKey && key == 67)) {
            return true;
        }
        if ((e.ctrlKey && key == 122) || (e.ctrlKey && key == 90)) {
            return true;
        }
        if ((e.ctrlKey && key == 118) || (e.ctrlKey && key == 86) || (e.shiftKey && key == 45)) {
            return true;
        }
        if (key < 48 || key > 57) {
            var value = $(this).val();
            if ($.inArray('-', value.split('')) !== 0 && negative && key == 45 && (value.length === 0 || parseInt($.fn.getSelectionStart(this), 10) === 0)) {
                return true;
            }
            if (decimal && key == decimal.charCodeAt(0) && $.inArray(decimal, value.split('')) != -1) {
                allow = false;
            }
            if (key != 8 && key != 9 && key != 13 && key != 35 && key != 36 && key != 37 && key != 39 && key != 46) {
                allow = false;
            }
            else {
                if (typeof e.charCode != "undefined") {
                    if (e.keyCode == e.which && e.which !== 0) {
                        allow = true;
                        if (e.which == 46) {
                            allow = false;
                        }
                    }
                    else if (e.keyCode !== 0 && e.charCode === 0 && e.which === 0) {
                        allow = true;
                    }
                }
            }
            if (decimal && key == decimal.charCodeAt(0)) {
                if ($.inArray(decimal, value.split('')) == -1) {
                    allow = true;
                }
                else {
                    allow = false;
                }
            }
        }
        else {
            allow = true;
            if (decimal && decimalPlaces > 0) {
                var dot = $.inArray(decimal, $(this).val().split(''));
                if (dot >= 0 && $(this).val().length > dot + decimalPlaces) {
                    allow = false;
                }
            }
        }
        return allow;
    }
    ;
    function initialize() {
        ko.bindingHandlers['maskedValue'] = {
            after: ['options', 'foreach'],
            init: function (element, valueAccessor, allBindings) {
                $(element).keypress(numericOnly);
                bindEvents(element, valueAccessor, allBindings);
            },
            update: function (element, valueAccessor, allBindings) {
                var newValue = ko.utils.unwrapObservable(valueAccessor());
                var elementValue = ko.selectExtensions.readValue(element);
                var valueHasChanged = (newValue !== elementValue);
                if (valueHasChanged) {
                    ko.selectExtensions.writeValue(element, newValue);
                }
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/numberValue',["require", "exports", 'bindings/koUtil'], function (require, exports, koUtil) {
    function validateElementValue(elementValue, meta) {
        if (typeof elementValue !== 'string') {
            throw new Error('elementValue is not of type "string"');
        }
        if (!meta.regex.test(elementValue))
            return false;
        if (elementValue !== '') {
            if (meta.max && +elementValue > meta.max)
                return false;
            if (meta.min && +elementValue < meta.min)
                return false;
        }
        return true;
    }
    function displayValidState(element, isElementValueValid) {
        var $formGroup = $(element).closest('.form-group');
        if (isElementValueValid) {
            $formGroup.removeClass('has-input-error');
        }
        else {
            $formGroup.addClass('has-input-error');
        }
    }
    function createMeta(element, valueAccessor, allBindingsAccessor) {
        var meta = {
            previousValue: 0,
            nullable: true,
            max: 9999999.99,
            min: -999999.99,
            allowDecimal: true,
            decimalLength: 0,
            regex: null
        };
        if (element.max) {
            meta.max = parseFloat(element.max);
        }
        if (element.getAttribute('rmin')) {
            meta.min = parseFloat(element.getAttribute('rmin'));
        }
        meta.allowDecimal = meta.max !== Math.floor(meta.max);
        var len = Math.floor(meta.max).toString().length;
        meta.decimalLength = meta.max.toString().length - len - 1;
        var pattern = "^-?\\d{" + (meta.nullable ? "0" : "1") + "," + len.toString() + "}" + (meta.allowDecimal ? "(\\.\\d{0," + meta.decimalLength + "}){0,1}" : "") + "$";
        meta.regex = new RegExp(pattern);
        var modelValue = ko.utils.unwrapObservable(valueAccessor());
        if (typeof modelValue === 'string' && meta.regex.test(modelValue)) {
            modelValue = parseFloat(modelValue);
        }
        if (typeof modelValue !== 'number' && modelValue !== null) {
            throw new Error('The model value is not of type "number" or null');
        }
        meta.previousValue = modelValue;
        if (allBindingsAccessor().hasOwnProperty('nullable')) {
            meta.nullable = allBindingsAccessor().nullable && true;
        }
        $(element).data('numberValue', meta);
        return meta;
    }
    function getModelValueString(element, valueAccessor, meta) {
        var modelValue = ko.utils.unwrapObservable(valueAccessor()), isFocused = $(element).is(':focus'), modelValueString;
        if (typeof modelValue === 'string' && meta.regex.test(modelValue)) {
            modelValue = parseFloat(modelValue);
        }
        if (typeof modelValue !== 'number' && modelValue !== null) {
            throw new Error('The model value is not of type "number" or null');
        }
        if (modelValue === null) {
            modelValueString = '';
        }
        else if (isFocused || meta.allowDecimal === false) {
            modelValueString = modelValue.toString();
        }
        else {
            modelValueString = modelValue.toFixed(meta.decimalLength);
        }
        return modelValueString;
    }
    function update(element, valueAccessor, allBindingsAccessor) {
        var elementValue = ko.selectExtensions.readValue(element), meta = $(element).data('numberValue'), modelValueString = getModelValueString(element, valueAccessor, meta);
        if (typeof elementValue !== 'string') {
            throw new Error('elementValue is not of type "string"');
        }
        if (modelValueString !== elementValue) {
            ko.selectExtensions.writeValue(element, modelValueString);
            elementValue = ko.selectExtensions.readValue(element);
            displayValidState(element, validateElementValue(elementValue, meta));
        }
    }
    function init(element, valueAccessor, allBindingsAccessor) {
        var meta = createMeta(element, valueAccessor, allBindingsAccessor), $element = $(element);
        var eventsToCatch = ['change', 'keyup', 'keypress', 'paste'];
        var propertyChangedFired = false;
        var valueUpdateHandler = function () {
            propertyChangedFired = false;
            var modelValue = valueAccessor(), unwrappedModelValue = ko.utils.unwrapObservable(valueAccessor()), elementValue = ko.selectExtensions.readValue(element), isElementValueValid = validateElementValue(elementValue, meta), parsedElementValue = parseFloat(elementValue);
            if (isElementValueValid) {
                if (isNaN(parsedElementValue)) {
                    parsedElementValue = null;
                }
                if (parsedElementValue === unwrappedModelValue)
                    return;
                koUtil.writeValueToProperty(modelValue, allBindingsAccessor, 'numberValue', parsedElementValue);
                meta.previousValue = parsedElementValue;
            }
            displayValidState(element, isElementValueValid);
        };
        var keyDownHandler = function (e) {
            if (e.altKey || e.ctrlKey) {
                return;
            }
            if (!e.shiftKey && e.which >= 48 && e.which <= 57) {
                return;
            }
            if (!e.shiftKey && e.which >= 96 && e.which <= 105) {
                return;
            }
            if (!e.shiftKey && meta.allowDecimal && e.which === 190) {
                return;
            }
            if (!e.shiftKey && meta.allowDecimal && e.which === 110) {
                return;
            }
            if (!e.shiftKey && meta.min < 0 && (e.which === 109 || e.which === 189)) {
                return;
            }
            var special = [
                8,
                9,
                13,
                27,
                112,
                113,
                114,
                115,
                116,
                117,
                118,
                119,
                120,
                121,
                122,
                123,
                20,
                16,
                17,
                18,
                33,
                34,
                37,
                38,
                39,
                40,
                144,
                36,
                35,
                45,
                46,
                45,
                35,
                40,
                34,
                37,
                12,
                39,
                36,
                38,
                33,
                46,
            ];
            if (special.filter(function (k) { return k === e.which; }).length > 0) {
                return;
            }
            e.preventDefault();
        };
        $element.on('keydown', keyDownHandler);
        $element.on('blur', function (e) {
            update(element, valueAccessor, allBindingsAccessor);
        });
        var updateTimeoutHandle = 0;
        var changeHandler = function () {
            clearTimeout(updateTimeoutHandle);
            updateTimeoutHandle = setTimeout(valueUpdateHandler, 10);
        };
        ko.utils.arrayForEach(eventsToCatch, function (eventName) {
            ko.utils.registerEventHandler(element, eventName, changeHandler);
        });
    }
    function initialize() {
        ko.bindingHandlers['numberValue'] = {
            'after': ['options', 'foreach'],
            'init': init,
            'update': update
        };
    }
    exports.initialize = initialize;
});

define('bindings/validateField',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers['validateField'] = {
            init: function (element, valueAccessor, allBindings, viewModel) {
                var entity = viewModel.entity;
                var propertyName = ko.unwrap(valueAccessor());
                var validationErrors = ko.observableArray([]);
                if (!('entityAspect' in entity)) {
                    entity = entity();
                }
                entity.entityAspect.validationErrorsChanged.subscribe(function (changes) {
                    var newPropertyErrors = ko.utils.arrayFilter(changes.added, function (e) { return e.propertyName === propertyName; });
                    var removedPropertyErrors = ko.utils.arrayFilter(changes.removed, function (e) { return e.propertyName === propertyName; });
                    ko.utils.arrayForEach(newPropertyErrors, function (e) {
                        validationErrors([]);
                        validationErrors.push(e);
                    });
                    ko.utils.arrayForEach(removedPropertyErrors, function (e) {
                        validationErrors.remove(e);
                    });
                });
                validationErrors.subscribe(function (changes) {
                    var formGroup;
                    var child;
                    if (changes.length > 0) {
                        formGroup = $(element).closest('.form-group');
                        formGroup.removeClass('has-success').addClass('has-error');
                        child = formGroup.find('.validationError');
                        child.remove();
                    }
                    else {
                        formGroup = $(element).closest('.form-group');
                        formGroup.removeClass('has-error').addClass('has-success');
                        child = formGroup.find('.validationError');
                        child.remove();
                        setTimeout(function () { return formGroup.removeClass('has-success'); }, 2000);
                    }
                });
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/maxlengthPopup',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers['maxlengthPopup'] = {
            'after': ['options', 'foreach'],
            'init': init
        };
    }
    exports.initialize = initialize;
    function init(element, valueAccessor, allBindingsAccessor) {
        var maxlengthText = element.value.length + ' of ' + getMaxLength($(element)), tooltipOptions = { placement: 'bottom', trigger: 'manual', animation: false, title: maxlengthText }, propertyChangedFired = false, eventsToCatch = ['change', 'keyup', 'mouseup', 'paste'], lastValue = ko.utils.unwrapObservable(element.value);
        var valueUpdateHandler = function () {
            propertyChangedFired = false;
            var elementValue = ko.selectExtensions.readValue(element);
            if (typeof elementValue !== 'string') {
                throw new Error('elementValue is not of type "string"');
            }
            if (elementValue === lastValue)
                return;
            lastValue = elementValue;
            maxlengthText = elementValue.length + ' of ' + getMaxLength($(element));
            tooltipOptions.title = maxlengthText;
            $(element).tooltip(tooltipOptions);
            $(element).tooltip('hide').attr('data-original-title', tooltipOptions.title).tooltip('fixTitle').tooltip('show');
        };
        $(element).on('blur', function (e) {
            setTimeout(function () {
                $(element).tooltip('destroy');
            }, 10);
        });
        var updateTimeoutHandle = 0;
        var changeHandler = function () {
            clearTimeout(updateTimeoutHandle);
            updateTimeoutHandle = setTimeout(valueUpdateHandler, 10);
        };
        ko.utils.arrayForEach(eventsToCatch, function (eventName) {
            ko.utils.registerEventHandler(element, eventName, changeHandler);
        });
    }
    function getMaxLength(currentInput) {
        return currentInput.attr('maxlength') || currentInput.attr('size');
    }
    function updateElementValueUsingModelValue(element, valueAccessor, allBindingsAccessor) {
    }
});

define('bindings/popover',["require", "exports"], function (require, exports) {
    function guid() {
        "use strict";
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
    }
    function s4() {
        "use strict";
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }
    function initialize() {
        ko.bindingHandlers['popover'] = {
            'init': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                var popoverBindingValues = ko.utils.unwrapObservable(valueAccessor());
                var popoverTitle = popoverBindingValues.title;
                var tmplId = popoverBindingValues.template;
                var data = popoverBindingValues.data;
                var trigger = 'click';
                var eventType = 'click';
                if (popoverBindingValues.trigger) {
                    trigger = popoverBindingValues.trigger;
                }
                if (trigger === 'hover') {
                    eventType = 'mouseenter mouseleave';
                }
                else if (trigger === 'focus') {
                    eventType = 'focus blur';
                }
                var placement = popoverBindingValues.placement;
                var tmplHtml;
                if (!data) {
                    tmplHtml = $('#' + tmplId).html();
                }
                else {
                    tmplHtml = function () {
                        var container = $('<div data-bind="template: { name: template, if: data, data: data }"></div>');
                        ko.applyBindings({
                            template: tmplId,
                            data: data
                        }, container[0]);
                        return container;
                    };
                }
                var uuid = guid();
                var domId = "ko-bs-popover-" + uuid;
                var childBindingContext = bindingContext.createChildContext(viewModel);
                var tmplDom = $('<div/>', {
                    "class": "ko-popover",
                    "id": domId
                }).html(tmplHtml);
                var shit = tmplDom[0].outerHTML;
                var options = {
                    content: shit,
                    title: popoverTitle
                };
                if (placement) {
                    options.placement = placement;
                }
                if (popoverBindingValues.container) {
                    options.container = popoverBindingValues.container;
                }
                var popoverOptions = $.extend({}, ko.bindingHandlers.popover.options, options);
                $(element).bind(eventType, function () {
                    var popoverAction = 'show';
                    var popoverTriggerEl = $(this);
                    if (trigger !== 'click') {
                        popoverAction = 'toggle';
                    }
                    popoverTriggerEl.popover(popoverOptions).popover(popoverAction);
                    var popoverInnerEl = $('#' + domId);
                    $('.ko-popover').not(popoverInnerEl).parents('.popover').remove();
                    if (popoverInnerEl.is(':visible')) {
                        var triggerElementPosition = $(element).offset().top;
                        var triggerElementLeft = $(element).offset().left;
                        var triggerElementHeight = $(element).outerHeight();
                        var triggerElementWidth = $(element).outerWidth();
                        var popover = $(popoverInnerEl).parents('.popover');
                        var popoverHeight = popover.outerHeight();
                        var popoverWidth = popover.outerWidth();
                        var arrowSize = 10;
                        switch (popoverOptions.placement) {
                            case 'left':
                                popover.offset({ top: triggerElementPosition - popoverHeight / 2 + triggerElementHeight / 2, left: triggerElementLeft - arrowSize - popoverWidth });
                                break;
                            case 'right':
                                popover.offset({ top: triggerElementPosition - popoverHeight / 2 + triggerElementHeight / 2, left: 0 });
                                break;
                            case 'top':
                                popover.offset({ top: triggerElementPosition - popoverHeight - arrowSize, left: triggerElementLeft - popoverWidth / 2 + triggerElementWidth / 2 });
                                break;
                            case 'bottom':
                                popover.offset({ top: triggerElementPosition + triggerElementHeight + arrowSize, left: triggerElementLeft - popoverWidth / 2 + triggerElementWidth / 2 });
                        }
                    }
                    $(document).on('click', '[data-dismiss="popover"]', function (e) {
                        popoverTriggerEl.popover('hide');
                    });
                    return { controlsDescendantBindings: true };
                });
            },
            options: {
                placement: "right",
                title: "",
                html: true,
                content: "",
                trigger: "manual"
            }
        };
    }
    exports.initialize = initialize;
    ;
});

define('bindings/typeahead',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers['typeahead'] = {
            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                var options = ko.utils.unwrapObservable(valueAccessor());
                $(element).typeahead(options);
            },
            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/responsiveDropdown',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers["responsiveDropdown"] = {
            init: function (element) {
                $(element).on('show.bs.dropdown', function (event) {
                    if ($(this).css('overflow-x') === 'scroll') {
                        var height = $(this).height();
                        var dropdownMenu = $(event.target).find('ul.dropdown-menu');
                        var dropdownMenuHeight = dropdownMenu.height() + 25;
                        var tableOffsetTop = $(this).offset().top;
                        var dropdownMenuOffsetTop = $(event.target).offset().top + $(event.target).height();
                        var remaingSpace = height - (dropdownMenuOffsetTop - tableOffsetTop) - 20;
                        if (remaingSpace < dropdownMenuHeight) {
                            $(this).height(height + (dropdownMenuHeight - remaingSpace));
                        }
                        var offset = (dropdownMenuOffsetTop + dropdownMenuHeight) - $(window).scrollTop();
                        if (offset > window.innerHeight) {
                            $('html,body').scrollTop((offset - window.innerHeight) + $(window).scrollTop());
                        }
                    }
                });
                $(element).on('hide.bs.dropdown', function (event) {
                    $(this).css('height', 'auto');
                });
            },
            update: function (element) {
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/richTextValue',["require", "exports", 'bindings/koUtil'], function (require, exports, koUtil) {
    function initialize() {
        CKEDITOR.editorConfig = function (config) {
            config.toolbarGroups = [
                { name: 'document', groups: ['mode', 'document', 'doctools'] },
                { name: 'clipboard', groups: ['clipboard', 'undo'] },
                { name: 'editing', groups: ['find', 'selection', 'spellchecker'] },
                { name: 'forms' },
                { name: 'basicstyles', groups: ['basicstyles', 'cleanup'] },
                { name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi'] },
                { name: 'links' },
                { name: 'insert' },
                { name: 'styles' },
                { name: 'colors' },
                { name: 'tools' },
                { name: 'others' },
                { name: 'about' }
            ];
            config.removeButtons = 'Cut,Copy,Paste,Undo,Redo,Anchor,Font,BGColor,Strike,Subscript,Superscript';
            config.fontSize_sizes = '5/5pt;6/6pt;7/7pt;8/8pt;9/9pt;10/10pt;12/12pt;14/14pt;16/16pt;18/18pt;22/22pt;24/24pt;26/26pt;28/28pt;30/30pt;35/35pt;40/40pt;';
        };
        CKEDITOR.focusManager._.blurDelay = 10;
        CKEDITOR.disableAutoInline = true;
        ko.bindingHandlers['richTextValue'] = {
            'after': ['options', 'foreach'],
            'init': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                if (element.nodeName.toLowerCase() !== 'div')
                    throw new Error('div element expected');
                element.isContentEditable = true;
                var editor = CKEDITOR.inline(element, { floatSpaceDockedOffsetY: 20 }), modelValue = ko.utils.unwrapObservable(valueAccessor());
                if (isNullOrEmpty(modelValue))
                    modelValue = '';
                editor.setData(modelValue);
                $(element).on('change blur input', function () {
                    koUtil.writeValueToProperty(valueAccessor(), allBindingsAccessor, 'richTextValue', editor.getData(), true);
                });
                $(element).on('focus', function (ev) {
                    element.removeAttribute('aria-label');
                    element.removeAttribute('title');
                });
            },
            'update': function () {
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/email',["require", "exports"], function (require, exports) {
    var regex = new RegExp("^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$");
    function validateEmail(value) {
        if (value !== "") {
            return regex.test(value);
        }
        else {
            return true;
        }
    }
    function displayValidState(element, valid, silent) {
        var $formGroup = $(element).closest('.form-group');
        $formGroup.toggleClass('has-warning', !valid);
        if (valid && !silent) {
            $formGroup.addClass('has-success');
            setTimeout(function () { return $formGroup.removeClass('has-success'); }, 1000);
        }
        else {
            $formGroup.removeClass('has-success');
        }
    }
    function initialize() {
        ko.bindingHandlers['email'] = {
            init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                var viewModelValue = valueAccessor();
                var $input = $(element);
                $input.val(viewModelValue() || '');
                $input.on('blur', function () {
                    var value = $input.val();
                    if (validateEmail(value)) {
                        viewModelValue(value);
                    }
                    else {
                        $input.val(viewModelValue());
                    }
                    displayValidState(element, true, true);
                });
                $input.on('keyup', function () {
                    var value = $input.val();
                    var isValid;
                    if (value === "" || value === null) {
                        displayValidState(element, true, true);
                        return;
                    }
                    isValid = validateEmail(value);
                    if (isValid) {
                        viewModelValue(value);
                    }
                    displayValidState(element, isValid, false);
                });
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/timeValue',["require", "exports"], function (require, exports) {
    function displayValidState($input, isElementValueValid, tooltipOptions) {
        var $formGroup = $input.closest('.form-group');
        if (isElementValueValid) {
            $formGroup.removeClass('has-input-error');
        }
        else {
            $formGroup.addClass('has-input-error');
        }
        if (tooltipOptions) {
            $input.tooltip(tooltipOptions);
            $input.tooltip('hide').attr('data-original-title', tooltipOptions.title).tooltip('fixTitle').tooltip('show');
        }
        else {
            $input.tooltip('hide');
        }
    }
    var TimeInputParser = (function () {
        function TimeInputParser() {
        }
        TimeInputParser.parse = function (textToParse) {
            textToParse = this.padZeroColon(textToParse);
            textToParse = this.addMeridiem(textToParse);
            return moment(textToParse, "LT");
        };
        TimeInputParser.padZeroColon = function (timeValue) {
            var splitTime;
            var hour;
            var minute;
            if (timeValue.indexOf(":") !== -1) {
                splitTime = timeValue.split(":");
                if (splitTime[0] === "") {
                    splitTime[0] = "00";
                }
                else if (splitTime[0].length === 1) {
                    splitTime[0] = "0" + splitTime[0];
                }
                if (splitTime[1] === "") {
                    splitTime[1] = "00";
                }
                else {
                    if (!this.numberPattern.test(splitTime[1][0])) {
                        splitTime[1] = "00" + splitTime[1];
                    }
                    else if (!this.numberPattern.test(splitTime[1][1])) {
                        splitTime[1] = this.spliceSlice(splitTime[1], 1, 0, "0");
                    }
                }
                return splitTime.join(":");
            }
            if (!this.numberPattern.test(timeValue[0])) {
                timeValue = "00:00" + timeValue;
            }
            else if (!this.numberPattern.test(timeValue[1])) {
                timeValue = "0" + timeValue;
                timeValue = this.spliceSlice(timeValue, 2, 0, ":00");
            }
            else if (!this.numberPattern.test(timeValue[2])) {
                hour = parseInt(timeValue.slice(0, 2));
                if (hour > 9 && hour < 13) {
                    timeValue = this.spliceSlice(timeValue, 2, 0, ":00");
                }
                else {
                    timeValue = "0" + timeValue;
                    timeValue = this.spliceSlice(timeValue, 2, 0, ":");
                    timeValue = this.spliceSlice(timeValue, 4, 0, "0");
                }
            }
            else if (!this.numberPattern.test(timeValue[3])) {
                hour = parseInt(timeValue.slice(0, 2));
                minute = parseInt(timeValue.slice(2, 1));
                if (hour > 9 && hour < 13 && minute < 6) {
                    timeValue = this.spliceSlice(timeValue, 2, 0, ":");
                    timeValue = this.spliceSlice(timeValue, 4, 0, "0");
                }
                else {
                    timeValue = "0" + timeValue;
                    timeValue = this.spliceSlice(timeValue, 2, 0, ":");
                }
            }
            else {
                timeValue = this.spliceSlice(timeValue, 2, 0, ":");
            }
            return timeValue;
        };
        TimeInputParser.spliceSlice = function (str, index, count, add) {
            return str.slice(0, index) + add + str.slice(index + count);
        };
        TimeInputParser.addMeridiem = function (timeValue) {
            if (timeValue.indexOf("p") !== -1 || timeValue.indexOf("a") !== -1 || timeValue.indexOf("P") !== -1 || timeValue.indexOf("A") !== -1) {
                return timeValue;
            }
            var hourValues = timeValue.split(":");
            var hour = parseInt(hourValues[0]);
            if ((hour > 7 && hour < 12) || hour === 0) {
                timeValue = timeValue + "a";
            }
            else {
                timeValue = timeValue + "p";
            }
            return timeValue;
        };
        TimeInputParser.numberPattern = /\d+/;
        return TimeInputParser;
    })();
    function initialize() {
        ko.bindingHandlers['timeValue'] = {
            init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                var $input = $(element);
                var $timeControl = $input.closest("div.input-group");
                var tooltipOptions = { placement: 'top', trigger: 'manual', animation: false, title: '' };
                $input.val(valueAccessor()() || '');
                $timeControl.datetimepicker({
                    format: "LT",
                    keepInvalid: true,
                    useStrict: true
                });
                var dateTimePicker = $timeControl.data('DateTimePicker');
                $input.on("keydown", function (event) {
                    if (event.which !== 32 || element.readOnly || element.isDisabled) {
                        return;
                    }
                    event.preventDefault();
                    dateTimePicker.show();
                });
                $input.on("keyup", function () {
                    var controlValue = valueAccessor();
                    var value = $input.val();
                    if (value === null || value === "") {
                        controlValue(null);
                        tooltipOptions.title = '(blank)';
                        displayValidState($input, true, tooltipOptions);
                        return;
                    }
                    var time = TimeInputParser.parse(value);
                    var isValid = time.isValid();
                    if (isValid) {
                        controlValue(time.format("LT"));
                        tooltipOptions.title = time.format("LT");
                    }
                    else {
                        tooltipOptions.title = "(invalid)";
                    }
                    displayValidState($input, isValid, tooltipOptions);
                });
                $input.on("blur", function () {
                    setTimeout(function () { return $input.tooltip('destroy'); }, 10);
                    var currentValue = $input.val();
                    var controlValue = valueAccessor();
                    if (currentValue === "" || currentValue === null) {
                        displayValidState($input, true);
                        return;
                    }
                    var time = TimeInputParser.parse(currentValue);
                    if (time.isValid()) {
                        var timeWithPrefix = time.format("LT");
                        if (timeWithPrefix.split(":", 2)[0].length == 1) {
                            timeWithPrefix = '0' + timeWithPrefix;
                        }
                    }
                    var controlValueWithPrefix = controlValue();
                    if (controlValueWithPrefix != null) {
                        if (controlValueWithPrefix.split(":", 2)[0].length == 1) {
                            controlValueWithPrefix = '0' + controlValueWithPrefix;
                        }
                    }
                    if (timeWithPrefix != controlValueWithPrefix) {
                        controlValue(timeWithPrefix);
                    }
                    $input.val(controlValue());
                    displayValidState($input, true);
                });
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/ssnText',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers['ssnText'] = {
            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            },
            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                var value = valueAccessor(), allBindings = allBindingsAccessor();
                var valueUnwrapped = ko.utils.unwrapObservable(value);
                if (SystemSettings.EnableSSNMasking && !isNullOrEmpty(valueUnwrapped) && /^\d{3}-\d{2}-\d{4}$/.test(valueUnwrapped)) {
                    valueUnwrapped = '<span class="text-muted">XXX-XX-</span>' + valueUnwrapped.substr(7, 4);
                }
                $(element).html(valueUnwrapped);
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/modal',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers['modal'] = {
            init: function (element, valueAccessor) {
                $(element).prependTo("body");
                $(element).modal({
                    show: false
                });
                var value = valueAccessor();
                if (typeof value === 'function') {
                    $(element).on('hide.bs.modal', function () {
                        value(false);
                    });
                }
                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    $(element).modal("destroy");
                });
            },
            update: function (element, valueAccessor) {
                var value = valueAccessor();
                if (ko.utils.unwrapObservable(value)) {
                    $(element).modal('show');
                }
                else {
                    $(element).modal('hide');
                }
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/modalLarger',["require", "exports"], function (require, exports) {
    function initialize() {
        ko.bindingHandlers['modalLarger'] = {
            init: function (element, valueAccessor) {
                var modalDialog = $(element).closest(".modal-dialog");
                modalDialog.addClass("modal-lg");
            }
        };
    }
    exports.initialize = initialize;
});

define('bindings/bindings',["require", "exports", 'bindings/value', 'bindings/dateText', 'bindings/dateValue', 'bindings/fadeVisible', 'bindings/focusin', 'bindings/maskedValue', 'bindings/numberValue', 'bindings/validateField', 'bindings/maxlengthPopup', 'bindings/popover', 'bindings/typeahead', 'bindings/autocapitalize', 'bindings/responsiveDropdown', 'bindings/richTextValue', 'bindings/email', 'bindings/timeValue', 'bindings/ssnText', 'bindings/modal', 'bindings/modalLarger'], function (require, exports, value, dateText, dateValue, fadeVisible, focusin, maskedValue, numberValue, validateField, maxlengthPopup, popover, typeahead, autocapitalize, responsiveDropdown, richTextValue, email, timeValue, ssnText, modal, modalLarger) {
    function initialize() {
        value.initialize();
        dateText.initialize();
        dateValue.initialize();
        fadeVisible.initialize();
        focusin.initialize();
        maskedValue.initialize();
        numberValue.initialize();
        validateField.initialize();
        maxlengthPopup.initialize();
        popover.initialize();
        typeahead.initialize();
        autocapitalize.initialize();
        responsiveDropdown.initialize();
        richTextValue.initialize();
        email.initialize();
        timeValue.initialize();
        ssnText.initialize();
        modal.initialize();
        modalLarger.initialize();
        ko.bindingHandlers['readonly'] = {
            'update': function (element, valueAccessor) {
                var value = ko.utils.unwrapObservable(valueAccessor());
                if (element.readOnly !== !!value)
                    element.readOnly = !!value;
            }
        };
        ko.bindingHandlers['readOnlyQuestion'] = {
            'init': function (element, valueAccessor) {
                var value = valueAccessor();
                if (value !== undefined && value) {
                    $('input', element).prop('readonly', true);
                    $('select', element).prop('readonly', true);
                    $('textarea', element).prop('readonly', true);
                    $('input[type=checkbox]', element).prop('disabled', true);
                    $('input[type=radio]', element).prop('disabled', true);
                    $('.input-group button', element).prop('disabled', true);
                }
            }
        };
        ko.bindingHandlers['selectOptionQuestion'] = {
            'init': function (element, valueAccessor, allBindings, viewModel) {
                var value = valueAccessor();
                if (value === undefined) {
                    return;
                }
                if (value == '') {
                    $(element).empty();
                    $(element).append('<option value=""></option>');
                }
                else {
                    if (allBindings.has('scale')) {
                        $(element).empty();
                        $(element).append('<option value=""></option>');
                        var allowedChoices = value.split(',');
                        var scaleId = allBindings.get('scale');
                        var q = viewModel.questionViewModels['q' + scaleId.toString()];
                        q.choices.filter(function (c) { return allowedChoices.indexOf(c.screenLookupId.toString()) !== -1; }).forEach(function (choice) {
                            $(element).append('<option id="' + choice.inputId + '" value="' + choice.screenLookupId + '">' + choice.name + '</option>');
                        });
                    }
                }
            }
        };
        function clearFileInput(input) {
            try {
                input.value = '';
                if (input.value) {
                    input.type = "text";
                    input.type = "file";
                }
            }
            catch (e) {
            }
        }
        ko.bindingHandlers['files'] = {
            'init': function (input, valueAccessor) {
                var fakeInput = $(input).parents('.input-group').find(':text')[0];
                $(input).on('change', function () {
                    var files = [];
                    for (var i = 0; i < input.files.length; i++) {
                        files.push(input.files.item(i));
                    }
                    fakeInput.value = files.map(function (f) { return '"' + f.name.replace(/\\/g, '/').replace(/.*\//, '') + '"'; }).join(', ');
                    valueAccessor()(files);
                });
                $(fakeInput).on('click', function () { return $(input).click(); }).keyup(function (e) {
                    var code = e.which;
                    if (code == 32 || code == 13) {
                        e.preventDefault();
                        $(input).click();
                    }
                    else if (code == 46 || e.keyCode === 46) {
                        clearFileInput(input);
                        fakeInput.value = '';
                    }
                });
            }
        };
    }
    exports.initialize = initialize;
});

define('security/enums',["require", "exports"], function (require, exports) {
    exports.CrudOperation = new breeze.core.Enum('CrudOperation');
    exports.CrudOperation.Read = exports.CrudOperation.addSymbol({ id: 1 });
    exports.CrudOperation.Create = exports.CrudOperation.addSymbol({ id: 2 });
    exports.CrudOperation.Update = exports.CrudOperation.addSymbol({ id: 3 });
    exports.CrudOperation.Delete = exports.CrudOperation.addSymbol({ id: 4 });
    exports.CrudOperation.resolveSymbols();
    exports.ProtectedApplication = new breeze.core.Enum('ProtectedApplication');
    exports.ProtectedApplication.Sams = exports.ProtectedApplication.addSymbol({ id: 1 });
    exports.ProtectedApplication.SamsAdministrator = exports.ProtectedApplication.addSymbol({ id: 2 });
    exports.ProtectedApplication.FinPAK = exports.ProtectedApplication.addSymbol({ id: 3 });
    exports.ProtectedApplication.SamsImportExport = exports.ProtectedApplication.addSymbol({ id: 4 });
    exports.ProtectedApplication.NapisSrt = exports.ProtectedApplication.addSymbol({ id: 5 });
    exports.ProtectedApplication.NysofaReporter = exports.ProtectedApplication.addSymbol({ id: 6 });
    exports.ProtectedApplication.CmsBiller = exports.ProtectedApplication.addSymbol({ id: 7 });
    exports.ProtectedApplication.SamsApp = exports.ProtectedApplication.addSymbol({ id: 8 });
    exports.ProtectedApplication.BenefitsCheckup = exports.ProtectedApplication.addSymbol({ id: 9 });
    exports.ProtectedApplication.CdaReporter = exports.ProtectedApplication.addSymbol({ id: 10 });
    exports.ProtectedApplication.CaregiverDirect = exports.ProtectedApplication.addSymbol({ id: 12 });
    exports.ProtectedApplication.WebResourceCenter = exports.ProtectedApplication.addSymbol({ id: 13 });
    exports.ProtectedApplication.resolveSymbols();
    exports.ProtectedItemType = new breeze.core.Enum('ProtectedItemType');
    exports.ProtectedItemType.Application = exports.ProtectedItemType.addSymbol({ id: 1 });
    exports.ProtectedItemType.Entity = exports.ProtectedItemType.addSymbol({ id: 2 });
    exports.ProtectedItemType.Field = exports.ProtectedItemType.addSymbol({ id: 3 });
    exports.ProtectedItemType.Report = exports.ProtectedItemType.addSymbol({ id: 4 });
    exports.ProtectedItemType.UserInterface = exports.ProtectedItemType.addSymbol({ id: 5 });
    exports.ProtectedItemType.ServiceProgram = exports.ProtectedItemType.addSymbol({ id: 6 });
    exports.ProtectedItemType.AssessmentForm = exports.ProtectedItemType.addSymbol({ id: 7 });
    exports.SecuredEntity = new breeze.core.Enum('SecuredEntity');
    exports.SecuredEntity.ActionItem = exports.SecuredEntity.addSymbol({ id: 0 });
    exports.SecuredEntity.Assessment = exports.SecuredEntity.addSymbol({ id: 1 });
    exports.SecuredEntity.Call = exports.SecuredEntity.addSymbol({ id: 2 });
    exports.SecuredEntity.Consumer = exports.SecuredEntity.addSymbol({ id: 3 });
    exports.SecuredEntity.ConsumerProvider = exports.SecuredEntity.addSymbol({ id: 4 });
    exports.SecuredEntity.Contract = exports.SecuredEntity.addSymbol({ id: 5 });
    exports.SecuredEntity.InvoicePayment = exports.SecuredEntity.addSymbol({ id: 6 });
    exports.SecuredEntity.Roster = exports.SecuredEntity.addSymbol({ id: 7 });
    exports.SecuredEntity.Route = exports.SecuredEntity.addSymbol({ id: 8 });
    exports.SecuredEntity.ServiceDelivery = exports.SecuredEntity.addSymbol({ id: 9 });
    exports.SecuredEntity.ServiceOrder = exports.SecuredEntity.addSymbol({ id: 10 });
    exports.SecuredEntity.ServicePlan = exports.SecuredEntity.addSymbol({ id: 11 });
    exports.SecuredEntity.ServiceSuspension = exports.SecuredEntity.addSymbol({ id: 12 });
    exports.SecuredEntity.UnitDistribution = exports.SecuredEntity.addSymbol({ id: 13 });
    exports.SecuredEntity.UserLogin = exports.SecuredEntity.addSymbol({ id: 14 });
    exports.SecuredEntity.Provider = exports.SecuredEntity.addSymbol({ id: 15 });
    exports.SecuredEntity.Episode = exports.SecuredEntity.addSymbol({ id: 16 });
    exports.SecuredEntity.resolveSymbols();
    exports.ProgramSecuredEntity = new breeze.core.Enum('ProgramSecuredEntity');
    exports.ProgramSecuredEntity.ActionItem = exports.ProgramSecuredEntity.addSymbol({ id: 0 });
    exports.ProgramSecuredEntity.Assessments = exports.ProgramSecuredEntity.addSymbol({ id: 1 });
    exports.ProgramSecuredEntity.CareHistory = exports.ProgramSecuredEntity.addSymbol({ id: 2 });
    exports.ProgramSecuredEntity.CarePlans = exports.ProgramSecuredEntity.addSymbol({ id: 3 });
    exports.ProgramSecuredEntity.Copays = exports.ProgramSecuredEntity.addSymbol({ id: 4 });
    exports.ProgramSecuredEntity.ServiceDeliveries = exports.ProgramSecuredEntity.addSymbol({ id: 5 });
    exports.ProgramSecuredEntity.ServiceOrders = exports.ProgramSecuredEntity.addSymbol({ id: 6 });
    exports.ProgramSecuredEntity.ServiceSuspensions = exports.ProgramSecuredEntity.addSymbol({ id: 7 });
    exports.ProgramSecuredEntity.resolveSymbols();
    exports.PropertyType = new breeze.core.Enum('PropertyType');
    exports.PropertyType.ServiceAgency = exports.PropertyType.addSymbol({ id: 1 });
    exports.PropertyType.ServiceProvider = exports.PropertyType.addSymbol({ id: 2 });
    exports.PropertyType.MatchType = exports.PropertyType.addSymbol({ id: 3 });
    exports.PropertyType.ServiceSubprovider = exports.PropertyType.addSymbol({ id: 4 });
    exports.PropertyType.ServiceSite = exports.PropertyType.addSymbol({ id: 5 });
    exports.PropertyType.DefaultAgency = exports.PropertyType.addSymbol({ id: 6 });
    exports.PropertyType.ConsumerProvider = exports.PropertyType.addSymbol({ id: 7 });
    exports.PropertyType.CareManager = exports.PropertyType.addSymbol({ id: 8 });
    exports.PropertyType.AssessmentProvider = exports.PropertyType.addSymbol({ id: 10 });
    exports.PropertyType.resolveSymbols();
    exports.MatchType = new breeze.core.Enum('MatchType');
    exports.MatchType.MatchAll = exports.MatchType.addSymbol({ id: 0 });
    exports.MatchType.MatchAny = exports.MatchType.addSymbol({ id: 1 });
    exports.MatchType.resolveSymbols();
    exports.ProtectedItem = new breeze.core.Enum('ProtectedItem');
    exports.ProtectedItem.Call = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Call' });
    exports.ProtectedItem.Call_ActionItem = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Call', ItemKey: 'ActionItem' });
    exports.ProtectedItem.Call_Assessment = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Call', ItemKey: 'Assessment' });
    exports.ProtectedItem.Call_Outcome = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Call', ItemKey: 'Outcome' });
    exports.ProtectedItem.Call_Referral = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Call', ItemKey: 'Referral' });
    exports.ProtectedItem.Call_ServiceDelivery = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Call', ItemKey: 'ServiceDelivery' });
    exports.ProtectedItem.Call_Topic = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Call', ItemKey: 'Topic' });
    exports.ProtectedItem.AllConsumerTypes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'AllConsumerTypes' });
    exports.ProtectedItem.Consumer = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Consumer' });
    exports.ProtectedItem.Consumer_ActionItem = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'ActionItem' });
    exports.ProtectedItem.Consumer_Assessment = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Assessment' });
    exports.ProtectedItem.Consumer_Call = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Call' });
    exports.ProtectedItem.Consumer_Caregiver = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Caregiver' });
    exports.ProtectedItem.Consumer_CareManager = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'CareManager' });
    exports.ProtectedItem.Consumer_Careplan = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Careplan' });
    exports.ProtectedItem.Consumer_ConsumerUfld = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'ConsumerUfld' });
    exports.ProtectedItem.Consumer_Contact = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Contact' });
    exports.ProtectedItem.Consumer_Copay = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Copay' });
    exports.ProtectedItem.Consumer_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Details' });
    exports.ProtectedItem.Consumer_EthnicGroup = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'EthnicGroup' });
    exports.ProtectedItem.Consumer_FundIdentifiers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'FundIdentifiers' });
    exports.ProtectedItem.Consumer_JournalEntry = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'JournalEntry' });
    exports.ProtectedItem.Consumer_Location = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Location' });
    exports.ProtectedItem.Consumer_LocusHistory = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'LocusHistory' });
    exports.ProtectedItem.Consumer_Phone = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Phone' });
    exports.ProtectedItem.Consumer_Providers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Providers' });
    exports.ProtectedItem.Consumer_Recipient = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Recipient' });
    exports.ProtectedItem.Consumer_ServiceDelivery = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'ServiceDelivery' });
    exports.ProtectedItem.Consumer_ServiceOrder = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'ServiceOrder' });
    exports.ProtectedItem.Consumer_ServiceSuspension = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'ServiceSuspension' });
    exports.ProtectedItem.Consumer_Episode = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'Episode' });
    exports.ProtectedItem.Episode_Dates = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Episode', ItemKey: 'Dates' });
    exports.ProtectedItem.Episode_CareEnrollments = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Episode', ItemKey: 'Care Enrollments' });
    exports.ProtectedItem.Episode_CareManagers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Episode', ItemKey: 'Care Managers' });
    exports.ProtectedItem.Episode_Providers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Episode', ItemKey: 'Providers' });
    exports.ProtectedItem.Episode_Agencies = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Episode', ItemKey: 'Agencies' });
    exports.ProtectedItem.Episode_ActivitiesReferrals = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Episode', ItemKey: 'Activities & Referrals' });
    exports.ProtectedItem.Episode_Assessments = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Episode', ItemKey: 'Assessments' });
    exports.ProtectedItem.Episode_Journals = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Episode', ItemKey: 'Journals' });
    exports.ProtectedItem.Episode_ServiceDeliveries = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Episode', ItemKey: 'Service Deliveries' });
    exports.ProtectedItem.Episode_InvoicesClaims = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Episode', ItemKey: 'Invoices & Claims' });
    exports.ProtectedItem.Eocb_Batch = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Episode Invoice Batch' });
    exports.ProtectedItem.Careplan_CareManagers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Careplan', ItemKey: 'CareManagers' });
    exports.ProtectedItem.Careplan_CarePlanDetails = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Careplan', ItemKey: 'CarePlanDetails' });
    exports.ProtectedItem.Careplan_CostCap = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Careplan', ItemKey: 'Cost Cap' });
    exports.ProtectedItem.Careplan_DiagnosisCodes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Careplan', ItemKey: 'DiagnosisCodes' });
    exports.ProtectedItem.Careplan_GoalStatement = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Careplan', ItemKey: 'GoalStatement' });
    exports.ProtectedItem.Careplan_JournalEntry = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Careplan', ItemKey: 'JournalEntry' });
    exports.ProtectedItem.Careplan_ServiceAllocation = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Careplan', ItemKey: 'ServiceAllocation' });
    exports.ProtectedItem.Careplan_ServiceAllocation_Subservice = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ServiceAllocation', ItemKey: 'SubserviceAllocation' });
    exports.ProtectedItem.Careplan_ServiceAllocation_Schedule = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ServiceAllocation', ItemKey: 'ServiceAllocationSchedule' });
    exports.ProtectedItem.Careplan_WorksheetEntry = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer.Careplan', ItemKey: 'WorksheetEntry' });
    exports.ProtectedItem.ConsumerGroup = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'ConsumerGroup' });
    exports.ProtectedItem.ConsumerGroup_ActionItem = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ConsumerGroup', ItemKey: 'ActionItem' });
    exports.ProtectedItem.ConsumerGroup_ConsumerUfld = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ConsumerGroup', ItemKey: 'ConsumerUfld' });
    exports.ProtectedItem.ConsumerGroup_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ConsumerGroup', ItemKey: 'Details' });
    exports.ProtectedItem.ConsumerGroup_EthnicGroup = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ConsumerGroup', ItemKey: 'EthnicGroup' });
    exports.ProtectedItem.ConsumerGroup_FundIdentifiers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ConsumerGroup', ItemKey: 'FundIdentifiers' });
    exports.ProtectedItem.ConsumerGroup_JournalEntry = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ConsumerGroup', ItemKey: 'JournalEntry' });
    exports.ProtectedItem.ConsumerGroup_LocusHistory = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ConsumerGroup', ItemKey: 'LocusHistory' });
    exports.ProtectedItem.ConsumerGroup_Providers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ConsumerGroup', ItemKey: 'Providers' });
    exports.ProtectedItem.ConsumerGroup_ServiceDelivery = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ConsumerGroup', ItemKey: 'ServiceDelivery' });
    exports.ProtectedItem.ConsumerGroup_ServiceOrder = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'ConsumerGroup', ItemKey: 'ServiceOrder' });
    exports.ProtectedItem.Contracts = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Contracts' });
    exports.ProtectedItem.Contracts_ProgramContracts = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Contracts', ItemKey: 'ProgramContracts' });
    exports.ProtectedItem.Contracts_ServiceContracts = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Contracts', ItemKey: 'ServiceContracts' });
    exports.ProtectedItem.CustomSearch = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'CustomSearch' });
    exports.ProtectedItem.Consumer_FileAttachments = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Consumer', ItemKey: 'FileAttachments' });
    exports.ProtectedItem.FolderAttach = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'FolderAttach' });
    exports.ProtectedItem.FolderAttach_AttachCat1 = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'FolderAttach', ItemKey: 'AttachCat1' });
    exports.ProtectedItem.FolderAttach_AttachCat2 = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'FolderAttach', ItemKey: 'AttachCat2' });
    exports.ProtectedItem.FolderAttach_AttachCat3 = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'FolderAttach', ItemKey: 'AttachCat3' });
    exports.ProtectedItem.FolderAttach_AttachCat4 = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'FolderAttach', ItemKey: 'AttachCat4' });
    exports.ProtectedItem.FolderAttach_AttachCat5 = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'FolderAttach', ItemKey: 'AttachCat5' });
    exports.ProtectedItem.FolderAttach_CreateFolders = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'FolderAttach', ItemKey: 'CreateFolders' });
    exports.ProtectedItem.Invoices = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Invoices' });
    exports.ProtectedItem.Invoices_ConsumerInvoices = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Invoices', ItemKey: 'ConsumerInvoices' });
    exports.ProtectedItem.Invoices_AgencyInvoices = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Invoices', ItemKey: 'Invoices' });
    exports.ProtectedItem.Invoices_ThirdPartyInvoices = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Invoices', ItemKey: 'ThirdPartyInvoices' });
    exports.ProtectedItem.IRClient = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IR Client' });
    exports.ProtectedItem.IRClient_ActionItem = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'ActionItem' });
    exports.ProtectedItem.IRClient_Assessment = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'Assessment' });
    exports.ProtectedItem.IRClient_Call = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'Call' });
    exports.ProtectedItem.IRClient_CareManager = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'CareManager' });
    exports.ProtectedItem.IRClient_ConsumerUfld = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'ConsumerUfld' });
    exports.ProtectedItem.IRClient_Contact = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'Contact' });
    exports.ProtectedItem.IRClient_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'Details' });
    exports.ProtectedItem.IRClient_EthnicGroup = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'EthnicGroup' });
    exports.ProtectedItem.IRClient_JournalEntry = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'JournalEntry' });
    exports.ProtectedItem.IRClient_Location = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'Location' });
    exports.ProtectedItem.IRClient_Phone = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'Phone' });
    exports.ProtectedItem.IRClient_Providers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'IR Client', ItemKey: 'Providers' });
    exports.ProtectedItem.Merge = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Merge' });
    exports.ProtectedItem.Merge_MergeConsumerGroups = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Merge', ItemKey: 'MergeConsumerGroups' });
    exports.ProtectedItem.Merge_MergeConsumers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Merge', ItemKey: 'MergeConsumers' });
    exports.ProtectedItem.Merge_MergeIRClients = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Merge', ItemKey: 'MergeIRClients' });
    exports.ProtectedItem.Payments = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Payments' });
    exports.ProtectedItem.Payments_AgencyPayments = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Payments', ItemKey: 'AgencyPayments' });
    exports.ProtectedItem.Payments_ConsumerPayments = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Payments', ItemKey: 'ConsumerPayments' });
    exports.ProtectedItem.Payments_ThirdPartyPayments = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Payments', ItemKey: 'ThirdPartyPayments' });
    exports.ProtectedItem.Report = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Report' });
    exports.ProtectedItem.Report_ActionReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Report', ItemKey: 'Action Reports' });
    exports.ProtectedItem.Report_AdministrativeReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Report', ItemKey: 'Administrative Reports' });
    exports.ProtectedItem.Report_AssessmentReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Report', ItemKey: 'AssessmentReports' });
    exports.ProtectedItem.Report_BillingReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Report', ItemKey: 'Billing Reports' });
    exports.ProtectedItem.Report_CareplanReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Report', ItemKey: 'CareplanReports' });
    exports.ProtectedItem.Report_ConsumerReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Report', ItemKey: 'ConsumerReports' });
    exports.ProtectedItem.Report_ContractReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Report', ItemKey: 'ContractReports' });
    exports.ProtectedItem.Report_CareTransitionsReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Report', ItemKey: 'Care Transitions Reports' });
    exports.ProtectedItem.Report_IRReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Report', ItemKey: 'IRReports' });
    exports.ProtectedItem.Report_ServiceReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Report', ItemKey: 'Service Reports' });
    exports.ProtectedItem.Roster = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Roster' });
    exports.ProtectedItem.Roster_Properties = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Roster', ItemKey: 'ServiceRoster' });
    exports.ProtectedItem.Roster_Record = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Roster', ItemKey: 'ServiceRosterRecord' });
    exports.ProtectedItem.Route = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Route' });
    exports.ProtectedItem.Route_RouteConsumers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Route', ItemKey: 'RouteConsumers' });
    exports.ProtectedItem.RouteConsumers_RefreshRouteConsumers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Route', ItemKey: 'UpdateRouteConsumers' });
    exports.ProtectedItem.RouteConsumers_MapQuest = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Route', ItemKey: 'MapQuest' });
    exports.ProtectedItem.SAMS = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'SAMS' });
    exports.ProtectedItem.ServiceOrderBulkGenerate = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools', ItemKey: 'Service Order Bulk Generate' });
    exports.ProtectedItem.Templates = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Templates' });
    exports.ProtectedItem.Templates_ServiceDelivery = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Templates', ItemKey: 'ServiceDelivery' });
    exports.ProtectedItem.Tools = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Tools' });
    exports.ProtectedItem.Tools_BulkActivityCreationWizard = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools', ItemKey: 'Bulk Activity Creation Wizard' });
    exports.ProtectedItem.Tools_AssociationUtility = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools', ItemKey: 'AssociationUtility' });
    exports.ProtectedItem.Tools_DeliveryConfirmationWizard = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools', ItemKey: 'DeliveryConfirmationWizard' });
    exports.ProtectedItem.Tools_Departments = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools', ItemKey: 'Departments' });
    exports.ProtectedItem.Tools_LocusHistoryBulk = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools', ItemKey: 'LocusHistoryBulk' });
    exports.ProtectedItem.Tools_ServiceRemap = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools', ItemKey: 'ServiceRemap' });
    exports.ProtectedItem.Tools_PAMEvents = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools', ItemKey: 'Public/Media Assessments' });
    exports.ProtectedItem.Tools_RelocateAssessmentForms = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools', ItemKey: 'Relocate Assessment Forms' });
    exports.ProtectedItem.Tools_SHIPExportFiles = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools', ItemKey: 'SHIPExportFiles' });
    exports.ProtectedItem.AirsXml = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'Tools - AIRS XML' });
    exports.ProtectedItem.AirsXml_ExporttoBeaconWEB = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools - AIRS XML', ItemKey: 'Export to BeaconWEB' });
    exports.ProtectedItem.AirsXml_ExportXMLFile = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools - AIRS XML', ItemKey: 'Export XML File' });
    exports.ProtectedItem.AirsXml_ImportXMLFile = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools - AIRS XML', ItemKey: 'Import XML File' });
    exports.ProtectedItem.AirsXml_ReviewConfirmImports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools - AIRS XML', ItemKey: 'Review/Confirm Imports' });
    exports.ProtectedItem.AirsXml_XMLConfiguration = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Tools - AIRS XML', ItemKey: 'XML Configuration' });
    exports.ProtectedItem.UnitDistribution = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'UnitDistribution' });
    exports.ProtectedItem.UnitDistribution_UnitDistributionSession = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'UnitDistribution', ItemKey: 'UnitDistributionSession' });
    exports.ProtectedItem.UnitDistribution_UnitDistributionSet = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'UnitDistribution', ItemKey: 'UnitDistributionSet' });
    exports.ProtectedItem.WorkflowTrigger = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'WorkflowTrigger' });
    exports.ProtectedItem.WorkflowTriggerAction = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'WorkflowTrigger', ItemKey: 'WorkflowTriggerAction' });
    exports.ProtectedItem.Careplan = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'Careplan' });
    exports.ProtectedItem.Careplan_FunctionalArea = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Careplan', ItemKey: 'FunctionalArea' });
    exports.ProtectedItem.Careplan_FunctionalCategory = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Careplan', ItemKey: 'FunctionalCategory' });
    exports.ProtectedItem.Careplan_Goal = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Careplan', ItemKey: 'Goal' });
    exports.ProtectedItem.Configuration = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'Configuration' });
    exports.ProtectedItem.Configuration_AuditConfig = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Configuration', ItemKey: 'AuditConfig' });
    exports.ProtectedItem.Configuration_AutoNumberSettings = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Configuration', ItemKey: 'AutoNumberSettings' });
    exports.ProtectedItem.Configuration_ListCaregiverDefaults = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Configuration', ItemKey: 'ListCaregiverDefaults' });
    exports.ProtectedItem.Configuration_ListDefault = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Configuration', ItemKey: 'ListDefault' });
    exports.ProtectedItem.Configuration_OmniaFileLocations = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Configuration', ItemKey: 'OmniaFileLocations' });
    exports.ProtectedItem.Configuration_SecuritySettings = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Configuration', ItemKey: 'SecuritySettings' });
    exports.ProtectedItem.Configuration_SystemSettings = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Configuration', ItemKey: 'SystemSettings' });
    exports.ProtectedItem.General = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'General' });
    exports.ProtectedItem.General_AgeGroups = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'Age Groups' });
    exports.ProtectedItem.General_Aliases = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'Aliases' });
    exports.ProtectedItem.General_CallOutcomes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'Call Outcomes' });
    exports.ProtectedItem.General_Eligibilities = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'Eligibilities' });
    exports.ProtectedItem.General_EthnicRace = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'EthnicRace' });
    exports.ProtectedItem.General_Keywords = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'Keywords' });
    exports.ProtectedItem.General_Language = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'Language' });
    exports.ProtectedItem.General_MaritalStatus = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'MaritalStatus' });
    exports.ProtectedItem.General_PaymentSources = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'PaymentSources' });
    exports.ProtectedItem.General_Plannings = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'Plannings' });
    exports.ProtectedItem.General_Priorities = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'Priorities' });
    exports.ProtectedItem.General_ReasonCode = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'ReasonCode' });
    exports.ProtectedItem.General_ReferredBy = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'Referred By' });
    exports.ProtectedItem.General_Relationships = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'Relationships' });
    exports.ProtectedItem.General_StatusCode = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'StatusCode' });
    exports.ProtectedItem.General_UserField = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General', ItemKey: 'UserField' });
    exports.ProtectedItem.StatusCode_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General.StatusCode', ItemKey: 'Details' });
    exports.ProtectedItem.StatusCode_Reasons = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'General.StatusCode', ItemKey: 'Reasons' });
    exports.ProtectedItem.Options = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'Options' });
    exports.ProtectedItem.Options_ListSettings = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Options', ItemKey: 'ListSettings' });
    exports.ProtectedItem.Organization = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'Organization' });
    exports.ProtectedItem.Organization_Agency = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization', ItemKey: 'Agency' });
    exports.ProtectedItem.Organization_AllProviderTypes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'AllProviderTypes' });
    exports.ProtectedItem.Organization_IRProvider = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization', ItemKey: 'IR Provider' });
    exports.ProtectedItem.Organization_Provider = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization', ItemKey: 'Provider' });
    exports.ProtectedItem.Organization_Site = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization', ItemKey: 'Site' });
    exports.ProtectedItem.Organization_StateUnit = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization', ItemKey: 'StateUnit' });
    exports.ProtectedItem.Agency_Contacts = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Agency', ItemKey: 'Contacts' });
    exports.ProtectedItem.Agency_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Agency', ItemKey: 'Details' });
    exports.ProtectedItem.Agency_Locations = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Agency', ItemKey: 'Locations' });
    exports.ProtectedItem.Agency_Phones = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Agency', ItemKey: 'Phones' });
    exports.ProtectedItem.Agency_PrivilegeFilters = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Agency', ItemKey: 'PrivilegeFilters' });
    exports.ProtectedItem.Agency_Providers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Agency', ItemKey: 'Providers' });
    exports.ProtectedItem.Agency_StaffingProfile = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Agency', ItemKey: 'StaffingProfile' });
    exports.ProtectedItem.IRProvider_Accessibilities = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Accessibilities' });
    exports.ProtectedItem.IRProvider_Agency = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Agency' });
    exports.ProtectedItem.IRProvider_Contacts = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Contacts' });
    exports.ProtectedItem.IRProvider_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Details' });
    exports.ProtectedItem.IRProvider_Eligibilities = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Eligibilities' });
    exports.ProtectedItem.IRProvider_Fees = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Fees' });
    exports.ProtectedItem.IRProvider_Keywords = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Keywords' });
    exports.ProtectedItem.IRProvider_Languages = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Languages' });
    exports.ProtectedItem.IRProvider_Locations = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Locations' });
    exports.ProtectedItem.IRProvider_Phones = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Phones' });
    exports.ProtectedItem.IRProvider_PrivilegeFilters = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'PrivilegeFilters' });
    exports.ProtectedItem.IRProvider_ProvTypes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'ProvTypes' });
    exports.ProtectedItem.IRProvider_Roles = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Roles' });
    exports.ProtectedItem.IRProvider_ServiceAreas = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Service Areas' });
    exports.ProtectedItem.IRProvider_Services = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Services' });
    exports.ProtectedItem.IRProvider_Sites = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Sites' });
    exports.ProtectedItem.IRProvider_Subproviders = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Subproviders' });
    exports.ProtectedItem.IRProvider_WebAccesses = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider', ItemKey: 'Web Access' });
    exports.ProtectedItem.IRProviderServices_Rates = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.IR Provider.Services', ItemKey: 'Rates' });
    exports.ProtectedItem.Provider_Accessibilities = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Accessibilities' });
    exports.ProtectedItem.Provider_Agency = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Agency' });
    exports.ProtectedItem.Provider_Contacts = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Contacts' });
    exports.ProtectedItem.Provider_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Details' });
    exports.ProtectedItem.Provider_Eligibilities = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Eligibilities' });
    exports.ProtectedItem.Provider_Fees = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Fees' });
    exports.ProtectedItem.Provider_Keywords = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Keywords' });
    exports.ProtectedItem.Provider_Languages = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Languages' });
    exports.ProtectedItem.Provider_Locations = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Locations' });
    exports.ProtectedItem.Provider_Phones = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Phones' });
    exports.ProtectedItem.Provider_PrivilegeFilters = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'PrivilegeFilters' });
    exports.ProtectedItem.Provider_ProvTypes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'ProvTypes' });
    exports.ProtectedItem.Provider_Roles = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Roles' });
    exports.ProtectedItem.Provider_ServiceAreas = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Service Areas' });
    exports.ProtectedItem.Provider_Services = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Services' });
    exports.ProtectedItem.Provider_Sites = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Sites' });
    exports.ProtectedItem.Provider_Subproviders = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Subproviders' });
    exports.ProtectedItem.Provider_WebAccesses = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider', ItemKey: 'Web Access' });
    exports.ProtectedItem.ProviderServices_Rates = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Provider.Services', ItemKey: 'Rates' });
    exports.ProtectedItem.Site_Contacts = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Site', ItemKey: 'Contacts' });
    exports.ProtectedItem.Site_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Site', ItemKey: 'Details' });
    exports.ProtectedItem.Site_Locations = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Site', ItemKey: 'Locations' });
    exports.ProtectedItem.Site_Phones = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Site', ItemKey: 'Phones' });
    exports.ProtectedItem.Site_SiteProviders = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.Site', ItemKey: 'SiteProviders' });
    exports.ProtectedItem.StateUnit_Contacts = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.StateUnit', ItemKey: 'Contacts' });
    exports.ProtectedItem.StateUnit_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.StateUnit', ItemKey: 'Details' });
    exports.ProtectedItem.StateUnit_Locations = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.StateUnit', ItemKey: 'Locations' });
    exports.ProtectedItem.StateUnit_Phones = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.StateUnit', ItemKey: 'Phones' });
    exports.ProtectedItem.StateUnit_PrivilegeFilters = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.StateUnit', ItemKey: 'PrivilegeFilters' });
    exports.ProtectedItem.StateUnit_StaffingProfile = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Organization.StateUnit', ItemKey: 'StaffingProfile' });
    exports.ProtectedItem.Places = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'Places' });
    exports.ProtectedItem.Places_Country = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places', ItemKey: 'Country' });
    exports.ProtectedItem.Places_County = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places', ItemKey: 'County' });
    exports.ProtectedItem.Places_Municipality = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places', ItemKey: 'Municipality' });
    exports.ProtectedItem.Places_Region = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places', ItemKey: 'Region' });
    exports.ProtectedItem.Places_State = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places', ItemKey: 'State' });
    exports.ProtectedItem.Places_Town = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places', ItemKey: 'Town' });
    exports.ProtectedItem.Places_ZipCode = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places', ItemKey: 'ZipCode' });
    exports.ProtectedItem.Country_CountryStates = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places.Country', ItemKey: 'CountryStates' });
    exports.ProtectedItem.Country_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places.Country', ItemKey: 'Details' });
    exports.ProtectedItem.County_CountyMunicipality = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places.County', ItemKey: 'CountyMunicipality' });
    exports.ProtectedItem.County_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places.County', ItemKey: 'Details' });
    exports.ProtectedItem.Town_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places.Town', ItemKey: 'Details' });
    exports.ProtectedItem.Town_TownZipCode = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Places.Town', ItemKey: 'TownZipCode' });
    exports.ProtectedItem.ProgramDefinition = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'ProgramDefinition' });
    exports.ProtectedItem.ProgramDefinition_Action = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'Action' });
    exports.ProtectedItem.ProgramDefinition_DiagnosisCodes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'DiagnosisCodes' });
    exports.ProtectedItem.ProgramDefinition_FundIdentifier = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'FundIdentifier' });
    exports.ProtectedItem.ProgramDefinition_LevelOfCare = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'LevelOfCare' });
    exports.ProtectedItem.ProgramDefinition_PlacesOfService = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'PlacesOfService' });
    exports.ProtectedItem.ProgramDefinition_Program = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'Program' });
    exports.ProtectedItem.ProgramDefinition_Service = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'Service' });
    exports.ProtectedItem.ProgramDefinition_ServiceCategory = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'ServiceCategory' });
    exports.ProtectedItem.ProgramDefinition_ServicePrograms = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'ServicePrograms' });
    exports.ProtectedItem.ProgramDefinition_Subservice = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'SubService' });
    exports.ProtectedItem.ProgramDefinition_Topic = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'Topic' });
    exports.ProtectedItem.ProgramDefinition_TopicCategory = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'TopicCategory' });
    exports.ProtectedItem.ProgramDefinition_TopicEventOutcome = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'TopicEventOutcome' });
    exports.ProtectedItem.ProgramDefinition_WebItems = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition', ItemKey: 'Web Items' });
    exports.ProtectedItem.FundIdentifier_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.FundIdentifier', ItemKey: 'Details' });
    exports.ProtectedItem.FundIdentifier_Services = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.FundIdentifier', ItemKey: 'Services' });
    exports.ProtectedItem.LevelOfCare_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.LevelOfCare', ItemKey: 'Details' });
    exports.ProtectedItem.LevelOfCare_CareProgram = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.LevelOfCare', ItemKey: 'ServiceProgram' });
    exports.ProtectedItem.Service_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.Service', ItemKey: 'Details' });
    exports.ProtectedItem.Service_PlacesOfService = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.Service', ItemKey: 'PlacesOfService' });
    exports.ProtectedItem.Service_ServiceTaxonomy = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.Service', ItemKey: 'Service Taxonomy' });
    exports.ProtectedItem.Service_ServiceSubservice = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.Service', ItemKey: 'ServiceSubservice' });
    exports.ProtectedItem.Service_ServiceTopic = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.Service', ItemKey: 'ServiceTopic' });
    exports.ProtectedItem.ServiceCategory_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.ServiceCategory', ItemKey: 'Details' });
    exports.ProtectedItem.ServiceCategory_ServCatServices = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.ServiceCategory', ItemKey: 'ServCatServices' });
    exports.ProtectedItem.ServicePrograms_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.ServicePrograms', ItemKey: 'Details' });
    exports.ProtectedItem.ServicePrograms_ServProgAccessPrivs = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.ServicePrograms', ItemKey: 'ServProgAccessPrivs' });
    exports.ProtectedItem.ServicePrograms_ServProgCostCap = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.ServicePrograms', ItemKey: 'ServProgCostCap' });
    exports.ProtectedItem.ServicePrograms_ServProgServices = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.ServicePrograms', ItemKey: 'ServProgServices' });
    exports.ProtectedItem.Topic_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.Topic', ItemKey: 'Details' });
    exports.ProtectedItem.Topic_Outcomes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'ProgramDefinition.Topic', ItemKey: 'Outcomes' });
    exports.ProtectedItem.ReportAdministration = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'Reports' });
    exports.ProtectedItem.ReportAdministration_CustomReports = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Reports', ItemKey: 'CustomReports' });
    exports.ProtectedItem.ReportAdministration_DocumentTemplate = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Reports', ItemKey: 'DocumentTemplate' });
    exports.ProtectedItem.SAMSAdmin = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'SAMSAdmin' });
    exports.ProtectedItem.Security_ = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'Security' });
    exports.ProtectedItem.Security_AccessRole = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Security', ItemKey: 'AccessRole' });
    exports.ProtectedItem.Security_UserLogin = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Security', ItemKey: 'UserLogin' });
    exports.ProtectedItem.Security_Users = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Security', ItemKey: 'Users' });
    exports.ProtectedItem.AccessRole_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Security.AccessRole', ItemKey: 'Details' });
    exports.ProtectedItem.AccessRole_Privileges = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Security.AccessRole', ItemKey: 'Privileges' });
    exports.ProtectedItem.UserLogin_Details = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Security.UserLogin', ItemKey: 'Details' });
    exports.ProtectedItem.UserLogin_Roles = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Security.UserLogin', ItemKey: 'Roles' });
    exports.ProtectedItem.Types_ = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: '', ItemKey: 'Types' });
    exports.ProtectedItem.Types_Accessibility = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'Accessibility' });
    exports.ProtectedItem.Types_Call = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'Call' });
    exports.ProtectedItem.Types_Caller = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'Caller' });
    exports.ProtectedItem.Types_ContactType = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'ContactType' });
    exports.ProtectedItem.Types_Disability = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'Disability' });
    exports.ProtectedItem.Types_Episode = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'Episode' });
    exports.ProtectedItem.Types_EpisodeDate = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'EpisodeDate' });
    exports.ProtectedItem.Types_Fee = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'Fee' });
    exports.ProtectedItem.Types_JournalType = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'JournalType' });
    exports.ProtectedItem.Types_LocationType = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'LocationType' });
    exports.ProtectedItem.Types_PaymentMethod = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'PaymentMethod' });
    exports.ProtectedItem.Types_PhoneType = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'PhoneType' });
    exports.ProtectedItem.Types_ProviderRoleType = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'ProviderRoleType' });
    exports.ProtectedItem.Types_ProviderType = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'ProviderType' });
    exports.ProtectedItem.Types_UnitType = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'UnitType' });
    exports.ProtectedItem.Types_USDAMealType = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Types', ItemKey: 'USDAMealType' });
    exports.ProtectedItem.ImportExportFeatures = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsImportExport, ParentKey: '', ItemKey: 'I/E' });
    exports.ProtectedItem.ImportExportFeatures_Export = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsImportExport, ParentKey: 'I/E', ItemKey: 'Export' });
    exports.ProtectedItem.ImportExportFeatures_Import = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsImportExport, ParentKey: 'I/E', ItemKey: 'Import' });
    exports.ProtectedItem.SamsImportExportApplication = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsImportExport, ParentKey: '', ItemKey: 'SAMS Import/Export' });
    exports.ProtectedItem.NAPISSRT = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.NapisSrt, ParentKey: '', ItemKey: 'NAPISSRT' });
    exports.ProtectedItem.CmsBiller = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CmsBiller, ParentKey: '', ItemKey: 'CMS Biller' });
    exports.ProtectedItem.CmsBatch = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CmsBiller, ParentKey: '', ItemKey: 'CmsBatch' });
    exports.ProtectedItem.CmsClaim = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CmsBiller, ParentKey: 'CmsBatch', ItemKey: 'CmsClaim' });
    exports.ProtectedItem.CmsSave837Locally = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CmsBiller, ParentKey: '', ItemKey: 'Save 837 Locally' });
    exports.ProtectedItem.CmsView837 = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CmsBiller, ParentKey: '', ItemKey: 'View 837' });
    exports.ProtectedItem.CmsDenySelectedClaimsViaReset = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CmsBiller, ParentKey: '', ItemKey: 'Deny Selected Claims Via Reset' });
    exports.ProtectedItem.CmsVoidSelectedClaims = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CmsBiller, ParentKey: '', ItemKey: 'Void Selected Claims' });
    exports.ProtectedItem.SAMSApp = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsApp, ParentKey: '', ItemKey: 'SAMSApp' });
    exports.ProtectedItem.SAMSApp_SAMSAppAdmin = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsApp, ParentKey: 'SAMSApp', ItemKey: 'SAMSApp Admin' });
    exports.ProtectedItem.SAMSApp_SAMSAppUser = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsApp, ParentKey: 'SAMSApp', ItemKey: 'SAMSApp User' });
    exports.ProtectedItem.Cgd = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CaregiverDirect, ParentKey: '', ItemKey: 'Caregiver Direct' });
    exports.ProtectedItem.CgdSendCredentials = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CaregiverDirect, ParentKey: '', ItemKey: 'Send Credentials' });
    exports.ProtectedItem.CgdRevokeConsumers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CaregiverDirect, ParentKey: '', ItemKey: 'Revoke Consumers' });
    exports.ProtectedItem.CgdShowCareManagers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CaregiverDirect, ParentKey: '', ItemKey: 'Show Care Managers' });
    exports.ProtectedItem.CgdViewCredentials = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CaregiverDirect, ParentKey: '', ItemKey: 'View Last Sent Credentials' });
    exports.ProtectedItem.CgdUsers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CaregiverDirect, ParentKey: '', ItemKey: 'Caregiver Direct Users' });
    exports.ProtectedItem.CgdSimulateView_AllUsers = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CaregiverDirect, ParentKey: '', ItemKey: 'Simulate View (all users)' });
    exports.ProtectedItem.CgdSimulateView_DefaultAgencyOnly = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.CaregiverDirect, ParentKey: '', ItemKey: 'Simulate View (default agency only)' });
    exports.ProtectedItem.Wrc = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.WebResourceCenter, ParentKey: '', ItemKey: 'Web Resource Center' });
    exports.ProtectedItem.WrcSendCredentials = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.WebResourceCenter, ParentKey: '', ItemKey: 'Send Provider Credentials' });
    exports.ProtectedItem.Field_NumberofADLs = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'ADLS' });
    exports.ProtectedItem.Field_AKAName = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'AKA_NAME' });
    exports.ProtectedItem.Field_AlternateId1 = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'ALT_ID_1' });
    exports.ProtectedItem.Field_AlternateId2 = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'ALT_ID_2' });
    exports.ProtectedItem.Field_AuditTrailInformation = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'AuditView' });
    exports.ProtectedItem.Field_ClientID = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'CLIENT_ID' });
    exports.ProtectedItem.Field_DefaultAgency = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'ConsumerDefaultAgency' });
    exports.ProtectedItem.Field_ConsumerStatus = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'ConsumerStatus' });
    exports.ProtectedItem.Field_DateRegistered = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'DATE_REGISTERED' });
    exports.ProtectedItem.Field_DirectionsToHome = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'DIRECTIONS_TO_HOME' });
    exports.ProtectedItem.Field_DateofBirth = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'DOB' });
    exports.ProtectedItem.Field_EmailAddress = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'EMAIL_ADDR' });
    exports.ProtectedItem.Field_HighNutritionalRisk = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'HIGH_NUTR_RISK' });
    exports.ProtectedItem.Field_NumberofIADLs = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IADLS' });
    exports.ProtectedItem.Field_IsAbusedorNeglectedorExploited = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_ABUSED_NEG' });
    exports.ProtectedItem.Field_JournalDateTime = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'JournalDateTime' });
    exports.ProtectedItem.Field_LastName = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'LAST_NAME' });
    exports.ProtectedItem.Field_LivesAlone = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'LIVES_ALONE' });
    exports.ProtectedItem.Field_MaidenName = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'MAIDEN_NAME' });
    exports.ProtectedItem.Field_MedicaidNo = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'MEDICAID_NO' });
    exports.ProtectedItem.Field_MedicalPolicyNo = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'MEDICAL_POLICY_NO' });
    exports.ProtectedItem.Field_MedicareNo = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'MEDICARE_NO' });
    exports.ProtectedItem.Field_ConsumerNotes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'NOTES' });
    exports.ProtectedItem.Field_ServiceDeliveryRate = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'ServiceDelivery.Rate' });
    exports.ProtectedItem.Field_ServiceOrderRate = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'ServiceOrder.Rate' });
    exports.ProtectedItem.Field_ServicePlanRate = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'ServicePlan.Rate' });
    exports.ProtectedItem.Field_SocialSecurityNo = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'SSN' });
    exports.ProtectedItem.Field_Ethnicity = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'ETHNICITY' });
    exports.ProtectedItem.Field_InPoverty = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_IN_POVERTY' });
    exports.ProtectedItem.Field_IsRural = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_RURAL' });
    exports.ProtectedItem.Field_MedicareEligible = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_MEDICARE_ELIGIBLE' });
    exports.ProtectedItem.Field_MedicalAssistanceID = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'MA_ID' });
    exports.ProtectedItem.Field_MonthlyHouseholdIncome = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'HOUSEHOLD_INCOME' });
    exports.ProtectedItem.Field_HouseholdSize = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'HOUSEHOLD_SIZE' });
    exports.ProtectedItem.Field_MonthlyIndividualIncome = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'INDIVIDUAL_INCOME' });
    exports.ProtectedItem.Field_Referredby = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'REFERRED_BY' });
    exports.ProtectedItem.Field_CognitiveImpairment = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'COGNITIVE_IMPAIRMENT' });
    exports.ProtectedItem.Field_Disabled = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_DISABLED' });
    exports.ProtectedItem.Field_DuplicateMail = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_DUP_MAIL' });
    exports.ProtectedItem.Field_EmploymentStatus = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'EMPLOYMENT_STATUS' });
    exports.ProtectedItem.Field_FemaleHeadofHousehold = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_FEMALE_HOHH' });
    exports.ProtectedItem.Field_Frail = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_FRAIL' });
    exports.ProtectedItem.Field_HomeBound = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_HOMEBOUND' });
    exports.ProtectedItem.Field_ReceivingSocialSecurity = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_SSI' });
    exports.ProtectedItem.Field_StateResident = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_STATE_RESIDENT' });
    exports.ProtectedItem.Field_Tribal = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_TRIBAL' });
    exports.ProtectedItem.Field_UnderstandsEnglish = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'UNDERSTANDS_ENGLISH' });
    exports.ProtectedItem.Field_USCitizen = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_US_CITIZEN' });
    exports.ProtectedItem.Field_NSIPMealEligible = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_USDAMEAL_ELIGIBLE' });
    exports.ProtectedItem.Field_NSIPMealsEligibilityType = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'USDAMEAL_TYPE_CODE' });
    exports.ProtectedItem.Field_Veteran = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_VETERAN' });
    exports.ProtectedItem.Field_VeteranDependent = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'IS_VETERAN_DEPENDANT' });
    exports.ProtectedItem.Field_ProviderActive = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'IS_ACTIVE' });
    exports.ProtectedItem.Field_ProviderName = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'NAME' });
    exports.ProtectedItem.Field_ProviderNPI = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'NPI' });
    exports.ProtectedItem.Field_ProviderUniversalPIN = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'UNIVERSAL_PIN' });
    exports.ProtectedItem.Field_ProviderStartDate = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'START_DATE' });
    exports.ProtectedItem.Field_ProviderEndDate = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'END_DATE' });
    exports.ProtectedItem.Field_ProviderShortDescription = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'SHORT_DESCRIPTION' });
    exports.ProtectedItem.Field_ProviderLongDescription = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'LONG_DESCRIPTION' });
    exports.ProtectedItem.Field_ProviderLegalName = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'LEGAL_NAME' });
    exports.ProtectedItem.Field_ProviderAlias = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'ALIAS' });
    exports.ProtectedItem.Field_ProviderNotes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'NOTES' });
    exports.ProtectedItem.Field_ProviderMedicalAssistanceID = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'MA_ID' });
    exports.ProtectedItem.Field_ProviderMedicaidNo = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'MEDICAID_NO' });
    exports.ProtectedItem.Field_ProviderMedicareNo = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'MEDICARE_NO' });
    exports.ProtectedItem.Field_ProviderDefaultBillingID = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'DEFAULT_BILLING_ID' });
    exports.ProtectedItem.Field_ProviderDetailsLastReviewed = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'DETAILS_LAST_REVIEWED' });
    exports.ProtectedItem.Field_ProviderPrimaryAgency = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Provider Fields', ItemKey: 'PRIMARY_AGENCY_UUID' });
    exports.ProtectedItem.Field_IRProviderActive = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'IS_ACTIVE' });
    exports.ProtectedItem.Field_IRProviderName = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'NAME' });
    exports.ProtectedItem.Field_IRProviderNPI = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'NPI' });
    exports.ProtectedItem.Field_IRProviderUniversalPIN = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'UNIVERSAL_PIN' });
    exports.ProtectedItem.Field_IRProviderStartDate = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'START_DATE' });
    exports.ProtectedItem.Field_IRProviderEndDate = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'END_DATE' });
    exports.ProtectedItem.Field_IRProviderShortDescription = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'SHORT_DESCRIPTION' });
    exports.ProtectedItem.Field_IRProviderLongDescription = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'LONG_DESCRIPTION' });
    exports.ProtectedItem.Field_IRProviderLegalName = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'LEGAL_NAME' });
    exports.ProtectedItem.Field_IRProviderAlias = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'ALIAS' });
    exports.ProtectedItem.Field_IRProviderNotes = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'NOTES' });
    exports.ProtectedItem.Field_IRProviderMedicalAssistanceID = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'MA_ID' });
    exports.ProtectedItem.Field_IRProviderMedicaidNo = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'MEDICAID_NO' });
    exports.ProtectedItem.Field_IRProviderMedicareNo = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'MEDICARE_NO' });
    exports.ProtectedItem.Field_IRProviderDefaultBillingID = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'DEFAULT_BILLING_ID' });
    exports.ProtectedItem.Field_IRProviderDetailsLastReviewed = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'DETAILS_LAST_REVIEWED' });
    exports.ProtectedItem.Field_IRProviderPrimaryAgency = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'IR Provider Fields', ItemKey: 'PRIMARY_AGENCY_UUID' });
    exports.ProtectedItem.Field_EpisodeLeadAgency = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Episode Fields', ItemKey: 'Lead Agency' });
    exports.ProtectedItem.Field_EpisodeBillingAgency = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: 'Episode Fields', ItemKey: 'Billing Agency' });
    exports.ProtectedItem.APSReferralInformation = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'APSReferralView' });
    exports.ProtectedItem.Field_Language = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'LANGUAGE_UUID' });
    exports.ProtectedItem.Field_MaritalStatus = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'MARITAL_STATUS_UUID' });
    exports.ProtectedItem.Field_Gender = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'GENDER' });
    exports.ProtectedItem.Field_ClientDetailsLastRevised = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'CLIENT_DETAILS_REVISED' });
    exports.ProtectedItem.Field_InfoReleaseAuthorized = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'INFO_RELEASE_AUTHORIZED' });
    exports.ProtectedItem.Field_ServiceDeliveryTopics = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.Sams, ParentKey: '', ItemKey: 'TEMP TEMP TEMP TEMP' });
    exports.ProtectedItem.Configuration_ServiceLock = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Configuration', ItemKey: 'ServiceLock' });
    exports.ProtectedItem.Configuration_ServiceUnlock = exports.ProtectedItem.addSymbol({ ProtectedApplication: exports.ProtectedApplication.SamsAdministrator, ParentKey: 'Configuration.ServiceLock', ItemKey: 'ServiceUnlock' });
    exports.ProtectedItem.resolveSymbols();
    exports.Product = new breeze.core.Enum('Product');
    exports.Product.Unknown = exports.Product.addSymbol({ id: 0, description: '*Unknown*' });
    exports.Product.OmniaInterviewer = exports.Product.addSymbol({ id: 1, description: 'Omnia Interviewer' });
    exports.Product.ProviderDirect = exports.Product.addSymbol({ id: 2, description: 'Harmony Provider Direct' });
    exports.Product.HarmonyForAging = exports.Product.addSymbol({ id: 3, description: 'Harmony for Aging' });
    exports.Product.OmbudsManager = exports.Product.addSymbol({ id: 4, description: 'OmbudsManager' });
    exports.Product.HarmonyforAPS = exports.Product.addSymbol({ id: 5, description: 'Harmony for APS' });
    exports.Product.HarmonyForID = exports.Product.addSymbol({ id: 6, description: 'Harmony for ID' });
    exports.Product.NapisSrt = exports.Product.addSymbol({ id: 7, description: 'NAPIS State Reporting Tool' });
    exports.Product.OmbudsmanReportingTool = exports.Product.addSymbol({ id: 8, description: 'Ombudsman Reporting Tool' });
    exports.Product.TribalReportingTool = exports.Product.addSymbol({ id: 9, description: 'Tribal Reporting Tool' });
    exports.Product.NysofaReporter = exports.Product.addSymbol({ id: 10, description: 'NYSOFA Reporter' });
    exports.Product.CdaReporter = exports.Product.addSymbol({ id: 11, description: 'CDAReporterUsers' });
    exports.Product.MsspReporter = exports.Product.addSymbol({ id: 12, description: 'MSSP Reporter' });
    exports.Product.HarmonyIR = exports.Product.addSymbol({ id: 13, description: 'Harmony IR' });
    exports.Product.Ship = exports.Product.addSymbol({ id: 14, description: 'State Health Insurance Assistance Program' });
    exports.Product.DocumentAttachments = exports.Product.addSymbol({ id: 15, description: 'Document Attachments' });
    exports.Product.AssistGuideIntegration = exports.Product.addSymbol({ id: 16, description: 'AssistGuide Integration' });
    exports.Product.HarmonyAdvancedReporting = exports.Product.addSymbol({ id: 17, description: 'Harmony Advanced Reporting' });
    exports.Product.SamsVansql07 = exports.Product.addSymbol({ id: 18, description: 'SAMSUsers' });
    exports.Product.SamsAdministratorVansql07 = exports.Product.addSymbol({ id: 19, description: 'SAMSAdminUsers' });
    exports.Product.InterviewerVansql07 = exports.Product.addSymbol({ id: 20, description: 'OmniaInterviewerUsers' });
    exports.Product.SamsVansql06 = exports.Product.addSymbol({ id: 21, description: 'SIMS_SAMS' });
    exports.Product.SamsAdministratorVansql06 = exports.Product.addSymbol({ id: 22, description: 'SIMS_SAMS_Administrator' });
    exports.Product.InterviewerVansql06 = exports.Product.addSymbol({ id: 23, description: 'SIMS_Omnia_Interviewer' });
    exports.Product.SamsTtnsql01 = exports.Product.addSymbol({ id: 24, description: 'SAMS_ttnsql01' });
    exports.Product.SamsAdministratorTtnsql01 = exports.Product.addSymbol({ id: 25, description: 'SAMSAdmin_ttnsql01' });
    exports.Product.InterviewerTtnsql01 = exports.Product.addSymbol({ id: 26, description: 'Interviewer_ttnsql01' });
    exports.Product.CaregiverDirect = exports.Product.addSymbol({ id: 27, description: 'Caregiver Direct' });
    exports.Product.BulkUpload = exports.Product.addSymbol({ id: 28, description: 'Bulk Upload' });
    exports.Product.Access2000 = exports.Product.addSymbol({ id: 29, description: 'Access2000Users' });
    exports.Product.SamsImportExportVansql07 = exports.Product.addSymbol({ id: 30, description: 'SAMSIEUsers' });
    exports.Product.OmniaAnalyzerVansql07 = exports.Product.addSymbol({ id: 31, description: 'OmniaAnalyzerUsers' });
    exports.Product.OmniaDesignerVansql07 = exports.Product.addSymbol({ id: 32, description: 'OmniaDesignerUsers' });
    exports.Product.HarmonyAdvancedReportingDesigners = exports.Product.addSymbol({ id: 33, description: 'Report_Users' });
    exports.Product.SamsScanVansql07 = exports.Product.addSymbol({ id: 34, description: 'SAMSScanUsers' });
    exports.Product.ArCmsBillerVansql07 = exports.Product.addSymbol({ id: 35, description: 'AR CMS Biller' });
    exports.Product.HarmonyFinanceModule = exports.Product.addSymbol({ id: 36, description: 'Harmony Finance Module' });
    exports.Product.BeaconVansql06 = exports.Product.addSymbol({ id: 37, description: 'SIMS_Beacon' });
    exports.Product.OmniaAnalyzerVansql06 = exports.Product.addSymbol({ id: 38, description: 'SIMS_Omnia_Analyzer' });
    exports.Product.OmniaDesignerVansql06 = exports.Product.addSymbol({ id: 39, description: 'SIMS_Omnia_Designer' });
    exports.Product.SamsImportExportVansql06 = exports.Product.addSymbol({ id: 40, description: 'SIMS_SAMS_IE_Utility' });
    exports.Product.CaCmsBillerVansql07 = exports.Product.addSymbol({ id: 41, description: 'CA CMS Biller' });
    exports.Product.FlCmsBillerVansql07 = exports.Product.addSymbol({ id: 42, description: 'FL CMS Biller' });
    exports.Product.MeCmsBillerVansql07 = exports.Product.addSymbol({ id: 43, description: 'ME CMS Biller' });
    exports.Product.NvCmsBillerVansql07 = exports.Product.addSymbol({ id: 44, description: 'NV CMS Biller' });
    exports.Product.TnCmsBillerVansql07 = exports.Product.addSymbol({ id: 45, description: 'TN CMS Biller' });
    exports.Product.SamsAnsql09 = exports.Product.addSymbol({ id: 46, description: 'SAMSVAN09' });
    exports.Product.SamsAdministratorAnsql09 = exports.Product.addSymbol({ id: 47, description: 'SAMSAdminVAN09' });
    exports.Product.OmniaDesignerAnsql09 = exports.Product.addSymbol({ id: 48, description: 'OmniaDesignerVAN09' });
    exports.Product.OmniaAnalyzerAnsql09 = exports.Product.addSymbol({ id: 49, description: 'OmniaAnalyzerVAN09' });
    exports.Product.SamsImportExportAnsql09 = exports.Product.addSymbol({ id: 50, description: 'SAMSIEVAN09' });
    exports.Product.SamsScanAnsql09 = exports.Product.addSymbol({ id: 51, description: 'SAMSScanVAN09' });
    exports.Product.OmniaInterviewerAnsql09 = exports.Product.addSymbol({ id: 52, description: 'OmniaInterviewerVAN09' });
    exports.Product.NysofaReporterAnsql09 = exports.Product.addSymbol({ id: 53, description: 'NYSOFAReporterVAN09' });
    exports.Product.CdaReporterAnsql09 = exports.Product.addSymbol({ id: 54, description: 'CDAReporterUsersVAN09' });
    exports.Product.MsspReporterAnsql09 = exports.Product.addSymbol({ id: 55, description: 'MSSPReporterVAN09' });
    exports.Product.CaCmsBillerAnsql09 = exports.Product.addSymbol({ id: 56, description: 'CACMSBillerVAN09' });
    exports.Product.BeaconUsersAnsql09 = exports.Product.addSymbol({ id: 57, description: 'BeaconUsersVAN09' });
    exports.Product.SamsSqldw02Rs02 = exports.Product.addSymbol({ id: 58, description: 'SAMS_RS02' });
    exports.Product.SamsAdminSqldw02Rs02 = exports.Product.addSymbol({ id: 59, description: 'SAMSAdmin_RS02' });
    exports.Product.SamsImportExportSqldw02Rs02 = exports.Product.addSymbol({ id: 60, description: 'SAMSIE_RS02' });
    exports.Product.OmniaInterviewerSqldw02Rs02 = exports.Product.addSymbol({ id: 61, description: 'OmniaInterviewer_RS02' });
    exports.Product.OmniaDesignerSqldw02Rs02 = exports.Product.addSymbol({ id: 62, description: 'OmniaDesigner_RS02' });
    exports.Product.NapisSrtVansql06 = exports.Product.addSymbol({ id: 63, description: 'SIMS_SAMS_SRT' });
    exports.Product.PvReporterVansql06 = exports.Product.addSymbol({ id: 64, description: 'SIMS_PV_Reporter' });
    exports.Product.InterRai = exports.Product.addSymbol({ id: 65, description: 'interRAI' });
    exports.Product.BeaconVansql07 = exports.Product.addSymbol({ id: 66, description: 'BeaconUsers' });
    exports.Product.OmbudsManagerLegacy = exports.Product.addSymbol({ id: 67, description: 'OmbudsManagerUsers' });
    exports.Product.AgencyReportingTool = exports.Product.addSymbol({ id: 68, description: 'ARToolUsers' });
    exports.Product.MjmIntegration = exports.Product.addSymbol({ id: 69, description: 'MJM Integration' });
    exports.Product.WebResourceCenterIntegration = exports.Product.addSymbol({ id: 70, description: 'Web Resource Center Integration' });
    exports.Product.HarmonyHostingLicense = exports.Product.addSymbol({ id: 71, description: 'Harmony Hosting License' });
    exports.Product.SamsSql10 = exports.Product.addSymbol({ id: 72, description: 'SAMSSQL10' });
    exports.Product.SamsAdministratorSql10 = exports.Product.addSymbol({ id: 73, description: 'SAMSAdminSQL10' });
    exports.Product.OmniaDesignerSql10 = exports.Product.addSymbol({ id: 74, description: 'OmniaDesignerSQL10' });
    exports.Product.OmniaAnalyzerSql10 = exports.Product.addSymbol({ id: 75, description: 'OmniaAnalyzerSQL10' });
    exports.Product.SamsImportExportSql10 = exports.Product.addSymbol({ id: 76, description: 'SAMSIESQL10' });
    exports.Product.SamsScanSql10 = exports.Product.addSymbol({ id: 77, description: 'SAMSScanSQL10' });
    exports.Product.OmniaInterviewerSql10 = exports.Product.addSymbol({ id: 78, description: 'OmniaInterviewerSQL10' });
    exports.Product.NysofaReporterSQL10 = exports.Product.addSymbol({ id: 79, description: 'NYSOFAReporterSQL10' });
    exports.Product.CdaReporterSQL10 = exports.Product.addSymbol({ id: 80, description: 'CDAReporterUsersSQL10' });
    exports.Product.MsspReporterSQL10 = exports.Product.addSymbol({ id: 81, description: 'MSSPReporterSQL10' });
    exports.Product.CaCmsBillerSQL10 = exports.Product.addSymbol({ id: 82, description: 'CACMSBillerSQL10' });
    exports.Product.BeaconUsersSQL10 = exports.Product.addSymbol({ id: 83, description: 'BeaconUsersSQL10' });
    exports.Product.SamsiVanSql = exports.Product.addSymbol({ id: 84, description: 'SAMSIVANSQL' });
    exports.Product.SamsAdministratoriVanSql = exports.Product.addSymbol({ id: 85, description: 'SAMSAdminIVANSQL' });
    exports.Product.OmniaDesigneriVanSql = exports.Product.addSymbol({ id: 86, description: 'OmniaDesignerIVANSQL' });
    exports.Product.OmniaAnalyzeriVanSql = exports.Product.addSymbol({ id: 87, description: 'OmniaAnalyzerIVANSQL' });
    exports.Product.SamsImportExportiVanSql = exports.Product.addSymbol({ id: 88, description: 'SAMSIEIVANSQL' });
    exports.Product.SamsScaniVanSql = exports.Product.addSymbol({ id: 89, description: 'SAMSScanIVANSQL' });
    exports.Product.OmniaIntervieweriVanSql = exports.Product.addSymbol({ id: 90, description: 'OmniaInterviewerIVANSQL' });
    exports.Product.NysofaReporterIVANSQL = exports.Product.addSymbol({ id: 91, description: 'NYSOFAReporterIVANSQL' });
    exports.Product.CdaReporterIVANSQL = exports.Product.addSymbol({ id: 92, description: 'CDAReporterUsersIVANSQL' });
    exports.Product.MsspReporterIVANSQL = exports.Product.addSymbol({ id: 93, description: 'MSSPReporterIVANSQL' });
    exports.Product.CaCmsBillerIVANSQL = exports.Product.addSymbol({ id: 94, description: 'CACMSBillerIVANSQL' });
    exports.Product.BeaconUsersIVANSQL = exports.Product.addSymbol({ id: 95, description: 'BeaconUsersIVANSQL' });
    exports.Product.NapisSrtVansql07 = exports.Product.addSymbol({ id: 96, description: 'NAPISSRTSAMSUsers' });
    exports.Product.NapisSrtIVANSQL = exports.Product.addSymbol({ id: 97, description: 'NAPISSRTSAMSIVANSQL' });
    exports.Product.PhysicianPortal = exports.Product.addSymbol({ id: 98, description: 'Physician Portal' });
    exports.Product.SamsSql05aSql08d2 = exports.Product.addSymbol({ id: 99, description: 'MAFTSamsUsers' });
    exports.Product.SamsAdministratorSql05aSql08d2 = exports.Product.addSymbol({ id: 100, description: 'MAFTSamsAdminUsers' });
    exports.Product.OmniaDesignerSql05aSql08d2 = exports.Product.addSymbol({ id: 101, description: 'MAFTOmniaDesignerUsers' });
    exports.Product.OmniaAnalyzerSql05aSql08d2 = exports.Product.addSymbol({ id: 102, description: 'MAFTOmniaAnalyzerUsers' });
    exports.Product.SamsImportExportSql05aSql08d2 = exports.Product.addSymbol({ id: 103, description: 'MAFTSamsImportExportUsers' });
    exports.Product.SamsScanSql05aSql08d2 = exports.Product.addSymbol({ id: 104, description: 'MAFTSamsScanUsers' });
    exports.Product.OmniaInterviewerSql05aSql08d2 = exports.Product.addSymbol({ id: 105, description: 'MAFTOmniaInterviewerUsers' });
    exports.Product.BeaconUsersSql05aSql08d2 = exports.Product.addSymbol({ id: 106, description: 'MAFTBeaconUsers' });
    exports.Product.NapisSrtSql05aSql08d2 = exports.Product.addSymbol({ id: 107, description: 'MAFTNapisSRTSamsUsers' });
    exports.Product.PvReporterSql05aSql08d2 = exports.Product.addSymbol({ id: 108, description: 'MAFTPvReporterUsers' });
    exports.Product.SamsSql11 = exports.Product.addSymbol({ id: 109, description: 'SAMSSQL11' });
    exports.Product.SamsAdministratorSql11 = exports.Product.addSymbol({ id: 110, description: 'SAMSAdminSQL11' });
    exports.Product.OmniaDesignerSql11 = exports.Product.addSymbol({ id: 111, description: 'OmniaDesignerSQL11' });
    exports.Product.OmniaAnalyzerSql11 = exports.Product.addSymbol({ id: 112, description: 'OmniaAnalyzerSQL11' });
    exports.Product.SamsImportExportSql11 = exports.Product.addSymbol({ id: 113, description: 'SAMSIESQL11' });
    exports.Product.SamsScanSql11 = exports.Product.addSymbol({ id: 114, description: 'SAMSScanSQL11' });
    exports.Product.OmniaInterviewerSql11 = exports.Product.addSymbol({ id: 115, description: 'OmniaInterviewerSQL11' });
    exports.Product.NysofaReporterSql11 = exports.Product.addSymbol({ id: 116, description: 'NYSOFAReporterSQL11' });
    exports.Product.CdaReporterSql11 = exports.Product.addSymbol({ id: 117, description: 'CDAReporterUsersSQL11' });
    exports.Product.MsspReporterSql11 = exports.Product.addSymbol({ id: 118, description: 'MSSPReporterSQL11' });
    exports.Product.CaCmsBillerSql11 = exports.Product.addSymbol({ id: 119, description: 'CACMSBillerSQL11' });
    exports.Product.BeaconUsersSql11 = exports.Product.addSymbol({ id: 120, description: 'BeaconUsersSQL11' });
    exports.Product.NapisSrtSql11 = exports.Product.addSymbol({ id: 121, description: 'NAPISSRTSAMSSQL11' });
    exports.Product.CareTransitions = exports.Product.addSymbol({ id: 122, description: 'Care Transitions' });
    exports.Product.SamsSql12 = exports.Product.addSymbol({ id: 123, description: 'SAMSSQL12' });
    exports.Product.SamsAdministratorSql12 = exports.Product.addSymbol({ id: 124, description: 'SAMSAdminSQL12' });
    exports.Product.OmniaDesignerSql12 = exports.Product.addSymbol({ id: 125, description: 'OmniaDesignerSQL12' });
    exports.Product.OmniaAnalyzerSql12 = exports.Product.addSymbol({ id: 126, description: 'OmniaAnalyzerSQL12' });
    exports.Product.SamsImportExportSql12 = exports.Product.addSymbol({ id: 127, description: 'SAMSIESQL12' });
    exports.Product.SamsScanSql12 = exports.Product.addSymbol({ id: 128, description: 'SAMSScanSQL12' });
    exports.Product.OmniaInterviewerSql12 = exports.Product.addSymbol({ id: 129, description: 'OmniaInterviewerSQL12' });
    exports.Product.NysofaReporterSql12 = exports.Product.addSymbol({ id: 130, description: 'NYSOFAReporterSQL12' });
    exports.Product.CdaReporterSql12 = exports.Product.addSymbol({ id: 131, description: 'CDAReporterUsersSQL12' });
    exports.Product.MsspReporterSql12 = exports.Product.addSymbol({ id: 132, description: 'MSSPReporterSQL12' });
    exports.Product.CaCmsBillerSql12 = exports.Product.addSymbol({ id: 133, description: 'CACMSBillerSQL12' });
    exports.Product.BeaconUsersSql12 = exports.Product.addSymbol({ id: 134, description: 'BeaconUsersSQL12' });
    exports.Product.NapisSrtSql12 = exports.Product.addSymbol({ id: 135, description: 'NAPISSRTSAMSSQL12' });
    exports.Product.OmniaAnalyzerNavpasql = exports.Product.addSymbol({ id: 136, description: 'OMNIAANALYZERNAVPASQL' });
    exports.Product.OmniaDesignerNavpasql = exports.Product.addSymbol({ id: 137, description: 'OMNIADESIGNERNAVPASQL' });
    exports.Product.OmniaInterviewerNavpasql = exports.Product.addSymbol({ id: 138, description: 'OMNIAINTNAVPASQL' });
    exports.Product.SamsNavpasql = exports.Product.addSymbol({ id: 139, description: 'SAMSNAVPASQL' });
    exports.Product.SamsAdministratorNavpasql = exports.Product.addSymbol({ id: 140, description: 'SAMSADMINNAVPASQL' });
    exports.Product.SamsImportExportNavpasql = exports.Product.addSymbol({ id: 141, description: 'SAMSIENAVPASQL' });
    exports.Product.SamsScanNavpasql = exports.Product.addSymbol({ id: 142, description: 'SAMSCANNAVPASQL' });
    exports.Product.SamsHcsisNavpasql = exports.Product.addSymbol({ id: 143, description: 'SAMSHCSISNAVPASQL' });
    exports.Product.SamsHcsisPaidClaimsNavpasql = exports.Product.addSymbol({ id: 144, description: 'SAMSHCSISPCNAVPASQL' });
    exports.Product.SamsHcsisIvansql = exports.Product.addSymbol({ id: 145, description: 'SAMSHCSISIVANSQL' });
    exports.Product.SamsHcsisPaidClaimsIvansql = exports.Product.addSymbol({ id: 146, description: 'SAMSHCSISPCIVANSQL' });
    exports.Product.SamsHcsisSql10 = exports.Product.addSymbol({ id: 147, description: 'SAMSHCSISSQL10' });
    exports.Product.SamsHcsisPaidClaimsSql10 = exports.Product.addSymbol({ id: 148, description: 'SAMSHCSISPCSQL10' });
    exports.Product.SamsHcsisSql12 = exports.Product.addSymbol({ id: 149, description: 'SAMSHCSISSQL12' });
    exports.Product.SamsHcsisPaidClaimsSql12 = exports.Product.addSymbol({ id: 150, description: 'SAMSHCSISPCSQL12' });
    exports.Product.RouteMapping = exports.Product.addSymbol({ id: 151, description: 'Route Mapping' });
    exports.Product.MoneyFollowsThePerson = exports.Product.addSymbol({ id: 152, description: 'Money Follows the Person' });
    exports.Product.MobileAssessments = exports.Product.addSymbol({ id: 153, description: 'Mobile Assessments' });
    exports.Product.Samscan = exports.Product.addSymbol({ id: 154, description: 'Samscan' });
    exports.Product.OfflineMobileAssessments = exports.Product.addSymbol({ id: 155, description: 'Offline Mobile Assessments' });
    exports.Product.CommunityLinksPortal = exports.Product.addSymbol({ id: 156, description: 'Community Links Portal' });
    exports.Product.SAMSPPRSQL14 = exports.Product.addSymbol({ id: 157, description: 'SAMSPPRSQL14' });
    exports.Product.SamsAdminPPRSQL14 = exports.Product.addSymbol({ id: 158, description: 'SAMSAdminPPRSQL14' });
    exports.Product.OmniaDesignerPPRSQL14 = exports.Product.addSymbol({ id: 159, description: 'OmniaDesignerPPRSQL14' });
    exports.Product.OmniaAnalyzerPPRSQL14 = exports.Product.addSymbol({ id: 160, description: 'OmniaAnalyzerPPRSQL14' });
    exports.Product.SamsImportExportPPRSQL14 = exports.Product.addSymbol({ id: 161, description: 'SAMSIEPPRSQL14' });
    exports.Product.SamsScanPPRSQL14 = exports.Product.addSymbol({ id: 162, description: 'SAMSScanPPRSQL14' });
    exports.Product.OmniaInterviewerPPRSQL14 = exports.Product.addSymbol({ id: 163, description: 'OmniaInterviewerPPRSQL14' });
    exports.Product.NysofaReporterPPRSQL14 = exports.Product.addSymbol({ id: 164, description: 'NYSOFAReporterPPRSQL14' });
    exports.Product.CdaReporterPPRSQL14 = exports.Product.addSymbol({ id: 165, description: 'CDAReporterUsersPPRSQL14' });
    exports.Product.MsspReporterPPRSQL14 = exports.Product.addSymbol({ id: 166, description: 'MSSPReporterPPRSQL14' });
    exports.Product.CaCmsBillerPPRSQL14 = exports.Product.addSymbol({ id: 167, description: 'CACMSBillerPPRSQL14' });
    exports.Product.BeaconUsersPPRSQL14 = exports.Product.addSymbol({ id: 168, description: 'BeaconUsersPPRSQL14' });
    exports.Product.NapisSrtPPRSQL14 = exports.Product.addSymbol({ id: 169, description: 'NAPISSRTSAMSPPRSQL14' });
    exports.Product.SamsHcsisPPRSQL14 = exports.Product.addSymbol({ id: 170, description: 'SAMSHCSISPPRSQL14' });
    exports.Product.SamsHcsisPaidClaimsPPRSQL14 = exports.Product.addSymbol({ id: 171, description: 'SAMSHCSISPCPPRSQL14' });
    exports.Product.SAMSPPRSQL12 = exports.Product.addSymbol({ id: 172, description: 'SAMSPPRSQL12' });
    exports.Product.SamsAdminPPRSQL12 = exports.Product.addSymbol({ id: 173, description: 'SAMSAdminPPRSQL12' });
    exports.Product.OmniaDesignerPPRSQL12 = exports.Product.addSymbol({ id: 174, description: 'OmniaDesignerPPRSQL12' });
    exports.Product.OmniaAnalyzerPPRSQL12 = exports.Product.addSymbol({ id: 175, description: 'OmniaAnalyzerPPRSQL12' });
    exports.Product.SamsImportExportPPRSQL12 = exports.Product.addSymbol({ id: 176, description: 'SAMSIEPPRSQL12' });
    exports.Product.SamsScanPPRSQL12 = exports.Product.addSymbol({ id: 177, description: 'SAMSScanPPRSQL12' });
    exports.Product.OmniaInterviewerPPRSQL12 = exports.Product.addSymbol({ id: 178, description: 'OmniaInterviewerPPRSQL12' });
    exports.Product.NysofaReporterPPRSQL12 = exports.Product.addSymbol({ id: 179, description: 'NYSOFAReporterPPRSQL12' });
    exports.Product.CdaReporterPPRSQL12 = exports.Product.addSymbol({ id: 180, description: 'CDAReporterUsersPPRSQL12' });
    exports.Product.MsspReporterPPRSQL12 = exports.Product.addSymbol({ id: 181, description: 'MSSPReporterPPRSQL12' });
    exports.Product.CaCmsBillerPPRSQL12 = exports.Product.addSymbol({ id: 182, description: 'CACMSBillerPPRSQL12' });
    exports.Product.BeaconUsersPPRSQL12 = exports.Product.addSymbol({ id: 183, description: 'BeaconUsersPPRSQL12' });
    exports.Product.NapisSrtPPRSQL12 = exports.Product.addSymbol({ id: 184, description: 'NAPISSRTSAMSPPRSQL12' });
    exports.Product.SamsHcsisPPRSQL12 = exports.Product.addSymbol({ id: 185, description: 'SAMSHCSISPPRSQL12' });
    exports.Product.SamsHcsisPaidClaimsPPRSQL12 = exports.Product.addSymbol({ id: 186, description: 'SAMSHCSISPCPPRSQL12' });
    exports.Product.SAMSPPRSQL09 = exports.Product.addSymbol({ id: 187, description: 'SAMSPPRSQL09' });
    exports.Product.SamsAdminPPRSQL09 = exports.Product.addSymbol({ id: 188, description: 'SAMSAdminPPRSQL09' });
    exports.Product.OmniaDesignerPPRSQL09 = exports.Product.addSymbol({ id: 189, description: 'OmniaDesignerPPRSQL09' });
    exports.Product.OmniaAnalyzerPPRSQL09 = exports.Product.addSymbol({ id: 190, description: 'OmniaAnalyzerPPRSQL09' });
    exports.Product.SamsImportExportPPRSQL09 = exports.Product.addSymbol({ id: 191, description: 'SAMSIEPPRSQL09' });
    exports.Product.SamsScanPPRSQL09 = exports.Product.addSymbol({ id: 192, description: 'SAMSScanPPRSQL09' });
    exports.Product.OmniaInterviewerPPRSQL09 = exports.Product.addSymbol({ id: 193, description: 'OmniaInterviewerPPRSQL09' });
    exports.Product.NysofaReporterPPRSQL09 = exports.Product.addSymbol({ id: 194, description: 'NYSOFAReporterPPRSQL09' });
    exports.Product.CdaReporterPPRSQL09 = exports.Product.addSymbol({ id: 195, description: 'CDAReporterUsersPPRSQL09' });
    exports.Product.MsspReporterPPRSQL09 = exports.Product.addSymbol({ id: 196, description: 'MSSPReporterPPRSQL09' });
    exports.Product.CaCmsBillerPPRSQL09 = exports.Product.addSymbol({ id: 197, description: 'CACMSBillerPPRSQL09' });
    exports.Product.BeaconUsersPPRSQL09 = exports.Product.addSymbol({ id: 198, description: 'BeaconUsersPPRSQL09' });
    exports.Product.NapisSrtPPRSQL09 = exports.Product.addSymbol({ id: 199, description: 'NAPISSRTSAMSPPRSQL09' });
    exports.Product.SamsHcsisPPRSQL09 = exports.Product.addSymbol({ id: 200, description: 'SAMSHCSISPPRSQL09' });
    exports.Product.SamsHcsisPaidClaimsPPRSQL09 = exports.Product.addSymbol({ id: 201, description: 'SAMSHCSISPCPPRSQL09' });
    exports.Product.CaregiverDirectIntegration = exports.Product.addSymbol({ id: 202, description: 'Caregiver Direct Integration' });
    exports.Product.HarmonyFramework = exports.Product.addSymbol({ id: 203, description: 'Harmony Framework' });
    exports.Product.resolveSymbols();
});

define('security/module',["require", "exports", 'security/enums', 'core/util'], function (require, exports, enums, util) {
    function getCrudOperation(entity) {
        switch (entity.entityAspect.entityState) {
            case breeze.EntityState.Added:
                return security.CrudOperation.Create;
            case breeze.EntityState.Modified:
            case breeze.EntityState.Unchanged:
                return entity['IsNew'] && entity['IsNew']() ? security.CrudOperation.Create : security.CrudOperation.Update;
            case breeze.EntityState.Deleted:
                return security.CrudOperation.Delete;
            default:
                throw new Error('Unable to translate entity state \'' + entity.entityAspect.entityState.getName() + '\' to a crud operation.');
        }
    }
    function getScreenDesignHeaders(pageName) {
        pageName = pageName.toLowerCase();
        return util.Arrays.first(User.Current.Role.Role.GroupPackages, function (gp) { return equalsIgnoreCase(gp.ConfigPackage.ConfigPackageType.PackageTypeName, pageName); }).ConfigPackage.ScreenDesignConfigPackages.filter(function (s) { return s.Restricted == false && s.IsReadOnly == false; }).map(function (sdcp) { return sdcp.SCREENDESIGN; }).sort(function (a, b) { return util.stringComparisonOrdinalIgnoreCase(a.SCREENDESIGNNAME, b.SCREENDESIGNNAME); });
    }
    var fieldControls = {}, pages = {};
    function canAccessPage(pageName) {
        pageName = pageName.toLowerCase();
        return User.Current.Role.Role.ROLEPAGEs.filter(function (rp) { return rp.Page && equalsIgnoreCase(rp.Page.PageName, pageName); }).length > 0;
    }
    function canDeletePage(pageName) {
        pageName = pageName.toLowerCase();
        var rolePage = User.Current.Role.Role.ROLEPAGEs.filter(function (rp) { return rp.Page && equalsIgnoreCase(rp.Page.PageName, pageName); })[0];
        if (!rolePage) {
            return false;
        }
        return rolePage.Delete;
    }
    function getPage(pageName) {
        pageName = pageName.toLowerCase();
        return pages[pageName] || (pages[pageName] = util.Arrays.selectMany(User.Current.Role.Role.Group.Chapters, function (c) { return c.Pages; }).filter(function (p) { return equalsIgnoreCase(p.PageName, pageName); })[0]);
    }
    function getChapterLabel(pageName) {
        return getPage(pageName).Chapter.Label;
    }
    function getPageLabel(pageName) {
        return getPage(pageName).Label;
    }
    function getFieldControlByDBFieldName(pageName, dbFieldName) {
        pageName = pageName.toLowerCase();
        dbFieldName = dbFieldName.toLowerCase();
        if (fieldControls[pageName])
            return fieldControls[pageName][dbFieldName];
        fieldControls[pageName] = {};
        getPage(pageName).PageControls.forEach(function (pc) { return pc.Sections.forEach(function (s) { return s.FieldControls.forEach(function (fc) { return fieldControls[pageName][fc.DBFieldName.toLowerCase()] = fc; }); }); });
        return getFieldControlByDBFieldName(pageName, dbFieldName);
    }
    function getFieldLabel(pageName, dbFieldName) {
        return getFieldControlByDBFieldName(pageName, dbFieldName).Label;
    }
    function getFieldControlType(pageName, dbFieldName) {
        return getFieldControlByDBFieldName(pageName, dbFieldName).FieldControlType.Control;
    }
    function getFieldVisible(pageName, dbFieldName) {
        return getFieldControlByDBFieldName(pageName, dbFieldName).Visible;
    }
    function getFieldRequired(pageName, dbFieldName) {
        var field = getFieldControlByDBFieldName(pageName, dbFieldName);
        return field.SystemRequired || field.UserRequired;
    }
    function getFieldReadOnly(pageName, dbFieldName, entity) {
        var readOnly = getFieldControlByDBFieldName(pageName, dbFieldName).ReadOnly;
        return readOnly === FieldReadOnly.Always || readOnly === FieldReadOnly.OnAdd && entity.entityAspect.entityState.isAdded() || readOnly === FieldReadOnly.OnEdit && entity.entityAspect.entityState.isUnchangedOrModified();
    }
    var FieldControlPropertyName = {
        EnableSpellChecker: 'EnableSpellChecker',
        LookupIDDesc: 'LookupIDDesc',
        DefaultValue: 'DefaultValue',
        MaxLength: 'MaxLength',
        DefaultCriteria: 'DefaultCriteria',
        Rows: 'Rows',
        Columns: 'Columns',
        Value: 'Value',
        MinValue: 'MinValue',
        MaximumLength: 'MaximumLength',
        LookupType: 'LookupType',
        SearchType: 'SearchType',
        ReturnColumn: 'ReturnColumn',
        HasChainedParent: 'HasChainedParent',
        ValueSource: 'ValueSource',
        TableName: 'TableName',
        TableFieldName: 'TableFieldName',
        FilterLookupByValue: 'FilterLookupByValue',
        HideFromSolution: 'HideFromSolution',
        halignment: 'halignment',
        ShowDetail: 'ShowDetail',
        DisplayColumn: 'DisplayColumn',
        DynamicTriggerFieldValue: 'DynamicTriggerFieldValue',
        AssessmentType: 'AssessmentType',
        DisplayClearButton: 'DisplayClearButton',
        ChapterAndPageName: 'ChapterAndPageName',
        PlaceType: 'PlaceType',
        PlaceSection: 'PlaceSection',
        PlaceField: 'PlaceField',
        ToolTipField: 'ToolTipField',
        Axis: 'Axis',
        Type: 'Type',
        CommentHeight: 'CommentHeight',
        ShowDetailChapterAndPageNamePCLabel: 'ShowDetailChapterAndPageNamePCLabel',
        PopulateInPeopleSearch: 'PopulateInPeopleSearch',
        MaxValue: 'MaxValue',
        OperateMode: 'OperateMode',
        Alphabetized: 'Alphabetized',
        Ordered: 'Ordered',
        AllowFutureDate: 'AllowFutureDate',
        ContactType: 'ContactType',
        RestrictToFundCode: 'RestrictToFundCode',
        DiagNumber: 'DiagNumber',
        DisableInvoke: 'DisableInvoke',
        DisplayText: 'DisplayText',
        URL: 'URL',
        EnableOverride: 'EnableOverride',
        AllServiceCodes: 'AllServiceCodes',
        PositiveCurrencyOnly: 'PositiveCurrencyOnly',
        CommentWidth: 'CommentWidth',
        DisplayDescription: 'DisplayDescription',
        EnableAuthAllowed: 'EnableAuthAllowed',
        EmptyDate: 'EmptyDate',
        SearchByType: 'SearchByType',
        MapAddressFields: 'MapAddressFields',
        ExcludeProvider: 'ExcludeProvider',
        TableToUpdate: 'TableToUpdate',
        ProviderType: 'ProviderType',
        RadioButtonListItem: 'RadioButtonListItem',
        ValueType: 'ValueType',
        DisplayType: 'DisplayType',
        StoreClientSideControlID: 'StoreClientSideControlID',
        FosterParent: 'FosterParent',
        DisableFundCodeSecurity: 'DisableFundCodeSecurity',
        PageName: 'PageName',
        FieldControlType: 'FieldControlType',
        ShowAPSAgencyWorkersOnly: 'ShowAPSAgencyWorkersOnly',
        ShowCalculateButton: 'ShowCalculateButton',
        EmptyDateProp: 'EmptyDateProp',
        EnableExcludeAuthRequired: 'EnableExcludeAuthRequired',
        AutoPostBack: 'AutoPostBack',
        FundCode: 'FundCode',
        DisableAdd: 'DisableAdd',
        MaxLen: 'MaxLen',
        ProvidersForClaim: 'ProvidersForClaim',
        State: 'State',
        FetchOriginal: 'FetchOriginal',
        ParentIsEnrollment: 'ParentIsEnrollment',
        IsEnabled: 'IsEnabled',
        DisplayHyperlink: 'DisplayHyperlink',
        DropDownItem: 'DropDownItem',
        Address2: 'Address2',
        PayerID: 'PayerID',
        TargetWindow: 'TargetWindow',
        City: 'City',
        HRefText: 'HRefText',
        ShowAvailable: 'ShowAvailable',
        UseFIPSFilter: 'UseFIPSFilter',
        RenderDetails: 'RenderDetails',
        ReturnLinkedISOCodes: 'ReturnLinkedISOCodes',
        Address1: 'Address1',
        Zipcode: 'Zipcode',
        SendAutoPostBack: 'SendAutoPostBack',
        ListDirection: 'ListDirection',
        ReturnSubObjectCode: 'ReturnSubObjectCode',
        ShowCharacterCount: 'ShowCharacterCount',
        'Default Criteria': 'Default Criteria',
        Disabled: 'Disabled',
        ControlHeight: 'ControlHeight',
        MapSearch: 'MapSearch',
        FundCodeLookupType: 'FundCodeLookupType',
        DestinationLabel: 'DestinationLabel',
        'Non Authorized': 'Non Authorized',
        ReturnPayersWithISOCodes: 'ReturnPayersWithISOCodes',
        AllowOnlyNumeric: 'AllowOnlyNumeric',
        UpdateOnProgramChanged: 'UpdateOnProgramChanged',
        DisableInitialFetch: 'DisableInitialFetch',
        ShowLinked: 'ShowLinked',
        ServiceTypeName: 'ServiceTypeName',
        Allow4DecimalPlaces: 'Allow4DecimalPlaces',
        ClearInvalidPageFlag: 'ClearInvalidPageFlag',
        ProvidersForServiceIDProvided: 'ProvidersForServiceIDProvided',
        SourceLabel: 'SourceLabel',
        ChainingEnabled: 'ChainingEnabled',
        ReturnPrimaryISOCodes: 'ReturnPrimaryISOCodes',
        DisableTabStop: 'DisableTabStop',
        SingleSelect: 'SingleSelect',
        ProvidersWithAddress: 'ProvidersWithAddress',
        ShowDetails: 'ShowDetails',
        DisplayBlankValue: 'DisplayBlankValue',
        ForISOBudget: 'ForISOBudget',
        AssessmentInquiryType: 'AssessmentInquiryType',
        ShowBlankValue: 'ShowBlankValue',
        ReturnValue: 'ReturnValue',
        DisableEntityRequest: 'DisableEntityRequest',
        Authorized: 'Authorized',
        FilterByVendorID: 'FilterByVendorID',
        PlaceAddress: 'PlaceAddress',
        ReportDisplayName: 'ReportDisplayName',
        ReportID: 'ReportID',
        EnableRichText: 'EnableRichText',
        MultiSelectWidth: 'MultiSelectWidth',
        RichTextWidth: 'RichTextWidth',
        RichTextHeight: 'RichTextHeight',
    };
    var DefaultValue = {
        Today: '{Today}',
        Self: '{Self}',
        UserDefault: '{UserDefault}',
        ParentEntityID: '{ParentEntityID}',
        TimeNow: '{TimeNow}',
        ChapterEntityID: '{ChapterEntityID}',
        DefaultProvider: '{DefaultProvider}',
        ParentDefault: '{ParentDefault}',
        SingleFC: '{SingleFC}'
    };
    var UserRole = {
        User: 1,
        Admin: 2,
        TwoPartHarmony: 3
    };
    var AccessLevel = {
        Delete: 1,
        Edit: 2,
        View: 3,
        Add: 4,
        All: 5
    };
    var RoleAccessLevel = {
        All: 1,
        Office: 2,
        Program: 3,
        Unit: 4,
        Worker: 5
    };
    var AccessLevelType = {
        Group: 1,
        Page: 2,
        Role: 3
    };
    var FieldReadOnly = {
        Never: 0,
        OnAdd: 1,
        OnEdit: 2,
        Always: 3,
    };
    var FieldOperate = {
        Append: 0,
        Edit: 1
    };
    var AppendForNoteState = {
        Append: 0,
        Edit: 1,
        Disabled: 2
    };
    function getFieldControl(pageName, fieldControlPredicate) {
        var page = getPage(pageName), sections = util.Arrays.selectMany(page.PageControls, function (pc) { return pc.Sections; }), fieldControls = util.Arrays.selectMany(sections, function (s) { return s.FieldControls; }), fieldControl = util.Arrays.firstOrDefault(fieldControls, fieldControlPredicate);
        return fieldControl;
    }
    function getFieldControlPropertyValueInternal(pageName, fieldControlPredicate, propertyName) {
        var fieldControl = getFieldControl(pageName, fieldControlPredicate), property = util.Arrays.firstOrDefault(fieldControl.FieldControlProperties, function (p) { return equalsIgnoreCase(p.PropertyName, propertyName); });
        if (property)
            return property.PropertyValue;
        return null;
    }
    function getFieldControlPropertyValueByClientSideControlID(pageName, clientSideControlID, propertyName) {
        return getFieldControlPropertyValueInternal(pageName, function (fc) { return equalsIgnoreCase(fc.ClientSideControlID, clientSideControlID); }, propertyName);
    }
    function getFieldControlPropertyValue(pageName, dbFieldName, propertyName) {
        return getFieldControlPropertyValueInternal(pageName, function (fc) { return equalsIgnoreCase(fc.DBFieldName, dbFieldName); }, propertyName);
    }
    function getIsFieldRequired(pageName, dbFieldName) {
        var fieldControl = getFieldControl(pageName, function (fc) { return equalsIgnoreCase(fc.DBFieldName, dbFieldName); });
        return fieldControl.SystemRequired || fieldControl.UserRequired;
    }
    function likeComplete(status) {
        return util.Arrays.any(security.completeStatuses, function (s) { return equalsIgnoreCase(status, s); });
    }
    function likeOpen(openClose) {
        return util.Arrays.any(security.openDispositions, function (disposition) { return equalsIgnoreCase(openClose.DISPOSITION(), disposition); });
    }
    function likeOpenEnrollments(enrollment) {
        return util.Arrays.any(security.openEDispositions, function (edisposition) { return equalsIgnoreCase(enrollment.EDISPOSITION(), edisposition); });
    }
    function getConsumerFundCodes(consumer) {
        if (!consumer.OPENCLOSEs)
            return [];
        return consumer.OPENCLOSEs().filter(likeOpen).map(function (oc) { return oc.FUNDCODE(); }).filter(function (oc, index, arr) { return arr.indexOf(oc) === index; }).sort(util.stringComparisonOrdinalIgnoreCase);
    }
    function getOpenCloseId(consumer, fundCode) {
        var openClose = consumer.OPENCLOSEs().filter(likeOpen).filter(function (oc) { return equalsIgnoreCase(oc.FUNDCODE(), fundCode); })[0];
        if (openClose) {
            return openClose.OPENID();
        }
        return null;
    }
    function getEnrollmentOfOpenCloseForVendor(consumer, openCloseId, vendorId) {
        if (openCloseId == null || vendorId == null) {
            return null;
        }
        var enrollment;
        var openClose = consumer.OPENCLOSEs().filter(likeOpen).filter(function (oc) { return oc.OPENID() == openCloseId; })[0];
        if (openClose) {
            var oc = openClose;
            enrollment = oc.ENROLLMENTS().filter(likeOpenEnrollments).filter(function (e) { return e.VENDORID() == vendorId; })[0];
        }
        if (enrollment) {
            return enrollment;
        }
        return null;
    }
    var Permission = {
        Administrator: 'Administrator',
        Supervisor: 'Supervisor',
        Approver: 'Approver',
        SsnUnmask: 'SSN Unmask',
    };
    function hasPermission(permission) {
        return util.Arrays.any(User.Current.Role.Role.RolePermissions, function (rp) { return equalsIgnoreCase(permission, rp['Permission']['Permission1']); });
    }
    function initialize() {
    }
    exports.initialize = initialize;
    window['security'] = {
        getScreenDesignHeaders: getScreenDesignHeaders,
        canAccessPage: canAccessPage,
        canDeletePage: canDeletePage,
        getChapterLabel: getChapterLabel,
        getPageLabel: getPageLabel,
        getFieldControlType: getFieldControlType,
        getFieldLabel: getFieldLabel,
        getFieldVisible: getFieldVisible,
        getFieldRequired: getFieldRequired,
        getFieldReadOnly: getFieldReadOnly,
        FieldControlPropertyName: FieldControlPropertyName,
        getFieldControlPropertyValueByClientSideControlID: getFieldControlPropertyValueByClientSideControlID,
        getFieldControlPropertyValue: getFieldControlPropertyValue,
        getConsumerFundCodes: getConsumerFundCodes,
        getOpenCloseId: getOpenCloseId,
        getEnrollmentOfOpenCloseForVendor: getEnrollmentOfOpenCloseForVendor,
        getIsFieldRequired: getIsFieldRequired,
        DefaultValue: DefaultValue,
        Permission: Permission,
        hasPermission: hasPermission,
        likeComplete: likeComplete
    };
    security.CrudOperation = enums.CrudOperation;
});

define('core/flagr',["require", "exports", 'core/constants'], function (require, exports, constants) {
    var flagrNames = [
        'Mobile Assessments CF Builder',
    ];
    function initialize() {
        return getSetFlagr().then(function (success) {
            if (success === true) {
                return loadAppFlagrSettings().then(function () {
                    return true;
                }).fail(function () {
                    return false;
                });
            }
            else if (success === false) {
                return false;
            }
        });
    }
    exports.initialize = initialize;
    function getSetFlagr() {
        var deferred = Q.defer();
        $.post(constants.services.serviceBaseUrl + 'flagr/SetFlagrFlagStatus', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
        }).then(function (response) {
            deferred.resolve(response);
        }).fail(function () {
            deferred.reject(false);
        });
        return deferred.promise;
    }
    function getFlagrByName(flagName) {
        var deferred = Q.defer();
        $.get(constants.services.serviceBaseUrl + 'flagr/GetFlagrFlagCacheStatus' + '?flagName=' + flagName, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        }).then(function (response) {
            deferred.resolve(response);
        }).fail(function (x) {
            deferred.reject(false);
        });
        return deferred.promise;
    }
    function initializeAppFlagrSettings() {
        app.flagrSettings = {
            IsCFBuilderEnabled: false
        };
    }
    function loadAppFlagrSettings() {
        initializeAppFlagrSettings();
        var flagrPromises = flagrNames.map(function (name) {
            return getFlagrByName(name);
        });
        return Q.all(flagrPromises).then(function (result) {
            app.flagrSettings.IsCFBuilderEnabled = result[0];
        });
    }
});

define('bootstrapper',["require", "exports", 'core/util', 'security/module', 'security/login', 'durandal/app', 'durandal/system', 'durandal/binder', 'plugins/dialog', 'plugins/router', 'core/constants', 'core/logger', 'core/flagr', 'core/durability', 'core/viewmodels', 'bindings/bindings', 'core/messageBox', 'unsupportedBrowser'], function (require, exports, util, securityModule, login, durandalApp, durandalSystem, durandalBinder, durandalDialog, router, constants, logger, flagr, durability, viewModels, bindings, messageBox, browserCompat) {
    window['typeaheadThreshold'] = 100;
    util.ensureUrlHasTrailingBackslash();
    securityModule.initialize();
    app.instanceId = breeze.core.getUuid();
    app.activationCancelledException = new Error('Activation Cancelled.');
    $.resize.delay = 50;
    FastClick.attach(document.body);
    Q.longStackSupport = false;
    logger.initialize();
    durandalSystem.debug(true);
    durandalApp.title = 'Assessments';
    durandalApp.configurePlugins({
        router: true,
        dialog: true,
        widget: true
    });
    durandalBinder.binding = function (data, view, instruction) {
        var $view = $(view);
        if (view.hasAttribute('data-preprocess') && equalsIgnoreCase(view.getAttribute('data-preprocess'), 'true')) {
            var template = $view.html().split('&lt;').join('<').split('&gt;').join('>').split('&amp;').join('&');
            var html = $.jqote(template, data);
            $view.html(html);
        }
        $view.i18n();
    };
    durability.initialize();
    router.updateDocumentTitle = function (instance, instruction) {
        var title;
        if (instance.getTitle)
            title = instance.getTitle();
        if (!title && instruction.config.title)
            title = instruction.config.title;
        if (title) {
            if (durandalApp.title) {
                document.title = title + " | " + durandalApp.title;
            }
            else {
                document.title = title;
            }
        }
        else if (durandalApp.title) {
            document.title = durandalApp.title;
        }
    };
    jQuery.fn.putCursorAtEnd = function () {
        return this.each(function () {
            $(this).focus();
            if (this.setSelectionRange) {
                var len = $(this).val().length * 2;
                this.setSelectionRange(len, len);
            }
            else {
                $(this).val($(this).val());
            }
            this.scrollTop = 999999;
        });
    };
    bindings.initialize();
    function checkApplicationCacheNeedsSwap() {
        if (!document.body.parentNode.hasAttribute('manifest'))
            return;
        if (!window.applicationCache || window.applicationCache.status != window.applicationCache.UPDATEREADY)
            return false;
        try {
            window.applicationCache.swapCache();
        }
        catch (e) {
        }
        messageBox.show('applicationUpdateReady.title', 'applicationUpdateReady.message', messageBox.buttons.okOnly).then(function (value) {
            app.isOffline(false);
            localforage.setItem('isOffline', false);
            window.location.reload();
        });
        return true;
    }
    function registerServiceWorker() {
        if (!document.body.parentNode.hasAttribute('manifest'))
            return;
        var navigator;
        navigator = window['navigator'];
        navigator.serviceWorker.register('serviceworker').catch(function (err) {
            return console.error('Service worker error ', err);
        });
        var refreshing = false;
        navigator.serviceWorker.addEventListener('controllerchange', function () {
            if (!refreshing) {
                messageBox.show('applicationUpdateReady.title', 'applicationUpdateReady.message', messageBox.buttons.okOnly).then(function (value) {
                    app.isOffline(false);
                    localforage.setItem('isOffline', false);
                    window.location.reload();
                    refreshing = true;
                });
            }
        });
    }
    User = { Current: null, IsLoggedIn: false, Settings: null };
    AuthorizationHeader = { Current: null };
    app.busyIndicator = new viewModels.BusyIndicator();
    ko.applyBindings(app.busyIndicator, $('.loader-overlay')[0]);
    ko.applyBindings(app.busyIndicator, $('.loader-content')[0]);
    app.statusBar = new viewModels.StatusBar();
    app.notifier = new viewModels.Notifier();
    app.connection = ko.observable(constants.connection.unknown);
    app.isOffline = ko.observable(false);
    app.modal = null;
    app.tabletOrPhone = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    SystemSettings = null;
    function startDurandalApp() {
        durandalApp.start().then(function () {
            return flagr.initialize();
        }).then(function () {
            if (!browserCompat.isBrowserAllowed()) {
                durandalApp.setRoot('unsupportedBrowser');
                return;
            }
            if (app.isLogoutRedirection) {
                durandalApp.setRoot('security/ui/logoutPage');
                return;
            }
            if (app.isSSOLoginError) {
                durandalApp.setRoot('security/ui/ssoLoginError');
                return;
            }
            if (!('serviceWorker' in window.navigator) && window.applicationCache && checkApplicationCacheNeedsSwap())
                return;
            if ('serviceWorker' in window.navigator) {
                registerServiceWorker();
            }
            else if (window.applicationCache) {
                window.applicationCache.addEventListener('updateready', function (event) { return checkApplicationCacheNeedsSwap(); }, false);
            }
            if (app.webIntake) {
                if (browserCompat.browser() === 'ie') {
                    messageBox.show('common.warning', 'common.ieUnSupportedbrowser', messageBox.buttons.okOnly);
                }
                login.attemptWebIntakeLogin().done();
                return;
            }
            if (app.CfWebIntake) {
                if (browserCompat.browser() === 'ie') {
                    messageBox.show('common.warning', 'common.ieUnSupportedbrowser', messageBox.buttons.okOnly);
                }
                login.attemptCfWebIntakeLogin().done();
                return;
            }
            if (app.consumerModule) {
                AuthorizationHeader.Current = app.consumerModuleAuthorization;
                login.attemptConsumerModuleLogin().fail(function (reason) {
                    durandalApp.setRoot('security/ui/login');
                }).done();
                return;
            }
            if (app.IsSSOEnabled) {
                durandalApp.setRoot('security/ui/SSOLogin');
            }
            else {
                durandalApp.setRoot('security/ui/login');
            }
        });
    }
    function initializeStorage() {
        localforage.config({ name: 'Mobile Assessments' });
        return Q(localforage.getItem('app-version').then(function (version) {
            version = version || '0.0.0';
            localforage.setItem('app-version', app.shortVersion);
        }));
    }
    initializeStorage().done(startDurandalApp);
    $(document).off('focusin.harmony.modal').on('focusin.harmony.modal', function (e) {
        if (!app.modal)
            return;
        var dialog = durandalDialog.getDialog(app.modal);
        if (!dialog)
            return;
        var dialogHost = dialog['host'];
        if (!dialogHost)
            return;
        if (e.target === dialogHost || $.contains(dialogHost, e.target))
            return;
        if ($(e.target).hasClass('datepicker-dropdown'))
            return;
        var $dialogHost = $(dialogHost), defaultFocusTarget = $dialogHost.find('.autofocus').first();
        if (defaultFocusTarget.length === 0)
            defaultFocusTarget = $dialogHost;
        defaultFocusTarget.focus();
    });
    jQuery.fn.scrollParent = function () {
        var overflowRegex = /(auto|scroll)/, position = this.css("position"), excludeStaticParent = position === "absolute", scrollParent = this.parents().filter(function () {
            var parent = $(this);
            if (excludeStaticParent && parent.css("position") === "static") {
                return false;
            }
            return (overflowRegex).test(parent.css("overflow") + parent.css("overflow-y") + parent.css("overflow-x"));
        }).eq(0);
        return position === "fixed" || !scrollParent.length ? $(this[0].ownerDocument || document) : scrollParent;
    };
});


define('text!cfshell.html',[],function () { return '<div id="shell">\r\n    <div id="section-container" class="body" data-bind="router: { cacheViews: false }" style="width: 100%; padding-top: 0;"></div>\r\n</div>';});

define('cfshell',["require", "exports", 'plugins/router'], function (require, exports, durandalRouter) {
    var cfWebIntakeRouteConfig = [
        { route: 'form', title: $.i18n.t('common.template'), moduleId: 'custom_forms_widgets/complete_template/complete_template', nav: true, iconStyle: 'glyphicon-pro glyphicon-pro-globe' },
        { route: 'completeform', title: $.i18n.t('common.template'), moduleId: 'custom_forms_widgets/confirmation_template/cf_confirmation', nav: true, iconStyle: 'glyphicon-pro glyphicon-pro-globe' },
        { route: 'printform', title: $.i18n.t('common.template'), moduleId: 'custom_forms_widgets/print_template/print_cf_form', nav: true, iconStyle: 'glyphicon-pro glyphicon-pro-globe' }
    ];
    durandalRouter.map(cfWebIntakeRouteConfig).buildNavigationModel();
    durandalRouter.mapUnknownRoutes('custom_forms_widgets/complete_template/complete_template');
    durandalRouter.mapUnknownRoutes('custom_forms_widgets/confirmation_template/cf_confirmation');
    durandalRouter.mapUnknownRoutes('custom_forms_widgets/print_template/print_cf_form');
    durandalRouter.activate();
});


define('text!core/KeyboardShortcuts.html',[],function () { return '<div class="messageBox modal-content container keyboard-shortcuts">\r\n    <div class="modalBody">\r\n        <label for="search" class="watermark-md text-muted"\r\n               data-bind="visible: isNullOrEmpty(searchString())"\r\n               data-i18n="common.searchKeyboardShortcuts">\r\n        </label>\r\n        <div class="input-group">\r\n            <span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span>\r\n            <input type="text" id="search"\r\n                   data-bind="value: searchString, valueUpdate: \'input\'"\r\n                   class="form-control autofocus watermarked"\r\n                   autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n            <span class="input-group-btn">\r\n                <button class="btn btn-primary" type="button" data-bind="click: cancel">Close</button>\r\n            </span>\r\n        </div>\r\n\r\n        <div class="table-responsive" data-bind="visible: hasResults, style: { height: ($(window).height() * 0.85).toString() + \'px\' }">\r\n            <table class="table table-striped table-hover table-condensed">\r\n                <tbody>\r\n                    <!-- ko foreach: filteredCategories -->\r\n                        <tr>\r\n                            <td colspan="3">\r\n                                <h4 data-bind="text: name"></h4>\r\n                            </td>\r\n                        </tr>\r\n                        <!-- ko foreach: shortcuts -->\r\n                        <tr>\r\n                            <td data-bind="text: name"></td>\r\n                            <td data-bind="text: keys.replace(/([^,]) /, \'$1 then \')"></td>\r\n                            <td data-bind="text: description"></td>\r\n                        </tr>\r\n                        <!-- /ko -->\r\n                    <!-- /ko -->\r\n                </tbody>\r\n            </table>\r\n        </div>\r\n\r\n        <div data-bind="visible: showNoResultsMessage" class="h-margin-top-10px">\r\n            <span data-i18n="common.keyboardNoResults1"></span><em data-bind="text: searchString"></em><span data-i18n="common.keyboardNoResults2"></span>\r\n        </div>\r\n    </div>\r\n</div>';});

define('shell',["require", "exports", 'core/messageBox', 'plugins/router', 'security/login', 'core/keyboard', 'core/viewmodels', 'entities/api', 'core/util', 'entities/repo', 'core/logger', 'assessmentTracker/mobileAssessmentTracker', 'entities/sync', 'security/ssoSessionHandler'], function (require, exports, messageBox, durandalRouter, login, keyboard, viewmodels, entities, util, repo, logger, mobassesstrkr, entitySync, ssoHandler) {
    var routeConfigs = [
        { route: '', title: $.i18n.t('common.search'), moduleId: 'search/search', nav: true, iconStyle: 'glyphicon glyphicon-search' },
        { route: 'search', title: $.i18n.t('common.search'), moduleId: 'search/search', nav: false },
        { route: 'history', title: $.i18n.t('common.history'), moduleId: 'history/history', nav: true, iconStyle: 'glyphicon glyphicon-time' },
        { route: 'downloaded', title: $.i18n.t('common.downloaded'), moduleId: 'downloaded/downloaded', nav: true, iconStyle: 'glyphicon glyphicon-cloud-download' },
        { route: 'notifications', title: $.i18n.t('common.notifications'), moduleId: 'notifications/notifications', nav: true, iconStyle: 'glyphicon-pro glyphicon-pro-globe' },
    ];
    if (app.flagrSettings.IsCFBuilderEnabled) {
        routeConfigs.push({
            route: 'cfbuilder',
            title: $.i18n.t('common.cfbuilder'),
            moduleId: 'custom_forms_widgets/cfbuilder/cfbuilder',
            nav: true,
            iconStyle: 'glyphicon-pro glyphicon-pro-globe'
        });
        routeConfigs.push({
            route: 'cfbuilder/settings/custom-forms/new',
            title: $.i18n.t('common.edit'),
            moduleId: 'custom_forms_widgets/edit_template/edit_template',
            nav: false,
            iconStyle: 'glyphicon-pro glyphicon-pro-globe'
        });
    }
    durandalRouter.map(routeConfigs);
    if (!app.webIntake) {
        durandalRouter.on('router:navigation:processing router:navigation:mapUnknownRoutes').then(function (instance, instruction, router) {
            app.busyIndicator.setBusyLoading();
        });
    }
    durandalRouter.on('router:navigation:composition-complete router:navigation:cancelled').then(function (instance, instruction, router) {
        app.busyIndicator.setReady();
        if (instance === 'router:navigation:cancelled')
            return;
        var toFocus = $('#shell #section-container .autofocus:first:enabled');
        if (toFocus.length === 0) {
            toFocus = $('#shell #section-container .autofocus:first');
        }
        toFocus.focus();
    });
    durandalRouter.mapUnknownRoutes(function (instruction) {
        var info = entities.parseFragment(instruction.fragment), parentEntityManager = null, promise = Q.resolve(null), deferred = Q.defer(), newEntityConfig = {};
        durandalRouter.trigger('router:navigation:mapUnknownRoutes', instruction, durandalRouter);
        if ((info.action !== 0 /* Open */) && !durandalRouter['explicitNavigation']) {
            instruction.config.moduleId = 'core/fallback';
            return;
        }
        if (info.parentType) {
            promise = entities.getInstance(info.parentType.name, info.parentId).then(function (em) {
                parentEntityManager = em;
                newEntityConfig[entities.getEntityIdProperty(parentEntityManager.entity).name] = entities.getEntityId(parentEntityManager.entity);
            });
        }
        function connectParent(entityManager) {
            entityManager.parentEntityManager = parentEntityManager;
            if (parentEntityManager)
                entityManager.entity['ownerTitle'] = parentEntityManager.type.getTitle(parentEntityManager.entity);
            return entityManager;
        }
        switch (info.action) {
            case 1 /* New */:
                promise = promise.then(function () { return entities.createInstance(info.type.name, newEntityConfig); }).then(connectParent).then(function (entityManager) {
                    instruction.config.moduleId = entityManager.type.adderModuleId || entityManager.type.moduleId;
                    instruction.params = [entityManager];
                    if (!entityManager.type.adderModuleId) {
                        entityManager.notifyOpenedForEdit(false);
                    }
                });
                break;
            case 2 /* Copy */:
                promise = promise.then(function () { return Q.all([entities.getInstance(info.type.name, info.id).then(connectParent), entities.createInstance(info.type.name, newEntityConfig).then(connectParent)]); }).then(function (entityManagers) {
                    var sourceEntityManager = entityManagers[0], destinationEntityManager = entityManagers[1];
                    if (sourceEntityManager.type.copierModuleId) {
                        instruction.config.moduleId = sourceEntityManager.type.copierModuleId;
                        instruction.params = [sourceEntityManager, destinationEntityManager];
                    }
                    else if (sourceEntityManager.type.copy) {
                        return sourceEntityManager.type.copy(sourceEntityManager, destinationEntityManager).then(function () {
                            instruction.config.moduleId = sourceEntityManager.type.moduleId;
                            instruction.params = [destinationEntityManager];
                            destinationEntityManager.notifyOpenedForEdit(false);
                        });
                    }
                    else {
                        throw new Error('the instruction matched the "copy" pattern but the entity type has no copierModule or copy function.  instruction=' + instruction);
                    }
                });
                break;
            case 3 /* Print */:
                instruction.config.moduleId = 'reporting/Print';
                instruction.params = [info.type, info.id];
                return;
            case 0 /* Open */:
                promise = promise.then(function () { return entities.getInstance(info.type.name, info.id); }).then(connectParent).then(function (entityManager) {
                    if (!entityManager.canUserRead()) {
                        throw entities.getInstanceExceptions.entityNotAuthorized;
                    }
                    instruction.config.moduleId = entityManager.type.moduleId;
                    instruction.params = [entityManager];
                    entityManager.notifyOpenedForEdit(true);
                });
                break;
        }
        promise.then(function () { return deferred.resolve(null); }).fail(function (reason) {
            if (reason === app.activationCancelledException) {
                deferred.reject(reason);
                return;
            }
            var message = entities.getInstanceExceptionMessage(reason);
            if (message === null) {
                deferred.reject(reason);
                return Q.reject(reason);
            }
            messageBox.show('common.navigationFailed', 'common.navigationFailedMessageFormat', messageBox.buttons.okOnly, [message]);
            instruction.config.moduleId = 'core/fallback';
            instruction.params = [message, reason];
            deferred.resolve(null);
        }).done();
        return deferred.promise;
    });
    durandalRouter.buildNavigationModel();
    durandalRouter.activate();
    exports.router = durandalRouter;
    exports.statusBar = app.statusBar;
    exports.notifier = app.notifier;
    function logout() {
        messageBox.show('security.logoutTitle', 'security.logoutMessage', messageBox.buttons.yesCancel).then(function (result) {
            if (result !== messageBox.yes)
                return;
            login.logout();
        });
    }
    exports.logout = logout;
    function toggleOffline() {
        var messageBoxTitle = app.isOffline() ? 'common.goOnline' : 'common.goOffline';
        var messageBoxText = app.isOffline() ? 'common.goOnlineMessage' : 'common.goOfflineMessage';
        if (app.isOffline()) {
            if (app.IsSSOEnabled) {
                login.checkIfSessionActive().then(function (isSessionActive) {
                    if (!isSessionActive) {
                        messageBox.show('security.sessionExpiredTitle', 'security.sessionAlreadyExpired', messageBox.buttons.okOnly).then(function (result) {
                            login.redirectToLogin();
                        }).fail(function (reason) {
                            if (util.isConnectionFailure(reason)) {
                                app.isOffline(true);
                                logger.logUserAction('The users offline mode retained due to connection failure.');
                                return;
                            }
                            return Q.reject(reason);
                        });
                    }
                    else {
                        offlineToOnlineMode(messageBoxTitle, messageBoxText);
                    }
                });
            }
            else {
                offlineToOnlineMode(messageBoxTitle, messageBoxText);
            }
        }
        else {
            messageBox.show(messageBoxTitle, messageBoxText, messageBox.buttons.yesCancel).then(function (button) {
                if (button !== messageBox.yes) {
                    return;
                }
                entitySync.sync();
                app.isOffline(true);
                logger.logUserAction('The user has switched to Offline mode.');
                localforage.setItem('isOffline', app.isOffline());
            });
        }
    }
    exports.toggleOffline = toggleOffline;
    function clearData() {
        messageBox.show('common.clearData', 'common.clearDataMessage', messageBox.buttons.yesCancel).then(function (button) {
            if (button !== messageBox.yes)
                return;
            app.busyIndicator.setBusy('Clearing data...');
            return Q(localforage.clear()).then(function () { return messageBox.show('common.dataCleared', 'common.dataClearedMessage', [$.i18n.t('common.restart'), $.i18n.t('common.close')]); }).then(function (button) {
                if (button === $.i18n.t('common.restart')) {
                    logger.logUserAction('The user has forced a clear of his local storage.');
                    location.assign(util.getOrigin(window.location.href) + location.pathname);
                    return;
                }
                location.assign('about:blank');
            });
        }).done();
    }
    exports.clearData = clearData;
    function toggleDebugInfos() {
        localforage.getItem('user-actions-history').then(function (currentData) {
            messageBox.show('common.developerTitle', 'common.developerInfos', messageBox.buttons.okOnly, ['<pre style="max-height: ' + ($(window).height() / 3) + 'px; overflow: auto; display: block;">' + currentData + '</pre>']);
        });
    }
    exports.toggleDebugInfos = toggleDebugInfos;
    function OfflineAssessmentTrackerStartMenu() {
        return mobassesstrkr.getStartupAssessmentTrackerMenu().then(function (value) {
            return value;
        });
    }
    exports.OfflineAssessmentTrackerStartMenu = OfflineAssessmentTrackerStartMenu;
    function getStartMenu() {
        OfflineAssessmentTrackerStartMenu().then(function (data) {
            return data;
        }).then(function (data) {
            $('#offlineAssessmentTrackerLink').text(data);
        });
    }
    exports.getStartMenu = getStartMenu;
    function OfflineAssessmentTrackerClickMenu() {
        return mobassesstrkr.getClickAssessmentTrackerMenu().then(function (value) {
            return value;
        });
    }
    exports.OfflineAssessmentTrackerClickMenu = OfflineAssessmentTrackerClickMenu;
    function getClickMenu() {
        OfflineAssessmentTrackerClickMenu().then(function (data) {
            return data;
        }).then(function (data) {
            $('#offlineAssessmentTrackerLink').text(data);
        });
    }
    exports.getClickMenu = getClickMenu;
    function offlineToOnlineMode(messageBoxTitle, messageBoxText) {
        if (exports.notifier.count() === 0) {
            goOnline();
            logger.logUserAction('The user has switched to Online mode.');
            return;
        }
        messageBox.show(messageBoxTitle, messageBoxText, messageBox.buttons.yesNoCancel, [exports.notifier.count().toString()]).then(function (button) {
            if (button === messageBox.cancel) {
                logger.logUserAction('The user has switched to Online mode and cancelled the synchronization.');
                return;
            }
            if (button === messageBox.yes) {
                repo.saveAll();
                goOnline();
                logger.logUserAction('The user has switched to Online mode and synchronized local changes to server.');
                return;
            }
            if (button === messageBox.no) {
                logger.logUserAction('The user has switched to Online mode without synchronizing with the server.');
                goOnline();
            }
        });
        return;
    }
    function goOnline() {
        app.isOffline(false);
        localforage.setItem('isOffline', false);
        entitySync.sync();
        exports.router.navigate('/');
        if (app.IsSSOEnabled) {
            ssoHandler.resetCountdown();
        }
    }
    exports.showShortcuts = keyboard.showShortcuts;
    exports.commands = new viewmodels.CommandCollection();
    exports.commands.add('showShortcuts', new viewmodels.Command(keyboard.showShortcuts));
    exports.commands.add('navigateBack', new viewmodels.Command(durandalRouter.navigateBack));
    exports.commands.add('toggleDebugInfos', new viewmodels.Command(function () { return toggleDebugInfos(); }));
});

define('core/keyboard',["require", "exports", 'core/KeyboardShortcuts', 'durandal/app', 'shell'], function (require, exports, KeyboardShortcuts, durandalApp, shell) {
    function showShortcuts() {
        var vm = new KeyboardShortcuts();
        return Q(durandalApp.showDialog(vm));
    }
    exports.showShortcuts = showShortcuts;
    exports.categories = [
        {
            name: 'Site-wide shortcuts',
            shortcuts: [
                {
                    name: 'This Screen',
                    keys: 'ctrl+k',
                    description: 'Open the keyboard shortcuts page.',
                    command: 'showShortcuts'
                },
                {
                    name: 'Go Back',
                    keys: 'ctrl+shift+b',
                    description: 'Navigate to the previous page.',
                    command: 'navigateBack'
                },
                {
                    name: 'Goto Search',
                    keys: 'ctrl+shift+s',
                    description: 'Navigate to the search page.',
                    href: '#'
                },
                {
                    name: 'Goto History',
                    keys: 'ctrl+shift+h',
                    description: 'Navigate to the history page.',
                    href: '#history'
                },
                {
                    name: 'Goto Downloaded',
                    keys: 'ctrl+shift+d',
                    description: 'Navigate to the dowloaded consumers page.',
                    href: '#downloaded'
                },
                {
                    name: 'Goto Notifications',
                    keys: 'ctrl+shift+n',
                    description: 'Navigate to the notifications page.',
                    href: '#notifications'
                },
                {
                    name: 'Debug informations',
                    keys: 'ctrl+shift+z',
                    description: 'Display debug informations for developers.',
                    command: 'toggleDebugInfos'
                }
            ]
        },
        {
            name: 'Dialogs',
            shortcuts: [
                {
                    name: 'Submit',
                    keys: 'enter',
                    description: 'Submit the dialog.',
                    command: 'submit'
                },
                {
                    name: 'Cancel',
                    keys: 'esc',
                    description: 'Cancel the dialog.',
                    command: 'cancel'
                },
            ]
        },
        {
            name: 'Forms',
            shortcuts: [
                {
                    name: 'Save',
                    keys: 'ctrl+s',
                    description: 'Save the record.',
                    command: 'save'
                },
                {
                    name: 'Close',
                    keys: 'ctrl+e',
                    description: 'Close the record.',
                    command: 'close'
                },
                {
                    name: 'Revert',
                    keys: 'ctrl+u',
                    description: 'Revert all unsaved changes.',
                    command: 'revert'
                },
            ]
        },
        {
            name: 'Assessment',
            shortcuts: [
                {
                    name: 'Find Question',
                    keys: 'ctrl+f',
                    description: 'Focus the find question text box.',
                    command: 'focusFindQuestion'
                },
                {
                    name: 'Goto Section List',
                    keys: 'ctrl+l',
                    description: 'Focus the assessment section/subsection navigation list.',
                    command: 'focusSectionList'
                },
                {
                    name: 'Next',
                    keys: 'tab, down',
                    description: 'Navigate to the next question.'
                },
                {
                    name: 'Previous',
                    keys: 'shift+tab, up',
                    description: 'Navigate to the previous question.'
                },
                {
                    name: 'Go Back',
                    keys: 'ctrl+left',
                    description: 'Navigate backwards in the question history.',
                    command: 'goBack'
                },
                {
                    name: 'Go Forward',
                    keys: 'ctrl+right',
                    description: 'Navigate forward in the question history.',
                    command: 'goForward'
                },
                {
                    name: 'Next Unanswered',
                    keys: 'shift+down',
                    description: 'Navigate to the next unanswered question.',
                    command: 'nextUnansweredQuestion'
                },
                {
                    name: 'Previous Unanswered',
                    keys: 'shift+up',
                    description: 'Navigate to the previous unanswered question.',
                    command: 'previousUnansweredQuestion'
                },
                {
                    name: 'Next Required',
                    keys: 'ctrl+down',
                    description: 'Navigate to the next required question.',
                    command: 'nextRequiredQuestion'
                },
                {
                    name: 'Previous Required',
                    keys: 'ctrl+up',
                    description: 'Navigate to the previous required question.',
                    command: 'previousRequiredQuestion'
                },
                {
                    name: 'Next Choice',
                    keys: 'right',
                    description: 'Navigate to the next choice (single and multi-select questions).'
                },
                {
                    name: 'Previous Choice',
                    keys: 'left',
                    description: 'Navigate to the previous choice (single and multi-select questions).'
                },
                {
                    name: 'Edit',
                    keys: 'ctrl+i',
                    description: 'Edit the assessment properties.',
                    command: 'editAssessmentProperties'
                }
            ]
        }
    ];
    function executeShortcut(shortcut, event) {
        var command = getCommand(app.modal, shortcut.command);
        var isActive;
        if (command) {
            isActive = command.isActive();
            if (isActive && command.canExecute()) {
                command.execute();
                return false;
            }
            return !isActive;
        }
        if (app.modal) {
            return true;
        }
        if (shortcut.href) {
            shell.router.navigate(shortcut.href);
            return false;
        }
        var viewModel = shell.router.activeItem();
        command = getCommand(viewModel, shortcut.command) || getCommand(shell, shortcut.command);
        if (command) {
            isActive = command.isActive();
            if (isActive && command.canExecute()) {
                command.execute();
                return false;
            }
            return !isActive;
        }
    }
    function getCommand(model, key) {
        if (model && key && model.commands) {
            var commands = model.commands;
            return commands.getByKey(key);
        }
        return null;
    }
    exports.categories.forEach(function (c) {
        c.shortcuts.forEach(function (s) {
            if (s.command || s.href) {
                Mousetrap.bindGlobal(s.keys.split(',').map(function (k) { return k.trim(); }), function (e) { return executeShortcut(s, e); });
            }
        });
    });
});

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
define('core/KeyboardShortcuts',["require", "exports", 'core/keyboard', 'core/viewmodels'], function (require, exports, keyboard, viewmodels) {
    var KeyboardShortcuts = (function (_super) {
        __extends(KeyboardShortcuts, _super);
        function KeyboardShortcuts() {
            var _this = this;
            _super.call(this);
            this.filteredCategories = ko.observableArray([]);
            this.searchString = ko.observable('');
            this.hasResults = ko.computed(function () { return _this.filteredCategories().length > 0; });
            this.showNoResultsMessage = ko.observable(false);
            this.throttledSearchString = ko.computed(function () {
                return _this.searchString();
            }).extend({ throttle: 500 });
            this.searchString.subscribe(function (value) {
                _this.showNoResultsMessage(false);
            });
            this.throttledSearchString.subscribe(function (value) {
                _this.filterCategories();
            });
            this.filterCategories();
        }
        KeyboardShortcuts.prototype.filterCategories = function () {
            var s = this.searchString().toLowerCase().trim();
            if (s === '') {
                this.filteredCategories(keyboard.categories);
                return;
            }
            var filtered = keyboard.categories.map(function (c) {
                return {
                    name: c.name,
                    shortcuts: c.shortcuts.filter(function (k) { return (c.name + ' ' + k.name + ' ' + k.description + ' ' + k.keys).toLowerCase().indexOf(s) >= 0; })
                };
            });
            filtered = filtered.filter(function (c) { return c.shortcuts.length > 0; });
            this.showNoResultsMessage(filtered.length === 0 && s.length > 0);
            this.filteredCategories(filtered);
        };
        return KeyboardShortcuts;
    })(viewmodels.ModalViewModelBase);
    return KeyboardShortcuts;
});

define('core/fallback',["require", "exports", 'plugins/router'], function (require, exports, durandalRouter) {
    var Fallback = (function () {
        function Fallback() {
            this.compositionComplete = durandalRouter.navigateBack;
        }
        Fallback.prototype.getView = function () {
            return $.parseHTML('<div></div>')[0];
        };
        return Fallback;
    })();
    return Fallback;
});


define('text!core/rootEntityCommands.html',[],function () { return '<div class="btn-group btn-group-sm">\r\n    <button type="button" class="btn btn-info" data-bind="click: save, enable: canSave, visible: !isReadOnly()">\r\n        <span class="glyphicon glyphicon-floppy-disk"></span>\r\n        <span data-i18n="common.save"></span>\r\n    </button>\r\n    <button type="button" class="btn btn-info hidden-xs" data-bind="click: saveAndClose, enable: canSaveAndClose, visible: !isReadOnly()">\r\n        <span data-i18n="common.saveAndClose"></span>\r\n    </button>\r\n    <button type="button" class="btn btn-info" data-bind="click: close, enable: canClose">\r\n        <!--<span class="glyphicon glyphicon-minus"></span>-->\r\n        <span data-i18n="common.close"></span>\r\n    </button>\r\n\r\n    <!--<button type="button" class="btn btn-info" data-bind="click: revert, enable: canRevert">\r\n        <span data-i18n="common.revert"></span>\r\n    </button>\r\n    <button type="button" class="btn btn-info" data-bind="click: remove, enable: canRemove">\r\n        <span data-i18n="common.delete"></span>\r\n    </button>\r\n    <button type="button" class="btn btn-info" data-bind="click: print, enable: canPrint">\r\n        <span class="glyphicon glyphicon-print"></span>\r\n        <span data-i18n="common.print"></span>\r\n    </button>-->\r\n    <div class="btn-group btn-group-sm">\r\n        <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">\r\n            <span data-i18n="common.more"></span>\r\n            &nbsp;\r\n            <span class="caret"></span>\r\n        </button>\r\n        <ul class="dropdown-menu" role="menu">\r\n            <li data-bind="css: { disabled: !canRevert() }, visible: !isReadOnly()">\r\n                <a href="#" data-bind="click: revert" data-i18n="common.revert"></a>\r\n            </li>\r\n            <li data-bind="css: { disabled: !canRemove() }, visible: showRemove()">\r\n                <a href="#" data-bind="click: remove" data-i18n="common.delete"></a>\r\n            </li>\r\n            <li data-bind="css: { disabled: !canPrint() }, visible: showPrint()">\r\n                <a href="#" data-bind="click: print" data-i18n="common.print"></a>\r\n            </li>\r\n        </ul>\r\n    </div>\r\n</div>';});


define('text!core/standardSelect.html',[],function () { return '<select class="form-control"\r\n        data-bind="options: activationData.lookup,\r\n                optionsText: \'Description\',\r\n                optionsValue: function(item) { return normalizeGuid(item.ID); },\r\n                optionsCaption: activationData.placeholder,\r\n                value: activationData.property,\r\n                css: { blank: !activationData.property(), \'input-sm\': activationData.small },\r\n                attr: { id: activationData.elementId },\r\n                enable: activationData.enable"></select>\r\n';});

define('core/strings',["require", "exports"], function (require, exports) {
    exports.resources = {
        'en-US': {
            translation: {
                app: {
                    shortName: 'Assessments',
                    longName: 'Mobile Assessments',
                    versionPrefix: 'Focus Group ',
                },
                common: {
                    id: 'ID',
                    name: 'Name',
                    yes: 'Yes',
                    no: 'No',
                    ok: 'OK',
                    cancel: 'Cancel',
                    all: 'All',
                    none: 'None',
                    back: 'Back',
                    submit: 'Submit',
                    agency: 'Agency',
                    provider: 'Provider',
                    'date': 'Date',
                    attach: 'Attach',
                    open: 'Open',
                    'new': 'New',
                    save: 'Save',
                    sync: 'Sync',
                    saveAndClose: 'Save and Close',
                    revert: 'Revert',
                    'clear': 'Clear',
                    close: 'Close',
                    copy: 'Copy',
                    edit: 'Edit',
                    select: 'Select',
                    print: 'Print',
                    preview: 'Preview',
                    'delete': 'Delete',
                    addNext: 'Add Next',
                    more: 'More',
                    download: 'Download',
                    downloaded: 'Downloaded',
                    downloading: 'Downloading',
                    search: 'Search',
                    makeAvailableOffline: 'Make Available Offline',
                    empty: 'Empty',
                    description: 'Description',
                    restart: 'Restart',
                    error: 'Error',
                    errorMessage: 'An error has occurred.\n\n{0}',
                    developerTitle: 'Developer console',
                    developerInfos: 'User actions log : \n{0}',
                    validationErrorsWarningMessage: 'The assessment contains validation errors. If you want to save anyway, switch the status to Draft.',
                    timeoutWarning: 'The server couldn\'t process your request at this moment. Your data was saved locally. You may want to retry to save your assessment to the server in a few.',
                    unableToFindAnythingMatching: 'Unable to find anything matching "',
                    saveFailedUnableToConnect: 'Save failed.  Unable to connect to Harmony servers.',
                    promptToFinalizeChangesTitle: 'Action Required',
                    promptToFinalizeChangesMessage: '"{0}" has pending changes that must be saved or discarded before continuing.',
                    revertPrompt: 'Are you sure you want to revert your changes to "{0}"?',
                    revertAllPrompt: 'Are you sure you want to revert/delete all of your unsaved changes?',
                    deletePrompt: 'Are you sure you want to PERMANENTLY DELETE "{0}" from the database?  This cannot be undone.',
                    deleteFromCachePrompt: 'Are you sure you want to delete "{0}" from the device?',
                    deleteTitle: 'Delete {0}',
                    deleting: 'Deleting...',
                    successfulDelete: "'{0}' was deleted",
                    validationErrorsPreventedDelete: '{0}',
                    validationErrorsPreventedSave: 'Unable to save due to validation errors in "{0}".  Would you like to open this record to correct the validation errors?\n\n<ul>{1}</ul>',
                    validationErrorsPreventedSaveOKOnly: 'Unable to save due to validation errors in "{0}".\n\n<ul>{1}</ul>',
                    checkIn: "Check In",
                    checkOut: "Check Out",
                    undoCheckOut: "Undo Check Out",
                    history: 'History',
                    searchHistory: 'Search history...',
                    youDontHaveAnyHistory: 'Records you\'ve opened will be listed here.  You can find records to open using the ',
                    historyNoResults1: 'Your history does not contain anything matching "',
                    historyNoResults2: '".  Would you like to ',
                    unableToConnect: 'Unable to connect to Harmony servers.',
                    keyboardShortcuts: 'Keyboard Shortcuts',
                    searchKeyboardShortcuts: 'Search keyboard shortcuts...',
                    keyboardNoResults1: 'There are no shortcuts matching "',
                    keyboardNoResults2: '".',
                    phone: 'Phone',
                    town: 'Town',
                    resAddress1: 'Address 1',
                    notes: 'Notes',
                    loading: 'Loading...',
                    saving: 'Saving...',
                    activeWithQuestionMark: 'Active?',
                    toggleNavigation: 'Toggle navigation',
                    startDate: 'Start Date',
                    endDate: 'End Date',
                    type: 'Type',
                    year: 'Year',
                    duration: 'Duration',
                    hospitalName: 'Hospital Name',
                    reason: 'Reason',
                    unitType: 'Unit Type',
                    frequency: 'Frequency',
                    comments: 'Comments',
                    register: 'Register',
                    notifications: 'Notifications',
                    localDataThatIsNotSaved: 'Unsaved Data - Click to recover',
                    youDontHaveAnyUnsavedEntity: 'System notifications will be listed here as they become available.',
                    entityWasSavedToTheDatabase: '{0} was saved to the database.',
                    entityWasSavedToDeviceStorage: '{0} was saved to device storage.',
                    conflictingEdit: 'Conflicting Edit',
                    conflictingEditMessage: 'Changes to {0} could not be saved because the record was updated by another user while you were editing it.',
                    conflictingDeleteMessage: 'Changes to {0} could not be saved because the record was deleted by another user while you were editing it.',
                    navigationFailed: 'Navigation Failed',
                    navigationFailedMessageFormat: '{0}',
                    unsupportedBrowserTitle: 'Unsupported Browser',
                    yourBrowserIsNotSupported: 'Your browser is not supported ({0} {1}).  Mobile Assessments supports the following device/OS/browser combinations:',
                    remove: 'Remove',
                    removing: 'Removing...',
                    removeFromDevice: 'Remove From Device',
                    removeFromDeviceMessage: 'Are you sure you want to remove \'{0}\' from your devices?  You will no longer be able to access \'{0}\' while offline.',
                    removeAllFromDevice: 'Remove All From Device',
                    removeAllFromDeviceMessage: 'Are you sure you want to remove all consumers from your devices?  You will no longer be able to access these consumers while offline.',
                    applicationData: 'Application Data',
                    clearData: 'Clear Data',
                    clearDataMessage: 'Are you sure you want to remove all Mobile Assessments application data stored on this device?',
                    dataCleared: 'Data Cleared',
                    dataClearedMessage: 'Application data cleared successfully.  Would you like to restart the application or close?',
                    goOnline: 'Go online',
                    goOnlineMessage: 'There are {0} entities modified offline. Would you like to synchronize them to the server? <br />You will be redirected to the homepage.',
                    goOffline: 'Go offline',
                    goOfflineMessage: 'Are you sure you want to go offline? Only downloaded data will be accessible until you go back online.',
                    warning: 'WARNING',
                    ieUnSupportedbrowser: 'You are using Internet Explorer, which is no longer supported. This will cause problems on this website (and other websites). Microsoft offers newer and better software to replace Internet Explorer, for free.<br /><br /> For more information on how to upgrade, please visit <a href="https://www.microsoft.com/en-us/edge" target="_blank">https://www.microsoft.com/en-us/edge</a>',
                    cfbuilder: 'CF Builder',
                    template: 'Form'
                },
                entities: {
                    consumer: 'Consumer',
                    consumerUserField: 'Custom Field',
                    caller: 'Caller',
                    assessment: 'Assessment',
                    response: 'Response',
                    eventListResponse: 'Event List Response',
                    icd9CodeResponse: 'ICD9 Code Response',
                    indicatorResult: 'Indicator Result',
                    medListResponse: 'Medication List Response',
                    multiChoiceResponse: 'Multiple Choice Response',
                    sessionNote: 'Note',
                    locusCareHistory: 'Care Enrollment',
                    applicationDefaults: 'My Settings',
                    consumerProvider: 'Consumer Provider',
                    consumerProviderWebAccess: 'Web Access',
                    diagnosisCode: 'Diagnosis Code',
                    location: 'Location',
                    phone: 'Phone',
                    contact: 'Contact',
                    consumerEthnicGroup: 'Ethnic Race'
                },
                consumer: {
                    firstName: 'First Name',
                    middleInitial: 'Middle Initial',
                    lastName: 'Last Name',
                    dateOfBirth: 'Date of Birth',
                    socialSecurityNumber: 'Social Security Number',
                    alternateIdentifier: 'Alternate Identifier',
                    downloadedConsumers: 'Downloaded Consumers',
                    recentConsumers: 'Recent Consumers',
                    searchForConsumers: 'Search for consumers...',
                    youDontHaveAnyDownloadedConsumers: 'Consumers you\'ve made available offline will be listed here.  You can find consumers to make available offline using the ',
                    clientIDChangeTitle: 'Client ID change',
                    clientIDChangeMessage: 'Client ID is based on DOB and SSN.  Your changes to DOB/SSN will result in a new client ID: {0}.  Current client ID: {1}.',
                    clientIDChangeToRandomMessage: 'Client ID is based on DOB and SSN.  Your changes to DOB/SSN will result in a random client ID being assigned because the consumer\'s DOB or last 4 digits of SSN are missing.  Current client ID: {0}.',
                },
                diagnosis: {
                    diagnosisCode: 'Diagnosis Code',
                    severity: 'Severity',
                    diseaseCode: 'Disease Code'
                },
                medication: {
                    medication: 'Medication',
                    othermedication: 'Other Medication',
                    dosage: 'Dosage',
                    status: 'Status',
                    routeOfAdministration: 'Route of Administration',
                    medicationManager: 'Medication Manager',
                    whereObtained: 'Where Obtained',
                    mailOrder: 'Mail Order',
                    packaging: 'Packaging',
                    typeOfAssistance: 'Type of Assistance',
                    medicationAssistance: 'Medication Assistance'
                },
                relation: {
                    addNewRelation: 'Add New Relation',
                    editRelation: 'Edit Relation',
                    searchExistingRelations: 'Search Existing Relations',
                    relationCategory: 'Relation Category',
                    relationship: 'Relationship',
                    multipleRelationships: 'Multiple Relationships',
                    lastName: 'Last Name',
                    middleName: 'Middle Name',
                    firstName: 'First Name',
                    street: 'Street',
                    street2: 'Street 2',
                    city: 'City',
                    state: 'State',
                    zipCode: 'Zip Code',
                    residenceCounty: 'Residence County',
                    homePhone: 'Home Phone',
                    cellPhone: 'Cell Phone',
                    workPhone: 'Work Phone'
                },
                assessment: {
                    findQuestion: 'Find Question...',
                    consumerNotUpdated_NeverUpdate: 'The consumer was not updated because your preferences are set to never update the consumer when saving an assessment.',
                    consumerNotUpdated_AccessRole: 'The consumer was not updated because your access role does not allow you to update consumers.',
                    consumerNotUpdated_NotMostRecent: 'The consumer was not updated because this assessment is not the consumer\'s most recent assessment.',
                    consumerNotUpdated_OrganizationSecurity: 'The consumer was not updated because members of your organization do not have permission to update this consumer.',
                    consumerNotUpdated_NoLinkedQuestionsWereChanged: 'The consumer was not updated because no changes were made to questions that map back to the consumer record.',
                    unansweredPrompt: 'There are {0} unanswered required questions in this assessment, are you sure you want to close it now?',
                    unansweredPromptTitle: 'Confirm Close',
                    readExpired: 'Your read permissions for this assessment have expired.',
                    consumerSaveFailed: 'Consumer save failed',
                },
                enrollment: {
                    careProgramName: "Care Program"
                },
                session: {
                    dateOfAssessment: 'Date of Assessment',
                    nextAssessmentDate: 'Next Assessment Date',
                    assessmentForm: 'Assessment Form',
                    filename: 'Filename',
                    assessor: 'Assessor',
                    lastUpdated: 'Last Updated',
                    updatedBy: 'Updated By',
                    newAssessment: 'New Assessment',
                    copyAssessment: 'Copy Assessment',
                    choiceId: 'ID',
                    catalogChoice: 'Catalog Choice',
                    choiceDescription: 'Description',
                    samsChoice: 'SAMS Choice',
                    checkOutUser: 'Check out User',
                    checkOutDateTime: 'Check out Date'
                },
                settings: {
                    mySettings: 'My Settings',
                    mapping: 'Assessment Response Mapping',
                    mappingDescription: 'Use this area to map assessment response choices to their equivalent SAMS consumer property value.  This will expedite data entry by eliminating the manual mapping that\'s required when saving an assessment with response values that do not have an exact match in SAMS.',
                },
                security: {
                    pleaseSignIn: 'Please sign in',
                    offlineSignIn: 'Offline sign in',
                    userName: 'User Name',
                    password: 'Password',
                    database: 'Database',
                    profile: 'Profile',
                    enterUserName: 'Enter user name',
                    selectUser: 'Select user',
                    enterPassword: 'Enter password',
                    selectDatabase: 'Select database',
                    loginAsTitle: 'Log in as another user',
                    loginAsMessage: 'Are you sure you want to log in as another user?',
                    logoutTitle: 'Sign out',
                    logoutMessage: 'Are you sure you want to sign out?',
                    authenticating: 'Authenticating...',
                    unauthorized: 'Unauthorized',
                    yourAccountIsNotAuthorized: 'Your account is not licensed for this site.  Contact your Harmony Customer Portal Administrator for assistance.',
                    offlineAccess: 'Offline Access',
                    notReadyForOfflineAccess: 'This device is not ready for offline access.  To enable offline access you must login at least once while online.  This will allow data such as assessment forms and consumers to be stored on the device for use when offline.',
                    userIsRequired: 'User is required.',
                    userNameIsRequired: 'User name is required.',
                    passwordIsRequired: 'Password is required.',
                    databaseIsRequired: 'Database is required.',
                    portalPasswordIsInvalid: 'Invalid password.',
                    incorrectPassword: 'Incorrect password.',
                    insufficientPrivilegesToRegister: 'Your access role(s) do not grant you \'create\' permission on the \'last name\' field.  This permission is required to register new consumers.',
                    insufficientPrivilegesToView: 'Your access role(s) do not grant you \'view\' permission on the object you\'re trying to access.  This permission is required.',
                    notAuthorizedMessage: 'Your access failed because {0}',
                    switchAccounts: 'Switch Accounts',
                    switchAccountsMessage: 'Initially you were signed in as {0}.  You\'ve signed back in as {1}.  To complete the account switch the application must restart.\r\n\r\nClick OK to restart the application.',
                    ssoSessionExpiryWarning: "Your session is about to expire. To extend your session, click on the 'Continue' button.",
                    sessionExpiredTitle: 'Session Expired',
                    sessionAlreadyExpired: 'Your session has expired. You will now be redirected to the login page.',
                    ssoLoginError: 'Oops! Something went wrong during the login process.'
                },
                locateForm: {
                    title: 'Assessment Form Missing',
                    message: 'Unable to locate assessment form <code>{0}</code>.',
                },
                formNotAvailableOffline: {
                    title: 'Assessment Form Not Available Offline',
                    message: 'The assessment cannot be opened because the form <code>{0}</code> has not been made available offline.<br /><br />Your administrator can make assessment forms available offline using <b>SAMS 3 Administrator</b><small class="glyphicon glyphicon-chevron-right" /><b>System Configuration</b><small class="glyphicon glyphicon-chevron-right" /><b>Assessment Forms</b>.',
                },
                ajaxRetry: {
                    message: 'There was an error connecting to the Harmony servers.  This may be a problem with your internet connection or a temporary issue with the Harmony servers.  Do you want to retry?',
                    title: 'Connection Error'
                },
                sessionLocked: {
                    message: 'Your session has been locked due to inactivity.<br/>Click OK to enter your credentials and continue your session.',
                    title: 'Session Locked'
                },
                applicationUpdateReady: {
                    message: 'An application update is ready.  Click OK to update.',
                    title: 'Application Update'
                },
                sync: {
                    systemData: 'Downloading system data...',
                    lookups: 'Downloading admin data...',
                    indicatorCatalog: 'Downloading indicator catalog...',
                    assessmentForm: 'Downloading assessment form ',
                    complete: 'Offline data synchronization complete.',
                    failed: 'Offline data synchronization failed.  Unable to connect to Harmony servers.',
                },
                dialog: {
                    registerConsumerTitle: 'Register Consumer',
                    registerConsumerPotentialDupes: 'Potential existing matching consumers',
                    personalizationTitle: 'Options',
                    applicationDefaults: 'Application Defaults',
                    assessmentOptions: 'Assessment Options'
                },
                options: {
                    defaultReassessmenDate: 'Default Reassessment Date (Months)',
                    uploadClientrecord: 'Update Consumer Record?',
                    requiredQuestionPrompt: 'Required Question Prompt',
                    defaultAssessmentForm: 'Default Assessment Form',
                    assessmentShowQuestionHighlight: 'Highlight Selected Question and Responses',
                    assessmentNavigateOnEnter: 'Navigate to Next Question/Section with Enter Key',
                    assesmentStartupOption: 'Start Up Mode',
                    medicalListNumerTakenDefault: 'Medication List Default Number Taken',
                    assessmentDefaultRoute: 'Medication List Default Route',
                    assessmentDefaultPrn: 'Medication List Default PRN',
                    enableAutomaticSaveAssessment: 'Enable Assessment Automatic Save',
                    assessmentAutomaticSaveInterval: 'Assessment Automatic Save Interval (Min)',
                    defaultCarePrograms: 'Default Care Programs',
                    defaultAgency: 'Default Agency',
                    defaultProvider: 'Default Provider'
                },
                webIntake: {
                    notAuthorizedTitle: 'Web Intake',
                    notAuthorizedMessage: 'Web intake is not enabled.',
                    cancelTitle: '{0}',
                    cancelMessage: '{0}'
                },
                screenDesignNotInPackage: {
                    title: 'Open Assessment',
                    message: 'The screen design is not in the "ConsumerAssessments" package.  Screen design ID is "{0}".'
                },
                apsWebIntake: {
                    cancelTitle: 'You are about to close this window',
                    cancelMessage: 'If you click OK, any information that was entered will be lost.  Click cancel to return to the window in order to continue entering information.'
                },
                spiWebIntake: {
                    success: 'Success!',
                    thankYou: 'Thank you for filling the form.',
                    singleIdReferenceMessage: 'Please keep this reference number for your record:',
                    multipleIdReferenceMessage: 'Please keep these reference numbers for your records:',
                    print: 'Print',
                    error: 'Error',
                    errorMessage: 'There was an error trying to save the Intake, please contact support with the ID:',
                    loadingTitle: 'Loading',
                    loadingMessage: 'The intake is being saved, please wait...'
                }
            }
        },
        'es-US': {
            translation: {
                spiWebIntake: {
                    success: '¡Éxito!',
                    thankYou: 'Gracias por completar el formulario.',
                    singleIdReferenceMessage: 'Por favor conserve este número de referencia:',
                    multipleIdReferenceMessage: 'Por favor conserve estos números de referencia:',
                    print: 'Imprimir',
                    error: 'Error',
                    errorMessage: 'Hubo un error al intentar guardar el formulario, por favor contacte a soporte con el identificador:',
                    loadingTitle: 'Cargando',
                    loadingMessage: 'El formulario está siendo procesado, espere un momento por favor...'
                }
            }
        }
    };
    exports.resources['en'] = exports.resources['en-US'];
    exports.resources['es'] = exports.resources['es-US'];
    exports.resources['dev'] = exports.resources['en-US'];
});


define('text!core/typeaheadSelect.html',[],function () { return '<input type="text"\r\n       class="form-control" autocomplete="off" autocorrect="off" autocapitalize="yes" spellcheck="false"\r\n       maxlength="80"\r\n       data-bind="value: value, valueUpdate: \'input\',\r\n                  attr: { id: activationData.id, placeholder: activationData.placeholder },\r\n                  enable: activationData.enable,\r\n                  typeahead: typeaheadOptions,\r\n                  css: { \'input-sm\': activationData.small }" />';});


define('text!core/validationSummary.html',[],function () { return '<div class="validation-summary hidden-print">\r\n    <div class="alert alert-danger" data-bind="visible: filterValidationErrorsByType(\'required\').length > 0">\r\n        <strong tabindex="0" data-bind="visible: filterValidationErrorsByType(\'required\').length > 0" required-val>Please answer the required questions.  You may click on the error messages below to navigate to unanswered questions.</strong>\r\n        <ul data-bind="foreach: filterValidationErrorsByType(\'required\')" class="list-unstyled">\r\n            <li tabindex="0" data-bind="text: errorMessage, click: function() { if ($parent.scrollToError) $parent.scrollToError.bind($parent)($data); }, css: { clickable: ($data.context && $data.context.scaleId) }"></li>\r\n        </ul>\r\n    </div>\r\n    <div class="alert alert-danger" data-bind="visible: filterValidationErrorsByType(\'reporttype\').length > 0">\r\n        <strong tabindex="0" data-bind="visible: filterValidationErrorsByType(\'reporttype\').length > 0" required-par>There is a value mismatch between the Type of Report (Child or Adult) selected on the main page and what is populated on the participant and/or allegation pages.   Please reopen the record(s) to reset the Type of Report field.</strong>\r\n        <ul data-bind="foreach: filterValidationErrorsByType(\'reporttype\')" class="list-unstyled">\r\n            <li tabindex="0" data-bind="text: errorMessage, click: function() { if ($parent.scrollToError) $parent.scrollToError.bind($parent)($data); }, css: { clickable: ($data.context && $data.context.scaleId) }"></li>\r\n        </ul>\r\n    </div>\r\n</div>';});


define('text!custom_forms_widgets/cfbuilder/cfbuilder.html',[],function () { return '<section class="container">\r\n    <div id="forms_settings_widget"></div>\r\n</section>\r\n';});

define('custom_forms_widgets/cfbuilder/cfbuilder',["require", "exports"], function (require, exports) {
    function loadWidget() {
        var tokenUrl = app.hostUrl + "/api/CustomForm/GetCustomFormBuilderSettings";
        $.get(tokenUrl, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        }).then(function (response) {
            var win = window;
            win["FormsWidgetSettings"] = window["FormsWidgetSettings"] || {};
            win["FormsWidgetSettings"]["widgets"] = window["FormsWidgetSettings"]["widgets"] || [];
            win["FormsWidgetSettings"]["widgets"].push({
                widget: 'forms_settings_page',
                type: 'inline',
                mount: 'forms_settings_widget',
                baseUrl: '',
                token: response.Token,
                appsyncGraphqlEndpoint: app.AppSyncGraphqlEndpoint,
                appsyncApiKey: app.AppSyncApiKey,
                widgetCompleteFormInNewWindow: true,
                timezone: "US/Pacific",
            });
            setTimeout(function () {
                var script = document.createElement("script");
                script.src = app.CFWidgets;
                var forms_settings_widget = document.getElementById('forms_settings_widget');
                if (forms_settings_widget != null) {
                    forms_settings_widget.appendChild(script);
                }
            }, 1000);
        });
    }
    loadWidget();
});


define('text!custom_forms_widgets/complete_template/complete_template.html',[],function () { return '<section class="container" style="width: 100%;">\r\n    <div id="custom_header"></div>\r\n    <div id="forms_settings_widget"></div>\r\n    <div id="custom_footer"></div>\r\n</section>';});

define('custom_forms_widgets/complete_template/complete_template',["require", "exports", 'core/util'], function (require, exports, util) {
    function loadWidget() {
        var tokenUrl = app.hostUrl + "/api/CustomForm/GetCustomFormBuilderSettings";
        $.get(tokenUrl, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        }).then(function (response) {
            var win = window;
            win["FormsWidgetSettings"] = window["FormsWidgetSettings"] || {};
            win["FormsWidgetSettings"]["widgets"] = window["FormsWidgetSettings"]["widgets"] || [];
            win["FormsWidgetSettings"]["widgets"].push({
                widget: 'complete_form',
                type: 'inline',
                formTemplateId: response.FormTemplateId,
                mount: 'forms_settings_widget',
                baseUrl: '',
                token: response.Token,
                appsyncGraphqlEndpoint: app.AppSyncGraphqlEndpoint,
                appsyncApiKey: app.AppSyncApiKey,
                widgetCompleteFormInNewWindow: true,
                disablePreviouslyFilledInstanceFetching: true,
                timezone: "US/Pacific",
                showSave: false,
                widgetLanguage: 'es',
                afterSubmitUrl: window.location.pathname + "?CfWebIntake=SpanishWebIntake#completeform"
            });
            setTimeout(function () {
                var script = document.createElement("script");
                script.src = app.CFWidgets;
                var forms_settings_widget = document.getElementById('forms_settings_widget');
                if (forms_settings_widget != null) {
                    forms_settings_widget.appendChild(script);
                }
                util.setCFWebIntakePageTitle();
            }, 1000);
        });
    }
    util.setCustomHeaderAndFooter();
    loadWidget();
});


define('text!custom_forms_widgets/confirmation_template/cf_confirmation.html',[],function () { return '<section class="container" style="width: 100%;">\r\n    <div id="custom_header"></div>\r\n    <h1 id="title"></h1>\r\n    <h3 id="thankYou" style="visibility: hidden;"><span data-i18n="spiWebIntake.thankYou"></span></h3>\r\n    <h3 id="message"></h3>\r\n    <br>\r\n    <button type="button" id="print_cf_form_button" style="visibility: hidden;">\r\n        <span data-i18n="spiWebIntake.print"></span>\r\n    </button>\r\n    <br>\r\n    <div id="custom_footer"></div>\r\n</section>';});

define('custom_forms_widgets/confirmation_template/cf_confirmation',["require", "exports", 'core/util'], function (require, exports, util) {
    function changeLang() {
        $.i18n.setLng("es-US");
    }
    function setLoadingTags() {
        var title = document.getElementById('title');
        var message = document.getElementById('message');
        title.innerHTML = $.i18n.t('spiWebIntake.loadingTitle');
        message.innerHTML = $.i18n.t('spiWebIntake.loadingMessage');
    }
    function setSuccessTags(idList) {
        var referenceMessage = idList.length == 1 ? $.i18n.t('spiWebIntake.singleIdReferenceMessage') : $.i18n.t('spiWebIntake.multipleIdReferenceMessage');
        var title = document.getElementById('title');
        var message = document.getElementById('message');
        var thankYou = document.getElementById('thankYou');
        var printButton = document.getElementById('print_cf_form_button');
        title.innerHTML = $.i18n.t('spiWebIntake.success');
        thankYou.setAttribute("style", "visibility: visible;");
        message.innerHTML = referenceMessage + ' ' + idList.join(', ');
        printButton.setAttribute("onclick", "window.location.href = window.location.pathname + '?CfWebIntake=SpanishWebIntake#printform' ");
        printButton.setAttribute("style", "visibility: visible;");
    }
    function setErrorTags() {
        var title = document.getElementById('title');
        var message = document.getElementById('message');
        var sanitazedCFFormInstanceId = encodeURIComponent(sessionStorage.getItem('cf_formInstanceId'));
        title.innerHTML = $.i18n.t('spiWebIntake.error');
        message.innerHTML = $.i18n.t('spiWebIntake.errorMessage') + ' ' + sanitazedCFFormInstanceId;
    }
    function GetInquiryStatus(formInstanceId, attemptNumber) {
        if (attemptNumber >= app.CustomFormsSubmissionCheckMaxAttempts) {
            setErrorTags();
            return;
        }
        var inquiryStatusUrl = app.hostUrl + "api/CustomForm/GetCreatedInquiryIds?" + $.param({ formInstanceId: formInstanceId, attemptNumber: attemptNumber });
        $.get(inquiryStatusUrl, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        }).then(function (response) {
            if (!Array.isArray(response) || response.length == 0) {
                setTimeout(function () {
                    GetInquiryStatus(formInstanceId, ++attemptNumber);
                }, app.CustomFormsSubmissionCheckTimeSpan);
            }
            else {
                setSuccessTags(response);
            }
        }).fail(function () {
            setErrorTags();
        });
    }
    function loadPage() {
        setLoadingTags();
        var attemptNumber = 0;
        var formInstanceId = encodeURIComponent(sessionStorage.getItem('cf_formInstanceId'));
        GetInquiryStatus(formInstanceId, attemptNumber);
    }
    changeLang();
    setTimeout(function () {
        loadPage();
        util.setCustomHeaderAndFooter();
        util.setCFWebIntakePageTitle();
    }, 500);
});


define('text!custom_forms_widgets/edit_template/edit_template.html',[],function () { return '<section class="container">\r\n    <div id="forms_settings_widget"></div>\r\n</section>\r\n';});

define('custom_forms_widgets/edit_template/edit_template',["require", "exports", 'entities/url'], function (require, exports, url) {
    function loadWidget() {
        var urlParams = url.getParamsAfterHash();
        var tokenUrl = app.hostUrl + "/api/CustomForm/GetCustomFormBuilderSettings";
        $.get(tokenUrl, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        }).then(function (response) {
            var win = window;
            win["FormsWidgetSettings"] = window["FormsWidgetSettings"] || {};
            win["FormsWidgetSettings"]["widgets"] = window["FormsWidgetSettings"]["widgets"] || [];
            win["FormsWidgetSettings"]["widgets"].push({
                widget: 'edit_template',
                type: 'inline',
                baseTemplateId: urlParams.template_id,
                templateUseId: urlParams.templateUse,
                mount: 'forms_settings_widget',
                afterSubmitUrl: '#cfbuilder/',
                baseUrl: '',
                appsyncGraphqlEndpoint: app.AppSyncGraphqlEndpoint,
                appsyncApiKey: app.AppSyncApiKey,
                token: response.Token,
                widgetCompleteFormInNewWindow: true,
                timezone: "US/Pacific",
            });
            setTimeout(function () {
                var script = document.createElement("script");
                script.src = app.CFWidgets;
                var forms_settings_widget = document.getElementById('forms_settings_widget');
                if (forms_settings_widget != null) {
                    forms_settings_widget.appendChild(script);
                }
            }, 1000);
        });
    }
    loadWidget();
});


define('text!custom_forms_widgets/print_template/print_cf_form.html',[],function () { return '<section class="container">\r\n    <div id="print_form_widget">\r\n    </div>\r\n</section>\r\n';});

define('custom_forms_widgets/print_template/print_cf_form',["require", "exports", 'core/util'], function (require, exports, util) {
    function loadPrintForm() {
        var formInstanceId = sessionStorage.getItem('cf_formInstanceId');
        var tokenUrl = app.hostUrl + "/api/CustomForm/GetCustomFormBuilderSettings";
        $.get(tokenUrl, {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        }).then(function (response) {
            window["FormsWidgetSettings"] = window["FormsWidgetSettings"] || {};
            window["FormsWidgetSettings"]["widgets"] = window["FormsWidgetSettings"]["widgets"] || [];
            window["FormsWidgetSettings"]["widgets"].push({
                widget: "print_form",
                type: "inline",
                mount: "print_form_widget",
                timezone: "US/Central",
                formInstanceId: formInstanceId,
                token: response.Token,
                appsyncGraphqlEndpoint: app.AppSyncGraphqlEndpoint,
                appsyncApiKey: app.AppSyncApiKey,
                displayFormInformation: false
            });
            setTimeout(function () {
                var script = document.createElement("script");
                script.src = app.CFWidgets;
                var print_form_widget = document.getElementById('print_form_widget');
                if (print_form_widget != null) {
                    print_form_widget.appendChild(script);
                }
            }, 1000);
        });
    }
    setTimeout(function () {
        loadPrintForm();
        util.setCFWebIntakePageTitle();
    }, 1500);
});


define('text!downloaded/downloaded.html',[],function () { return '<section class="container">\r\n    <h3 data-bind="visible: hasDownloadedEntities">\r\n        <span>Downloaded</span>\r\n        <button class="btn pull-right" data-bind="click: removeAllFromDevice">\r\n            <span class="glyphicon-pro glyphicon-pro-disk-remove"></span>\r\n            <span data-i18n="common.removeAllFromDevice"></span>\r\n        </button>\r\n    </h3>\r\n\r\n    <div class="table-responsive" data-bind="visible: hasDownloadedEntities, responsiveDropdown: \'\'">\r\n        <table class="table table-striped table-hover table-condensed">\r\n            <thead>\r\n                <tr>\r\n                    <th></th>\r\n                    <td>ID</td>\r\n                    <td>Name</td>\r\n                </tr>\r\n            </thead>\r\n            <tbody data-bind="foreach: downloadedEntities">\r\n                <tr>\r\n                    <td>\r\n                        <div class="h-grid-btn-group">\r\n                            <div class="btn-group">\r\n                                <a class="btn btn-primary btn-sm autofocus" data-bind="attr: { href: \'#DEMOGRAPHIC/\' + CaseNo }" data-i18n="common.open"></a>\r\n                                <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">\r\n                                    <span class="caret"></span>\r\n                                </button>\r\n                                <ul class="dropdown-menu" role="menu">\r\n                                    <li data-bind="visible: $root.canAddAssessment.bind($root)($data)">\r\n                                        <a href="#" data-i18n="session.newAssessment"\r\n                                           data-bind="attr: { href: \'#DEMOGRAPHIC/\' + CaseNo + \'/ConsumerAssessment/new\' }"></a>\r\n                                    </li>\r\n                                    <li class="divider"></li>\r\n                                    <li>\r\n                                        <a href="#" data-i18n="common.removeFromDevice"\r\n                                           data-bind="click: $root.removeFromDevice"></a>\r\n                                    </li>\r\n                                    <!--<li><a href="#" data-i18n="common.download"></a></li>\r\n                            <li><a href="#" data-i18n="common.print"></a></li>\r\n                            <li class="divider"></li>\r\n                            <li><a href="#" data-i18n="common.delete"></a></li>-->\r\n                                </ul>\r\n                            </div>\r\n                            <span class="glyphicon glyphicon-cloud-download"></span>\r\n                        </div>\r\n                    </td>\r\n                    <td data-bind="text: CaseNo"></td>\r\n                    <td data-bind="text: FirstName + \' \' + LastName"></td>\r\n                </tr>\r\n            </tbody>\r\n        </table>\r\n    </div>\r\n\r\n    <div class="row" data-bind="visible: !hasDownloadedEntities()">\r\n        <div class="col-md-8 col-md-offset-2">\r\n            <div class="panel panel-info">\r\n                <div class="panel-heading">\r\n                    <h3 class="panel-title"><span class="glyphicon glyphicon-info-sign"></span><span class="h-margin-left-10px" data-i18n="consumer.downloadedConsumers"></span></h3>\r\n                </div>\r\n                <div class="panel-body">\r\n                    <span data-i18n="consumer.youDontHaveAnyDownloadedConsumers"></span><a href="#" data-i18n="common.search"></a>.\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</section>';});

define('downloaded/downloaded',["require", "exports", 'entities/api', 'entities/sync', 'core/util', 'entities/softsave', 'core/messageBox'], function (require, exports, entities, entitySync, util, softsave, messageBox) {
    exports.downloadedEntities = ko.observableArray([]);
    exports.hasDownloadedEntities = ko.observable(false);
    function activate() {
        return entitySync.getClientVersions().then(function (clientVersions) {
            var temp = clientVersions.filter(function (v) { return v.Type === entities.entityTypes.DEMOGRAPHIC; }).map(function (v) { return JSON.parse(v.Data); });
            exports.hasDownloadedEntities(temp.length > 0);
            exports.downloadedEntities(temp);
        });
    }
    exports.activate = activate;
    function canAddAssessment(downloadedEntity) {
        return true;
    }
    exports.canAddAssessment = canAddAssessment;
    function removeAllFromDevice() {
        messageBox.show('common.removeAllFromDevice', 'common.removeAllFromDeviceMessage', messageBox.buttons.removeCancel).then(function (button) {
            if (button !== messageBox.remove)
                return;
            var promise = Q.resolve(null);
            app.busyIndicator.setBusy($.i18n.t('common.removing'));
            exports.downloadedEntities().forEach(function (downloadedEntity) { return promise = promise.then(function () { return removeFromDeviceInternal(downloadedEntity); }); });
            promise.then(activate).fail(function (reason) {
                if (util.isConnectionFailure(reason)) {
                    messageBox.show('common.removeAllFromDevice', 'common.unableToConnect', messageBox.buttons.okOnly);
                    return;
                }
                return Q.reject(reason);
            }).finally(function () { return app.busyIndicator.setReady(); }).done();
        });
    }
    exports.removeAllFromDevice = removeAllFromDevice;
    function removeFromDevice(downloadedEntity) {
        messageBox.show('common.removeFromDevice', 'common.removeFromDeviceMessage', messageBox.buttons.removeCancel, [downloadedEntity.FirstName + ' ' + downloadedEntity.LastName]).then(function (button) {
            if (button !== messageBox.remove)
                return;
            app.busyIndicator.setBusy($.i18n.t('common.removing'));
            removeFromDeviceInternal(downloadedEntity).then(activate).fail(function (reason) {
                if (util.isConnectionFailure(reason)) {
                    messageBox.show('common.removeFromDevice', 'common.unableToConnect', messageBox.buttons.okOnly);
                    return;
                }
                return Q.reject(reason);
            }).finally(function () { return app.busyIndicator.setReady(); }).done();
        });
    }
    exports.removeFromDevice = removeFromDevice;
    function removeFromDeviceInternal(consumer) {
        return entitySync.makeConsumerUnvailableOffline(consumer.CaseNo).then(function () { return softsave.SoftSaveManager.removeFromUnsavedEntitiesAndRemoveNotification(consumer.CaseNo, entities.entityTypes.DEMOGRAPHIC); });
    }
});


define('text!history/history.html',[],function () { return '<section class="container">\r\n    <label for="search" class="watermark-lg text-muted"\r\n           data-bind="visible: isNullOrEmpty(searchString()) && hasHistory()"\r\n           data-i18n="common.searchHistory">\r\n    </label>\r\n    <div class="input-group" data-bind="visible: hasHistory">\r\n        <span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span>\r\n        <input type="text" id="search"\r\n               data-bind="value: searchString, valueUpdate: \'input\'"\r\n               class="form-control input-lg autofocus watermarked"\r\n               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n    </div>\r\n    <div class="table-responsive" data-bind="visible: hasResults">\r\n        <table class="table table-striped table-hover table-condensed">\r\n            <tbody>\r\n                <!-- ko foreach: filteredDays -->\r\n                <tr>\r\n                    <td colspan="3">\r\n                        <h4 data-bind="text: description"></h4>\r\n                    </td>\r\n                </tr>\r\n                <!-- ko foreach: history -->\r\n                <tr>\r\n                    <td>\r\n                        <span class="h-margin-left-10px" data-bind="dateText: timestamp, datePattern: \'h:mm A\'"></span>\r\n                    </td>\r\n                    <td>\r\n                        <span data-bind="css: icon"></span>\r\n                        <span data-bind="text: singularName"></span>\r\n                    </td>\r\n                    <td>\r\n                        <span class="glyphicon h-glyphicon-fixed-width h-margin-right-10px" data-bind="css: { \'glyphicon-cloud-download\': IsAvailableOffline }"></span>\r\n                        <a data-bind="text: title, attr: { href: url }"></a>\r\n                    </td>\r\n                </tr>\r\n                <!-- /ko -->\r\n                <!-- /ko -->\r\n            </tbody>\r\n        </table>\r\n    </div>\r\n\r\n    <div data-bind="visible: showNoResultsMessage" class="h-margin-top-10px">\r\n        <span data-i18n="common.historyNoResults1"></span><em data-bind="text: searchString"></em><span data-i18n="common.historyNoResults2"></span><a href="#" data-bind="click: widenSearch">widen your search</a>?\r\n    </div>\r\n\r\n    <div class="row" data-bind="visible: !hasHistory()">\r\n        <div class="col-md-8 col-md-offset-2">\r\n            <div class="panel panel-info">\r\n                <div class="panel-heading">\r\n                    <h3 class="panel-title"><span class="glyphicon glyphicon-info-sign"></span><span class="h-margin-left-10px" data-i18n="common.history"></span></h3>\r\n                </div>\r\n                <div class="panel-body">\r\n                    <span data-i18n="common.youDontHaveAnyHistory"></span><a href="#" data-i18n="common.search"></a>.\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</section>\r\n';});

requirejs.config({
    paths: {
        'text': '../Scripts/text',
        'durandal': '../Scripts/durandal',
        'plugins': '../Scripts/durandal/plugins',
        'transitions': '../Scripts/durandal/transitions'
    },
});
var params = app.query = $.deparam.querystring(true);
if (params.WebIntake) {
    app.webIntake = true;
    app.webIntakeConfigurationName = params.WebIntake;
}
if (params.CfWebIntake) {
    app.CfWebIntake = true;
    app.CfWebIntakeName = params.CfWebIntake;
}
if (params.application == 'consumermodule' && params.authorization) {
    app.consumerModule = true;
    app.consumerModuleAuthorization = params.authorization;
}
if (params.logoutSuccess) {
    app.isLogoutRedirection = true;
}
if (params.ssoLoginError) {
    app.isSSOLoginError = true;
}
var root = this;
define('jquery', [], function () {
    return root.jQuery;
});
define('ko', [], function () {
    return root.ko;
});
define('knockout', [], function () {
    return root.ko;
});
define('breeze', [], function () {
    return root.breeze;
});
define('Q', [], function () {
    return root.Q;
});
define('main',['core/strings'], function (strings) {
    if (app.webIntake) {
        strings.resources['en-US'].translation.common.saving = 'Processing...';
    }
    $.i18n.init({ resStore: strings.resources }, function () {
        require(['bootstrapper'], function (bs) {
            console.log('bootstrapped.');
        });
    });
});


define('text!notifications/notifications.html',[],function () { return '<section class="container">\r\n    <h3 data-bind="visible: notificationDays().length > 0">\r\n        Assessments not synced\r\n        <button class="btn btn-sm pull-right" data-bind="click: revertAll, disable: isSynchronizing()">\r\n            <span class="glyphicon-pro glyphicon-pro-undo"></span>\r\n            <span>Revert All</span>\r\n        </button>\r\n        <button class="btn btn-primary btn-sm pull-right" data-bind="click: saveAll, disable: isSynchronizing()">\r\n            <span class="glyphicon glyphicon-floppy-disk"></span>\r\n            <span>Sync All</span>\r\n        </button>\r\n    </h3>\r\n\r\n    <div class="table-responsive" data-bind="visible: notificationDays().length > 0">\r\n        <table class="table table-striped table-hover table-condensed">\r\n            <tbody>\r\n                <!-- ko foreach: notificationDays -->\r\n                <tr>\r\n                    <td colspan="4">\r\n                        <h4 data-bind="text: description"></h4>\r\n                    </td>\r\n                </tr>\r\n                <!-- ko foreach: changes -->\r\n                <tr>\r\n                    <td>\r\n                        <div class="btn-group btn-group-xs" style="width: 65px">\r\n                            <button type="button" class="btn btn-primary btn-xs" data-bind="click: $root.save, disable: $root.isSynchronizing()" style="width: 65px">\r\n                                <span class="glyphicon glyphicon-floppy-disk"></span>\r\n                                <span data-i18n="common.sync"></span>\r\n                            </button>\r\n                            <button type="button" class="btn btn-xs" data-bind="click: $root.revert, visible: entityState === \'Added\', disable: $root.isSynchronizing()" style="width: 65px">\r\n                                <span class="glyphicon glyphicon-trash"></span>\r\n                                <span data-i18n="common.delete"></span>\r\n                            </button>\r\n                            <button type="button" class="btn btn-xs" data-bind="click: $root.revert, visible: entityState !== \'Added\', disable: $root.isSynchronizing()" style="width: 65px">\r\n                                <span class="glyphicon-pro glyphicon-pro-undo"></span>\r\n                                <span data-i18n="common.revert"></span>\r\n                            </button>\r\n                        </div>\r\n                    </td>\r\n                    <td data-bind="dateText: timestamp, datePattern: \'h:mm a\'"></td>\r\n                    <td>\r\n                        <span data-bind="css: icon"></span>\r\n                        <span data-bind="text: singularName"></span>\r\n                        <br />\r\n                        <em data-bind="text: entityState"></em>\r\n                    </td>\r\n                    <td>\r\n                        <a data-bind="text: title, attr: { href: url }"></a>\r\n                    </td>\r\n                </tr>\r\n                <!-- /ko -->\r\n                <!-- /ko -->\r\n            </tbody>\r\n        </table>\r\n    </div>\r\n\r\n    <div class="row" data-bind="visible: notificationDays().length === 0">\r\n        <div class="col-md-8 col-md-offset-2">\r\n            <div class="panel panel-info">\r\n                <div class="panel-heading">\r\n                    <h3 class="panel-title"><span class="glyphicon glyphicon-info-sign"></span><span class="h-margin-left-10px" data-i18n="common.notifications"></span></h3>\r\n                </div>\r\n                <div class="panel-body">\r\n                    <span data-i18n="common.youDontHaveAnyUnsavedEntity"></span>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</section>\r\n';});

define('notifications/notifications',["require", "exports", 'core/messageBox', 'entities/api', 'core/util', 'entities/repo', 'plugins/router', 'entities/core'], function (require, exports, messageBox, entities, util, repo, durandalRouter, core) {
    exports.notificationDays = ko.observableArray([]);
    exports.isSynchronizing = ko.computed(function () {
        return core.isSyncing();
    });
    function save(info) {
        app.busyIndicator.setBusy("Saving...");
        repo.saveInternal(info).fail(function (reason) { return repo.handleSaveChangesFail(reason, durandalRouter); }).finally(function () { return app.busyIndicator.setReady(); }).done();
    }
    exports.save = save;
    function saveAll() {
        return repo.saveAll();
    }
    exports.saveAll = saveAll;
    function revert(info) {
        if (info.entityState === breeze.EntityState.Modified.getName()) {
            messageBox.show('common.revert', 'common.revertPrompt', messageBox.buttons.yesCancel, [info.title]).then(function (dialogResult) {
                if (dialogResult !== messageBox.yes)
                    return;
                app.busyIndicator.setBusy("Reverting...");
                entities.getInstance(info.typeName, info.id).then(function (entityManager) { return entityManager.rejectChanges(); }).finally(function () { return app.busyIndicator.setReady(); }).done();
            });
            return;
        }
        messageBox.show('common.delete', 'common.deleteFromCachePrompt', messageBox.buttons.yesCancel, [info.title]).then(function (dialogResult) {
            if (dialogResult !== messageBox.yes)
                return;
            app.busyIndicator.setBusy("Deleting...");
            entities.removeLocalRootInstance(info.id, info.typeName).finally(function () { return app.busyIndicator.setReady(); }).done();
        });
    }
    exports.revert = revert;
    function revertAll() {
        messageBox.show('common.revert', 'common.revertAllPrompt', messageBox.buttons.yesCancel).then(function (dialogResult) {
            if (dialogResult !== messageBox.yes)
                return;
            var promise = Q.resolve(null);
            app.busyIndicator.setBusy("Reverting...");
            app.notifier.messages().map(function (x) { return x.notificationInfo; }).forEach(function (info) {
                promise = promise.then(function () {
                    if (info.entityState === breeze.EntityState.Modified.getName()) {
                        return entities.getInstance(info.typeName, info.id).then(function (entityManager) { return entityManager.rejectChanges(); });
                    }
                    return entities.removeLocalRootInstance(info.id, info.typeName);
                });
            });
            promise.finally(function () { return app.busyIndicator.setReady(); }).done();
        });
    }
    exports.revertAll = revertAll;
    function updateDays() {
        var day, item, current = moment().add('days', 1), today = moment().startOf('day'), itemDay, diff, description, type, parentType, me = this, days = [];
        app.notifier.messages().map(function (x) { return x.notificationInfo; }).sort(function (a, b) { return util.dateComparison(a.timestamp, b.timestamp); }).forEach(function (item) {
            itemDay = moment(item.timestamp).startOf('day');
            if (itemDay.diff(current, 'days') !== 0) {
                current = itemDay;
                diff = itemDay.diff(today, 'days');
                if (diff === 0)
                    description = 'Today - ';
                else if (diff === -1)
                    description = 'Yesterday - ';
                else
                    description = '';
                description = description + moment(item.timestamp).format('dddd, MMMM Do YYYY');
                day = { description: description, changes: [] };
                days.push(day);
            }
            day.changes.push(item);
        });
        exports.notificationDays(days);
    }
    updateDays();
    var timeoutHandle = 0;
    app.notifier.messages.subscribe(function () {
        clearTimeout(timeoutHandle);
        timeoutHandle = setTimeout(updateDays, 500);
    });
});


define('text!register/register.html',[],function () { return '<section class="container-fluid rootEntityViewModel" data-bind="with: consumerViewModel">\r\n    <div class="command-bar btn-toolbar" role="toolbar">\r\n        <div class="btn-group btn-group-sm">\r\n            <button type="button" class="btn btn-info" data-i18n="common.register"\r\n                    data-bind="click: createNewConsumer, enable: canSave">\r\n                <span class="glyphicon glyphicon-floppy-disk"></span>\r\n            </button>\r\n            <button type="button" class="btn btn-info" data-i18n="common.clear"\r\n                    data-bind="click: clearForm"></button>\r\n        </div>\r\n    </div>\r\n\r\n    <!-- ko compose: \'core/validationSummary.html\' --><!-- /ko -->\r\n\r\n    <div class="content">\r\n        <h3> <span data-i18n="dialog.registerConsumerTitle"></span><span class="hidden-xs">:&nbsp;&nbsp;</span><span class="hidden-xs" data-bind="text: entity.FullName"></span></h3>\r\n        <form role="form" novalidate>\r\n            <fieldset>\r\n                <div class="row">\r\n                    <div class="col-sm-4 form-group" data-bind="visible: propertyMetadata.FirstName.visible">\r\n                        <label for="firstName" data-i18n="consumer.firstName"></label>\r\n                        <input id="firstName" data-bind="value: entity.FirstName, valueUpdate: \'input\', maxlengthPopup: \'\', autocapitalize: true, validateField: \'FirstName\', attr: { maxlength: entity.entityType.getProperty(\'FirstName\').maxLength }, enable: propertyMetadata.FirstName.enable" type="text" class="form-control autofocus" placeholder="Enter first name"\r\n                               autocomplete="off" autocorrect="off" spellcheck="false" />\r\n                    </div>\r\n\r\n                    <div class="col-sm-4 form-group" data-bing="visible: propertyMetadata.MI.visible">\r\n                        <label for="middleInitial" data-i18n="consumer.middleInitial"></label>\r\n                        <input id="middleInitial" data-bind="value: entity.MI, valueUpdate: \'input\', maxlengthPopup: \'\', autocapitalize: true, validateField: \'MI\', attr: { maxlength: entity.entityType.getProperty(\'MI\').maxLength }, enable: propertyMetadata.MI.enable" type="text" class="form-control" placeholder="Enter middle initial"\r\n                               autocomplete="off" autocorrect="off" spellcheck="false" />\r\n                    </div>\r\n\r\n                    <div class="col-sm-4 form-group required" data-bind="visible: propertyMetadata.LastName.visible">\r\n                        <label for="lastName" data-i18n="consumer.lastName"></label>\r\n                        <input id="lastName" data-bind="value: entity.LastName, valueUpdate: \'input\', maxlengthPopup: \'\', autocapitalize: true, validateField: \'LastName\', attr: { maxlength: entity.entityType.getProperty(\'LastName\').maxLength }, enable: propertyMetadata.LastName.enable" type="text" class="form-control" placeholder="Enter last name"\r\n                               autocomplete="off" autocorrect="off" spellcheck="false" />\r\n                    </div>\r\n                </div>\r\n\r\n                <div class="row">\r\n                    <div class="col-sm-4 form-group" data-bind="visible: propertyMetadata.Dob.visible">\r\n                        <label for="dob" data-i18n="consumer.dateOfBirth"></label>\r\n                        <div class="input-group">\r\n                            <input id="dob" class="form-control" type="text" min="1/1/1850" max="12/31/2250" placeholder="Enter date of birth" data-bind="dateValue: entity.Dob, validateField: \'Dob\', enable: propertyMetadata.Dob.enable" />\r\n                            <span class="input-group-btn">\r\n                                <button class="btn" type="button" tabindex="-1"\r\n                                        data-bind="enable: propertyMetadata.Dob.enable">\r\n                                    <span class="glyphicon glyphicon-th"></span>\r\n                                </button>\r\n                            </span>\r\n                        </div>\r\n                    </div>\r\n\r\n                    <div class="col-sm-4 form-group" data-bind="visible: propertyMetadata.Ssn.visible">\r\n                        <label for="ssn" data-i18n="consumer.socialSecurityNumber"></label>\r\n                        <input id="ssn" data-bind="maskedValue: entity.Ssn, valueUpdate: \'input\', validateField: \'Ssn\', attr: { maxlength: entity.entityType.getProperty(\'Ssn\').maxLength }, enable: propertyMetadata.Ssn.enable" type="text" class="form-control" placeholder="Enter social security number"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"\r\n                               data-inputmask="\'mask\': \'000-00-0000\', \'delimiter\': \'-\'" />\r\n                    </div>\r\n                </div>\r\n                <div class="row">\r\n                    <div class="col-sm-4 form-group" data-bind="visible: propertyMetadata.AgencyUuid.visible">\r\n                        <label for="defaultAgency" data-i18n="options.defaultAgency"></label>\r\n                        <!-- ko compose: { \r\n                            model: \'core/adaptiveSelect\',\r\n                            view: propertyLookups.AgencyUuid.length <= typeaheadThreshold ? \'core/standardSelect\' : \'core/typeaheadSelect\',\r\n                            activationData: {\r\n                                elementId: \'defaultAgency\',\r\n                                placeholder: \'Select agency\',\r\n                                lookup: propertyLookups.AgencyUuid,\r\n                                property: entity.AgencyUuid,\r\n                                enable: propertyMetadata.AgencyUuid.enable\r\n                            } \r\n                        } -->\r\n                        <!-- /ko -->\r\n                    </div>\r\n\r\n                    <div class="col-sm-4 form-group">\r\n                        <label for="defaultProvider" data-i18n="options.defaultProvider"></label>\r\n                        <!-- ko compose: { \r\n                            model: \'core/adaptiveSelect\',\r\n                            view: lookups.Providers.length <= typeaheadThreshold ? \'core/standardSelect\' : \'core/typeaheadSelect\',\r\n                            activationData: {\r\n                                elementId: \'defaultProvider\',\r\n                                placeholder: \'Select provider\',\r\n                                lookup: lookups.Providers,\r\n                                property: defaultProviderUuid,\r\n                                enable: true\r\n                            } \r\n                        } -->\r\n                        <!-- /ko -->\r\n                </div>\r\n            </fieldset>\r\n        </form>\r\n\r\n        <div class="panel panel-warning" data-bind="visible: dupeConsumers().length > 0">\r\n            <div class="panel-heading">\r\n                <h3 class="panel-title"><span class="glyphicon glyphicon-warning-sign"></span><span class="h-margin-left-10px" data-i18n="dialog.registerConsumerPotentialDupes"></span></h3>\r\n            </div>\r\n            <div class="panel-body">\r\n                <div class="table-responsive" data-bind="responsiveDropdown: \'\'">\r\n                    <table class="table table-striped table-hover table-condensed">\r\n                        <thead>\r\n                            <tr>\r\n                                <th></th>\r\n                                <th data-i18n="common.id"></th>\r\n                                <th data-i18n="common.name"></th>\r\n                                <th data-i18n="common.phone"></th>\r\n                                <th data-i18n="common.resAddress1"></th>\r\n                                <th data-i18n="common.town"></th>\r\n                            </tr>\r\n                        </thead>\r\n                        <tbody data-bind="foreach: dupeConsumers()">\r\n                            <tr>\r\n                                <td>\r\n                                    <div class=" h-grid-btn-group">\r\n                                        <div class="btn-group">\r\n                                            <a class="btn btn-primary btn-sm" data-bind="attr: { href: \'#consumer/\' + ConsumerUuid }" data-i18n="common.open"></a>\r\n                                            <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">\r\n                                                <span class="caret"></span>\r\n                                            </button>\r\n                                            <ul class="dropdown-menu" role="menu">\r\n                                                <li>\r\n                                                    <a href="#" data-i18n="session.newAssessment"\r\n                                                       data-bind="attr: { href: \'#consumer/\' + ConsumerUuid + \'/session/new\' }"></a>\r\n                                                </li>\r\n                                            </ul>\r\n                                        </div>\r\n                                        <span class="glyphicon glyphicon-cloud-download" data-bind="visible: IsAvailableOffline"></span>\r\n                                    </div>\r\n                                </td>\r\n                                <td data-bind="text: ClientID"></td>\r\n                                <td data-bind="text: FullName"></td>\r\n                                <td data-bind="text: HomePhone"></td>\r\n                                <td data-bind="text: ResAddress1"></td>\r\n                                <td data-bind="text: ResTownName"></td>\r\n                            </tr>\r\n                        </tbody>\r\n                    </table>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</section>\r\n';});

define('register/register',["require", "exports"], function (require, exports) {
    function canActivate() {
        return true;
    }
    exports.canActivate = canActivate;
});


define('text!search/search.html',[],function () { return '<section class="container">\r\n    <!--<ul class="nav nav-pills nav-justified" data-bind="foreach: entityTypeArray">\r\n        <li role="presentation" data-bind="css: { active: $root.entityType() === $data }">\r\n            <a href="#" data-bind="click: $root.selectEntityType.bind($root, $data),\r\n                                   text: $root.getEntityTypeLabel($data)"></a>\r\n        </li>\r\n    </ul>-->\r\n    <label for="search" class="watermark-lg text-muted"\r\n           data-bind="visible: isNullOrEmpty(searchString()), text: getWatermark()">\r\n    </label>\r\n    <div class="input-group">\r\n        <span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span>\r\n        <input type="text" id="search"\r\n               data-bind="value: searchString, valueUpdate: \'input\'"\r\n               class="form-control input-lg autofocus watermarked"\r\n               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n    </div>\r\n\r\n    <div class="table-responsive" data-bind="visible: hasResults, responsiveDropdown: \'\'">\r\n        <table class="table table-striped table-hover table-condensed">\r\n            <thead>\r\n                <tr>\r\n                    <th></th>\r\n                    <th data-i18n="common.id"></th>\r\n                    <!-- ko if: entityType() === entityTypes.DEMOGRAPHIC -->\r\n                    <th data-bind="text: security.getFieldLabel(\'demographics\', \'lastname\'),\r\n                                   visible: security.getFieldVisible(\'demographics\', \'lastname\')"></th>\r\n                    <th data-bind="text: security.getFieldLabel(\'demographics\', \'firstname\'),\r\n                                   visible: security.getFieldVisible(\'demographics\', \'firstname\')"></th>\r\n                    <th data-bind="text: security.getFieldLabel(\'demographics\', \'secid\'),\r\n                                   visible: security.getFieldVisible(\'demographics\', \'secid\')"></th>\r\n                    <th data-bind="text: security.getFieldLabel(\'demographics\', \'ssn\'),\r\n                                   visible: security.getFieldVisible(\'demographics\', \'ssn\')"></th>\r\n                    <th data-bind="text: security.getFieldLabel(\'demographics\', \'dob\'),\r\n                                   visible: security.getFieldVisible(\'demographics\', \'dob\')"></th>\r\n                    <th data-bind="text: security.getFieldLabel(\'demographics\', \'city\'),\r\n                                   visible: security.getFieldVisible(\'demographics\', \'city\')"></th>\r\n                    <th data-bind="text: security.getFieldLabel(\'demographics\', \'rescounty\'),\r\n                                   visible: security.getFieldVisible(\'demographics\', \'rescounty\')"></th>\r\n                    <!-- /ko -->\r\n                    <!-- ko if: entityType() === entityTypes.INQUIRY -->\r\n                    <th>Victim</th>\r\n                    <th>Reporter</th>\r\n                    <!-- /ko -->\r\n                    <!-- ko if: entityType() === entityTypes.Incident -->\r\n                    <th>Victim</th>\r\n                    <th>Reporter</th>\r\n                    <!-- /ko -->\r\n                    <!-- ko if: entityType() === entityTypes.Vendor -->\r\n                    <th>Name</th>\r\n                    <!-- /ko -->\r\n                </tr>\r\n            </thead>\r\n            <tbody data-bind="foreach: results">\r\n                <tr>\r\n                    <td>\r\n                        <div class="h-grid-btn-group">\r\n                            <div class="btn-group">\r\n                                <a class="btn btn-primary btn-sm" data-bind="attr: { href: $root.getOpenUrl.bind($root)($data) }" data-i18n="common.open"></a>\r\n                                <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">\r\n                                    <span class="caret"></span>\r\n                                </button>\r\n                                <ul class="dropdown-menu" role="menu">\r\n                                    <li data-bind="visible: $root.canAddSession.bind($root)($data)">\r\n                                        <a href="#" data-i18n="session.newAssessment"\r\n                                           data-bind="attr: { href: $root.getAddUrl.bind($root)($data) }"></a>\r\n                                    </li>\r\n\r\n                                    <li class="divider" data-bind="visible: !IsAvailableOffline()"></li>\r\n                                    <li><a href="#" data-i18n="common.makeAvailableOffline" data-bind="click: $root.makeAvailableOffline, visible: !IsAvailableOffline()"></a></li>\r\n\r\n                                    <!--<li class="divider" data-bind="visible: $root.canDelete.bind($root)($data)"></li>\r\n                                    <li data-bind="visible: $root.canDelete.bind($root)($data)"><a href="#" data-bind="click: $root.remove.bind($parent)" data-i18n="common.delete"></a></li>-->                                    \r\n                                </ul>\r\n                            </div>\r\n                            <span class="glyphicon glyphicon-cloud-download" data-bind="visible: IsAvailableOffline"></span>\r\n                        </div>\r\n                    </td>\r\n                    <!-- ko if: $root.entityType() === $root.entityTypes.DEMOGRAPHIC -->\r\n                    <td data-bind="text: EntityID"></td>\r\n                    <td data-bind="text: Lastname,\r\n                                   visible: security.getFieldVisible(\'demographics\', \'lastname\')"></td>\r\n                    <td data-bind="text: FirstName,\r\n                                   visible: security.getFieldVisible(\'demographics\', \'firstname\')"></td>\r\n                    <td data-bind="text: SecID,\r\n                                   visible: security.getFieldVisible(\'demographics\', \'secid\')"></td>\r\n                    <td data-bind="ssnText: SSN,\r\n                                   visible: security.getFieldVisible(\'demographics\', \'ssn\')"></td>\r\n                    <td data-bind="text: DOBString,\r\n                                   visible: security.getFieldVisible(\'demographics\', \'dob\')"></td>\r\n                    <td data-bind="text: City,\r\n                                   visible: security.getFieldVisible(\'demographics\', \'city\')"></td>\r\n                    <td data-bind="text: ResCounty,\r\n                                   visible: security.getFieldVisible(\'demographics\', \'rescounty\')"></td>\r\n                    <!-- /ko -->\r\n                    <!-- ko if: $root.entityType() === $root.entityTypes.INQUIRY -->\r\n                    <td data-bind="text: EntityID"></td>\r\n                    <td data-bind="text: VictimName"></td>\r\n                    <td data-bind="text: ReporterName"></td>\r\n                    <!-- /ko -->\r\n                    <!-- ko if: $root.entityType() === $root.entityTypes.Incident -->\r\n                    <td data-bind="text: entityid"></td>\r\n                    <td data-bind="text: VictimName"></td>\r\n                    <td data-bind="text: ReporterName"></td>\r\n                    <!-- /ko -->\r\n                    <!-- ko if: $root.entityType() === $root.entityTypes.Vendor -->\r\n                    <td data-bind="text: VendorID"></td>\r\n                    <td data-bind="text: AGENCY"></td>\r\n                    <!-- /ko -->\r\n                </tr>\r\n            </tbody>\r\n        </table>\r\n    </div>\r\n\r\n    <div data-bind="visible: showNoResultsMessage" class="h-margin-top-10px">\r\n        <span data-i18n="common.unableToFindAnythingMatching"></span><em data-bind="text: searchString"></em>".<span data-bind="if: $root.entityType() === \'consumer\'">  Would you like to <a href="#register">register a new consumer</a>?</span>\r\n    </div>\r\n\r\n    <div data-bind="visible: showNoConnectionMessage()" class="h-margin-top-10px">\r\n        Looks like you\'re offline.  Use the <a href="#downloaded">downloaded</a> tab to access records you\'ve made available offline.<span data-bind="if: $root.entityType() === \'consumer\'">  Use the <a href="#register">register</a> tab to create a new consumer.</span>\r\n    </div>\r\n\r\n</section>\r\n';});

define('search/search',["require", "exports", 'entities/api', 'entities/sync', 'core/util', 'core/messageBox'], function (require, exports, entities, entitySync, util, messageBox) {
    exports.entityTypes = entities.entityTypes;
    exports.entityType = ko.observable(entities.entityTypes.DEMOGRAPHIC);
    exports.entityTypeArray = [
        entities.entityTypes.DEMOGRAPHIC,
        entities.entityTypes.INQUIRY,
        entities.entityTypes.Incident,
        entities.entityTypes.Vendor
    ];
    function getEntityTypeLabel(entityType) {
        var t = entities.getRootType(entityType);
        return security.getPageLabel(t.pageName);
    }
    exports.getEntityTypeLabel = getEntityTypeLabel;
    function getOpenUrl(searchEntity) {
        return '#' + entities.convertToShortName(exports.entityType()) + '/' + getEntityID(searchEntity);
    }
    exports.getOpenUrl = getOpenUrl;
    function getAddUrl(searchEntity) {
        return getOpenUrl(searchEntity) + '/' + entities.convertToShortName(entities.getRootType(exports.entityType()).assessmentType) + '/new';
    }
    exports.getAddUrl = getAddUrl;
    function getWatermark() {
        return 'Search for ' + getEntityTypeLabel(exports.entityType()).toLowerCase() + '...';
    }
    exports.getWatermark = getWatermark;
    function selectEntityType(name) {
        exports.showNoResultsMessage(false);
        exports.showNoConnectionMessage(false);
        exports.results([]);
        exports.entityType(name);
        search();
    }
    exports.selectEntityType = selectEntityType;
    exports.results = ko.observableArray();
    exports.searchString = ko.observable('');
    exports.hasResults = ko.computed(function () { return exports.results().length > 0; });
    exports.showNoResultsMessage = ko.observable(false);
    exports.showNoConnectionMessage = ko.observable(false);
    function getEntityID(entity) {
        switch (exports.entityType()) {
            case entities.entityTypes.DEMOGRAPHIC:
            case entities.entityTypes.INQUIRY:
                return entity.EntityID;
            case entities.entityTypes.Incident:
                return entity.entityid;
            case entities.entityTypes.Vendor:
                return entity.VendorID;
            default:
                throw new Error('Unsupported entity type: ' + entity.entityType.name);
        }
    }
    var throttledSearchString = ko.computed(function () {
        return exports.searchString();
    }).extend({ throttle: 500 });
    exports.searchString.subscribe(function (value) {
        exports.showNoResultsMessage(false);
        exports.showNoConnectionMessage(false);
    });
    throttledSearchString.subscribe(search);
    ko.computed(function () {
        if (app.isOffline()) {
            exports.results([]);
            exports.showNoConnectionMessage(true);
            return;
        }
        else {
            exports.showNoConnectionMessage(false);
            return;
        }
    });
    function search() {
        var _this = this;
        var entityManager, query;
        exports.showNoResultsMessage(false);
        exports.showNoConnectionMessage(false);
        if (exports.searchString().length === 0 || app.isOffline()) {
            if (app.isOffline()) {
                exports.showNoConnectionMessage(true);
            }
            exports.results([]);
            return;
        }
        return entities.createBreezeEntityManager(entities.getRootType(exports.entityType()).controllerName).then(function (em) {
            var query = new breeze.EntityQuery().from('Search').take(100).noTracking(true);
            switch (exports.entityType()) {
                case entities.entityTypes.DEMOGRAPHIC:
                    query = query.withParameters({ query: exports.searchString() });
                    break;
                case entities.entityTypes.INQUIRY:
                    query = query.where(breeze.Predicate.create('VictimName', 'startsWith', exports.searchString()).or('ReporterName', 'startsWith', exports.searchString()));
                    break;
                case entities.entityTypes.Incident:
                    query = query.where(breeze.Predicate.create('VictimName', 'startsWith', exports.searchString()).or('ReporterName', 'startsWith', exports.searchString()));
                    break;
                case entities.entityTypes.Vendor:
                    query = query.where('AGENCY', 'startsWith', exports.searchString());
                    break;
            }
            return em.executeQuery(query);
        }).then(function (data) { return data.results; }).then(function (r) {
            r.forEach(function (x) {
                var id = getEntityID(x), typeName = exports.entityType();
                x['IsAvailableOffline'] = ko.computed(function () { return util.Arrays.any(entitySync.versions(), function (v) { return v.ID === id && equalsIgnoreCase(v.Type, typeName); }); }, _this);
            });
            exports.results(r);
            exports.showNoResultsMessage(r.length === 0 && exports.searchString().length > 0);
        }).fail(function (reason) {
            if (util.isConnectionFailure(reason)) {
                exports.showNoConnectionMessage(true);
                return;
            }
            return Q.reject(reason);
        }).done();
    }
    function makeAvailableOffline(entity) {
        app.busyIndicator.setBusyLoading();
        entitySync.makeConsumerAvailableOffline(getEntityID(entity)).fail(function (reason) {
            if (util.isConnectionFailure(reason)) {
                messageBox.show('common.makeAvailableOffline', 'common.unableToConnect', messageBox.buttons.okOnly);
                return;
            }
            return Q.reject(reason);
        }).finally(function () {
            app.busyIndicator.setReady();
        }).done();
    }
    exports.makeAvailableOffline = makeAvailableOffline;
    function remove(consumer) {
    }
    exports.remove = remove;
    function canDelete(entity) {
        return true;
    }
    exports.canDelete = canDelete;
    function canAddSession(entity) {
        return true;
    }
    exports.canAddSession = canAddSession;
});


define('text!security/ui/SSOLogin.html',[],function () { return '<!DOCTYPE html>\r\n<html lang="en">\r\n<head>\r\n  <meta charset="UTF-8">\r\n  <meta name="viewport" content="width=device-width, initial-scale=1.0">\r\n  <title>Loading Message</title>\r\n  <style>\r\n    body {\r\n      margin: 0;\r\n      padding: 0;\r\n      display: flex;\r\n      justify-content: center;\r\n      align-items: center;\r\n      height: 100vh;\r\n      background-color: #f0f0f0;\r\n    }\r\n\r\n    .message-container {\r\n      background-color: #fff;\r\n      border: 2px solid #ddd;\r\n      border-radius: 8px;\r\n      padding: 20px;\r\n      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);\r\n      text-align: center;\r\n      min-width: 300px;\r\n    }\r\n\r\n    .loading {\r\n      color: #2196F3;\r\n      font-size: 18px;\r\n    }\r\n\r\n    .error {\r\n      font-size: 18px;\r\n    }\r\n  </style>\r\n</head>\r\n<body>\r\n  <div class="message-container" data-bind="visible: !app.busyIndicator.isBusy()">\r\n\r\n    <!-- Display Loading Message -->\r\n    <div data-bind="visible: errorMessage() === undefined || errorMessage() === \'\'" class="loading">Loading...</div>\r\n\r\n    <!-- Display Error Message -->\r\n    <div data-bind="visible: errorMessage() !== undefined && errorMessage() !== \'\'" class="error">\r\n        <span data-bind="text: errorMessage"></span>\r\n        <br><br>\r\n    <button class="btn btn-primary" data-bind="click: logout">Logout</button>\r\n    </div>\r\n  </div>\r\n</body>\r\n</html>\r\n';});

define('security/ui/SSOLogin',["require", "exports", 'security/login'], function (require, exports, login) {
    exports.errorMessage = ko.observable('');
    app.busyIndicator.setBusyLoading();
    login.checkIfAlreadyLoggedIn().fail(function (res) {
        if (res != null && res != undefined && res.Error != '') {
            exports.errorMessage(res.Error);
        }
    }).finally(function () {
        app.busyIndicator.setReady();
    }).done();
    function logout() {
        login.logout();
    }
    exports.logout = logout;
});


define('text!security/ui/login.html',[],function () { return '<section class="container login">\r\n\r\n    <div class="row" data-bind="visible: !hasLicenseError">\r\n        <div class="col-md-6 col-md-offset-3">\r\n            <h2 data-i18n="security.pleaseSignIn"></h2>\r\n\r\n            <form data-bind="submit: submit" role="form" class="form-horizontal">\r\n                <fieldset>\r\n                    <div class="alert alert-warning" data-bind="visible: errorMessage() !== \'\'">\r\n                        <span data-bind="text: errorMessage"></span>\r\n                    </div>\r\n                    <div class="form-group">\r\n                        <input id="userName" data-bind="value: userName, valueUpdate: \'input\', attr: { placeholder: $.i18n.t(\'security.enterUserName\') }" type="text"\r\n                               class="form-control input-lg"\r\n                               autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />\r\n                    </div>\r\n                    <div class="form-group">\r\n                        <input id="password" data-bind="value: password, valueUpdate: \'input\' , attr: { placeholder: $.i18n.t(\'security.enterPassword\') }" type="password"\r\n                               class="form-control input-lg" />\r\n                    </div>                    \r\n                    <button type="submit" class="btn btn-lg btn-primary btn-block" data-i18n="common.submit"></button>\r\n                </fieldset>\r\n            </form>\r\n        </div>\r\n    </div>\r\n\r\n    <div class="row" data-bind="visible: hasLicenseError">\r\n        <h2 data-i18n="app.longName" class="text-center"></h2>\r\n        <div class="col-md-8 col-md-offset-2">\r\n            <div class="panel panel-danger">\r\n                <div class="panel-heading">\r\n                    <h3 class="panel-title"><span class="glyphicon glyphicon-lock"></span><span class="h-margin-left-10px" data-i18n="security.unauthorized"></span></h3>\r\n                </div>\r\n                <div class="panel-body">\r\n                    <p data-i18n="security.yourAccountIsNotAuthorized"></p>\r\n                    <p class="small text-muted" data-bind="text: licenseError"></p>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</section>\r\n';});

define('security/ui/offlineLogin',["require", "exports", 'security/login', 'security/loginHistory', 'durandal/app'], function (require, exports, login, loginHistory, durandalApp) {
    exports.password = "";
    exports.offlineUser = ko.observable(null);
    exports.offlineUsers = null;
    exports.isLoggingIn = ko.observable(false);
    exports.errorMessage = ko.observable('');
    exports.hasOfflineUsers = true;
    exports.usersHasFocus = ko.observable(false);
    if (app.debugUserId && app.debugPassword) {
        exports.password = app.debugPassword;
    }
    function autoOfflineLogin(offlinepwd) {
        exports.password = offlinepwd;
        this.activate();
    }
    exports.autoOfflineLogin = autoOfflineLogin;
    function submit() {
        var _this = this;
        if (this.isLoggingIn())
            return;
        if (typeof exports.offlineUser() === 'undefined' || exports.offlineUser() === null) {
            exports.errorMessage($.i18n.t('security.userIsRequired'));
            return;
        }
        if (typeof exports.password === 'undefined' || exports.password === null || exports.password === '') {
            exports.errorMessage($.i18n.t('security.passwordIsRequired'));
            return;
        }
        this.isLoggingIn(true);
        app.busyIndicator.setBusy($.i18n.t('security.authenticating'));
        exports.errorMessage('');
        login.offlineLogin(exports.offlineUser(), exports.password).then(function (message) {
            durandalApp.setRoot('shell');
        }).fail(function (message) {
            if (message.toString().trim() === 'CORRUPT: ccm: tag doesn\'t match')
                exports.errorMessage($.i18n.t('security.portalPasswordIsInvalid'));
            else
                exports.errorMessage(message);
        }).finally(function () {
            _this.isLoggingIn(false);
            app.busyIndicator.setReady();
        });
    }
    exports.submit = submit;
    function activate() {
        var self = this;
        return loginHistory.getOfflineUsers().then(function (users) { return self.offlineUsers = users; }).fail(function (reason) { return self.offlineUsers = []; }).then(function () {
            self.hasOfflineUsers = self.offlineUsers.length > 0;
            if (self.offlineUsers.length > 0)
                self.offlineUser(self.offlineUsers[0]);
        }).then(function () {
            self.submit();
        });
    }
    exports.activate = activate;
    function compositionComplete(child, parent, settings) {
        $('.form-group', child).on('focusin', function (e) { return $(e.target).closest('.form-group').addClass('focusin'); }).on('focusout', function (e) { return $(e.target).closest('.form-group').removeClass('focusin'); });
    }
    exports.compositionComplete = compositionComplete;
});

define('security/ui/login',["require", "exports", 'security/login', 'core/util', 'durandal/app', 'security/ui/offlineLogin'], function (require, exports, login, util, durandalApp, offlinelogin) {
    exports.userName = "";
    exports.password = "";
    exports.isLoggingIn = ko.observable(false);
    exports.errorMessage = ko.observable('');
    exports.hasLicenseError = false;
    exports.licenseError = null;
    function submit() {
        if (exports.isLoggingIn())
            return;
        if (typeof exports.userName === 'undefined' || exports.userName === null || exports.userName === '') {
            exports.errorMessage($.i18n.t('security.userNameIsRequired'));
            return;
        }
        if (typeof exports.password === 'undefined' || exports.password === null || exports.password === '') {
            exports.errorMessage($.i18n.t('security.passwordIsRequired'));
            return;
        }
        sessionStorage.removeItem('msgBoxSetFocus');
        var pwd = exports.password;
        exports.isLoggingIn(true);
        app.busyIndicator.setBusy($.i18n.t('security.authenticating'));
        exports.errorMessage('');
        var args = new login.LoginArgs(exports.userName, exports.password);
        login.login(args).then(function (message) {
            durandalApp.setRoot('shell');
        }).fail(function (reason) {
            if (reason.Error) {
                exports.errorMessage(reason.Error);
                return;
            }
            if (util.isConnectionFailure(reason)) {
                durandalApp.setRoot('security/ui/offlineLogin');
                offlinelogin.autoOfflineLogin(exports.password);
                return;
            }
            return Q.reject(reason);
        }).finally(function () {
            exports.isLoggingIn(false);
            app.busyIndicator.setReady();
        }).done();
    }
    exports.submit = submit;
    function compositionComplete(child, parent, settings) {
        $('.form-group', child).on('focusin', function (e) { return $(e.target).closest('.form-group').addClass('focusin'); }).on('focusout', function (e) { return $(e.target).closest('.form-group').removeClass('focusin'); });
    }
    exports.compositionComplete = compositionComplete;
    if (app.debugUserId && app.debugPassword) {
        exports.userName = app.debugUserId;
        exports.password = app.debugPassword;
        submit();
    }
});


define('text!security/ui/logoutPage.html',[],function () { return '<html>\r\n<head>\r\n    <title>Logout Success</title>\r\n    <style>\r\n        body {\r\n            font-family: Arial, sans-serif;\r\n            text-align: center;\r\n            padding-top: 100px;\r\n        }\r\n    </style>\r\n</head>\r\n<body>\r\n    <h1>You have been successfully logged out.</h1>\r\n    <p>Kindly close this tab to end your session.</p>\r\n</body>\r\n</html>';});

define('security/ui/logoutPage',["require", "exports"], function (require, exports) {
    exports.displayMessage = ko.observable('');
    exports.displayMessage($.i18n.t('security.sessionLogout'));
});


define('text!security/ui/offlineLogin.html',[],function () { return '<section class="container login">\r\n    <div class="alert alert-info alert-dismissable" data-bind="visible: hasOfflineUsers">\r\n        <button type="button" class="close" data-dismiss="alert" aria-hidden="true" tabindex="99">&times;</button>\r\n        <strong>Looks like you\'re offline.</strong> Not to worry- you can still access consumers and assessments stored on this device.  Your work will automatically be uploaded to Harmony next time you\'re connected.\r\n        <span data-bind="visible: offlineUsers.length > 1"><strong>Choose a profile</strong> and enter your </span>\r\n        <span data-bind="visible: offlineUsers.length === 1">Enter your </span> Harmony password to get started.\r\n    </div>\r\n\r\n    <div class="row" data-bind="visible: hasOfflineUsers">\r\n        <div class="col-md-6 col-md-offset-3">\r\n            <form data-bind="submit: submit" role="form" class="form-horizontal">\r\n                <h2 data-i18n="security.offlineSignIn"></h2>\r\n                <fieldset>\r\n                    <div class="alert alert-warning" data-bind="visible: errorMessage() !== \'\'">\r\n                        <span data-bind="text: errorMessage"></span>\r\n                    </div>\r\n                    <div class="form-group">\r\n                        <div class="form-control h-complex-form-control">\r\n                            <table class="table table-condensed table-hover">\r\n                                <thead>\r\n                                    <tr>\r\n                                        <td data-bind="visible: offlineUsers.length > 1"></td>\r\n                                        <td>User ID</td>\r\n                                    </tr>\r\n                                </thead>\r\n                                <tbody data-bind="foreach: offlineUsers">\r\n                                    <tr data-bind="css: { active: $root.offlineUser() === $data }">\r\n                                        <td data-bind="visible: $root.offlineUsers.length > 1">\r\n                                            <input data-bind="attr: {id: CreateDateTime}, checked: $root.offlineUser, checkedValue: $data" type="radio" name="profile" />\r\n                                        </td>\r\n                                        <td data-bind="click: function() { $root.offlineUser($data); }, clickBubble: false">\r\n                                            <label data-bind="text: UserId.toLowerCase()"></label>\r\n                                        </td>\r\n                                    </tr>\r\n                                </tbody>\r\n                            </table>\r\n                        </div>\r\n                    </div>\r\n                    <div class="form-group">\r\n                        <input id=" password" data-bind="value: password, valueUpdate: \'input\' , attr: { placeholder: $.i18n.t(\'security.enterPassword\') }" type="password"\r\n                               class="form-control input-lg" />\r\n                    </div>\r\n                    <button type="submit" class="btn btn-lg btn-primary btn-block" data-i18n="common.submit"></button>\r\n                </fieldset>\r\n            </form>\r\n        </div>\r\n    </div>\r\n\r\n    <div class="row" data-bind="visible: !hasOfflineUsers">\r\n        <h2 data-i18n="app.longName" class="text-center"></h2>\r\n        <div class="col-md-8 col-md-offset-2">\r\n            <div class="panel panel-danger">\r\n                <div class="panel-heading">\r\n                    <h3 class="panel-title"><span class="glyphicon glyphicon-exclamation-sign"></span><span class="h-margin-left-10px" data-i18n="security.offlineAccess"></span></h3>\r\n                </div>\r\n                <div class="panel-body">\r\n                    <span data-i18n="security.notReadyForOfflineAccess"></span>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</section>\r\n';});


define('text!security/ui/ssoLoginError.html',[],function () { return '<html>\r\n<head>\r\n    <title>Login Error</title>\r\n    <style>\r\n        body {\r\n            font-family: Arial, sans-serif;\r\n            text-align: center;\r\n            padding-top: 100px;\r\n        }\r\n    </style>\r\n</head>\r\n<body>\r\n    <h1 data-bind="text: loginErrorMessage"></h1>\r\n    <p>Please try again later or contact administrator for assistance.</p>\r\n</body>\r\n</html>';});

define('security/ui/ssoLoginError',["require", "exports"], function (require, exports) {
    exports.loginErrorMessage = ko.observable('');
    exports.loginErrorMessage($.i18n.t('security.ssoLoginError'));
});


define('text!security/ui/ssoTimeout.html',[],function () { return '<div class="modal-content messageBox">\r\n    <div class="modal-header">\r\n        <div style="float: right;padding: 3%;border: 1px solid; margin-top: 2%;">\r\n           <b>Time Left:</b>\r\n            <span \r\n            data-bind="text: popupDisplayTimer()"></span>\r\n        </div>\r\n        <h3>Session Expiry</h3>\r\n    </div>\r\n    <div class="modal-body">\r\n        <form data-bind="submit: continueSession">\r\n            <div class="alert alert-warning" data-bind="visible: errorMessage() !== \'\'">\r\n                <span data-bind="text: errorMessage"></span>\r\n            </div>\r\n            <div class="form-group">\r\n                <p class="help-block" data-i18n="security.ssoSessionExpiryWarning"></p>\r\n            </div>\r\n            <br>\r\n            <button type="submit" class="btn btn-primary">Continue working</button>\r\n            &nbsp;\r\n            <button data-bind="click: logout" class="btn btn-secondary">Logout</button>\r\n        </form>\r\n    </div>\r\n</div>';});


define('text!security/ui/unlock.html',[],function () { return '<div class="modal-content messageBox">\r\n    <div class="modal-header">\r\n        <h3>Session Locked</h3>\r\n    </div>\r\n    <div class="modal-body">\r\n        <form data-bind="submit: submit">\r\n            <div class="alert alert-warning" data-bind="visible: errorMessage() !== \'\'">\r\n                <span data-bind="text: errorMessage"></span>\r\n            </div>\r\n            <div class="form-group">\r\n                <label for="password">Enter Password</label>\r\n                <input id="password" type="password" class="form-control autofocus" data-bind="value: password, valueUpdate: \'input\'" />\r\n                <p class="help-block">Enter your password to continue your session.</p>\r\n            </div>\r\n            <button type="submit" class="btn btn-primary">Login</button>\r\n        </form>\r\n    </div>\r\n</div>';});


define('text!shell.html',[],function () { return '<div id="shell">\r\n    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">\r\n        <div class="container-fluid">\r\n            <!-- Brand and toggle get grouped for better mobile display -->\r\n            <div class="navbar-header">\r\n                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#the-collapse">\r\n                    <span class="sr-only">Toggle navigation</span>\r\n                    <span class="icon-bar"></span>\r\n                    <span class="icon-bar"></span>\r\n                    <span class="icon-bar"></span>\r\n                </button>\r\n                <i class="h-logo h-navbar-logo"></i>\r\n            </div>\r\n            <!-- Collect the nav links, forms, and other content for toggling -->\r\n            <div class="collapse navbar-collapse" id="the-collapse">\r\n                <ul class="nav navbar-nav" data-bind="foreach: router.navigationModel">\r\n                    <li data-bind="css: { active: isActive }">\r\n                        <a data-bind="attr: { href: hash }">\r\n                            <span data-bind="attr: { class: iconStyle }"></span>\r\n                            <span data-bind="if: route === \'notifications\'">\r\n                                <span class="bubble" data-bind="text: $parent.notifier.count, visible: $parent.notifier.count() > 0"></span>\r\n                            </span>\r\n                            <span data-bind="html: title"></span>\r\n                        </a>\r\n                    </li>\r\n                </ul>\r\n                <ul class="nav navbar-nav navbar-right">\r\n                    <li class="hidden-sm">\r\n                        <p data-bind="visible: app.isOffline()" class="navbar-text nav-online-status">Offline mode</p>\r\n                    </li>\r\n                    <li>\r\n                        <a href="#" data-bind="click: toggleOffline">\r\n                            <span data-bind="ifnot: app.isOffline">\r\n                                <span class="fa fa-chain-broken"></span>\r\n                                <span>Go offline</span>\r\n                            </span>\r\n                            \r\n                            <!-- Device >=768px <=992px - Hack for Ipad and Android devices -->\r\n                            <span data-bind="if: app.isOffline" class="hidden-xs hidden-md hidden-lg medium-mobile-offline">\r\n                                <span class="fa fa-chain"></span>\r\n                                <span class="go-online">Go online</span>\r\n                                <span class="offline-mode-message">Offline Mode</span>\r\n                            </span>\r\n                            \r\n                            <!-- device > 992px width -->\r\n                            <span data-bind="if: app.isOffline" class="hidden-sm">\r\n                                <span class="fa fa-chain"></span>\r\n                                <span>Go online</span>\r\n                            </span>\r\n                        </a>\r\n                    </li>\r\n                    <li class="dropdown nav-user-infos">\r\n                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" id="user-dropdown">\r\n                            <span class="big-username" data-bind="text: User.Current.UserId.toUpperCase()"></span>\r\n                            <span class="medium-username" data-bind="text: User.Current.UserId.toUpperCase().length > 15 ? User.Current.UserId.toUpperCase().substr(0, 15) + \'...\' : User.Current.UserId.toUpperCase()"></span>\r\n                            <span class="small-username" data-bind="text: User.Current.UserId.toUpperCase().length > 10 ? User.Current.UserId.toUpperCase().substr(0, 10) + \'...\' : User.Current.UserId.toUpperCase()"></span>\r\n                            <b class="caret"></b>\r\n                        </a>\r\n                        <ul class="dropdown-menu">\r\n                            <li data-bind="visible: !app.tabletOrPhone">\r\n                                <a href="#" data-i18n="common.keyboardShortcuts" data-bind="click: showShortcuts"></a>\r\n                            </li>\r\n                            <li><a href="#" data-bind="click: clearData">Clear Data</a></li>\r\n                            <li><a href="#" data-bind="click: logout" data-i18n="security.logoutTitle"></a></li>\r\n                            <!--MHFW-1070 menu item to turn offline mobile assessment tracker on/off-->\r\n                            <li><a id="offlineAssessmentTrackerLink" href="#" data-bind="text: getStartMenu(), click: getClickMenu"></a></li>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \r\n                        </ul>\r\n                    </li>\r\n                </ul>\r\n            </div><!-- /.navbar-collapse -->\r\n        </div><!-- /.container-fluid -->\r\n    </nav>\r\n\r\n    <span data-bind="text: User.Current.Role.Role.Role1 + \'&nbsp;&nbsp;&nbsp;&nbsp;\' + app.shortVersion"\r\n          id="app-version" class="hidden-xs">\r\n    </span>\r\n\r\n    <div id="section-container" class="body" data-bind="router: { cacheViews: false }"></div>\r\n\r\n    <div class="alert h-status-bar" data-bind="fadeVisible: statusBar.hasStatus, css: statusBar.statusClass">\r\n        <span class="glyphicon" data-bind="css: statusBar.iconClass"></span>\r\n        <span data-bind="html: statusBar.message"></span>\r\n    </div>\r\n\r\n    <!--<button id="keyboard-button" class="btn btn-success btn-sm hidden-xs hidden-sm" data-bind="click: showShortcuts">\r\n        Keyboard\r\n    </button>-->\r\n\r\n    <span id="idleTimeout" data-bind="text: moment(\'1900-01-01\').add(app.secondsUntilSessionLocks(), \'seconds\').format(\'m:ss\'), visible: app.secondsUntilSessionLocks() <= 120"></span>\r\n</div>\r\n';});


define('text!unsupportedBrowser.html',[],function () { return '<section class="container">\r\n    <div class="row">\r\n        <h2 data-i18n="app.longName" class="text-center"></h2>\r\n        <div class="col-md-8 col-md-offset-2">\r\n            <div class="panel panel-danger">\r\n                <div class="panel-heading">\r\n                    <h3 class="panel-title"><span class="glyphicon glyphicon-ban-circle"></span><span class="h-margin-left-10px" data-i18n="common.unsupportedBrowserTitle"></span></h3>\r\n                </div>\r\n                <div class="panel-body">\r\n                    <p data-bind="text: yourBrowserIsNotSupportedMessage"></p>\r\n                    <p>Windows/Mac/Linux:</p>\r\n                    <ul>\r\n                        <li>Google Chrome (current version)</li>\r\n                        <li>Edge (current version)</li>\r\n                        <li>Firefox (currrent version)</li>\r\n                        <li>Safari (current version)</li>\r\n                        <li>Internet Explorer 10+</li>\r\n                    </ul>\r\n                    <p>Android:</p>\r\n                    <ul>\r\n                        <li>Google Chrome (current version)</li>\r\n                        <li>Firefox (currrent version)</li>\r\n                    </ul>\r\n                    <p>iOS:</p>\r\n                    <ul>\r\n                        <li>iPhone 5+</li>\r\n                        <li>iPad 4th generation+</li>\r\n                        <li>iPad Mini</li>\r\n                    </ul>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n\r\n    <div class="h-built-with-html5 hidden-xs">\r\n        <div>\r\n            Built with\r\n            <div></div>\r\n            by Harmony Information Systems\r\n            <i class="h-logo"></i>\r\n        </div>\r\n    </div>\r\n</section>';});


define('text!webIntakeShell.html',[],function () { return '<div id="shell">\r\n    <p class="visible-print pull-right" style="margin-bottom: -30px">Reference #:  <strong data-bind="text: sessionEntityManager.entity.OwnerID() == null ? \'(not submitted)\' : (sessionEntityManager.entity.OwnerID() != -1 ? sessionEntityManager.entity.OwnerID() : sessionEntityManager.entity.FundCode())"></strong></p>\r\n\r\n    <div data-bind="compose: { model: assessmentViewModel, view: \'assessments/webIntake.html\', preserveContext: true }, visible: showIntake" />\r\n\r\n    <div class="container" data-bind="visible: !showIntake()">\r\n        <div class="jumbotron">\r\n            <h1 tabindex="0" aria-label="This message has multiple lines. Use the Tab key to navigate." id="txtSuccess" data-bind="event: {\'keydown\' : txtSuccessKeyDownButton}">Success!</h1>\r\n            <p id="txtSuccessMessage2" data-bind="html: WebIntakeSettings.SuccessMessage" tabindex="0"></p>\r\n            <p tabindex="0">Please keep this reference number for your records:  <strong data-bind="text: sessionEntityManager.entity.OwnerID() != -1 ? sessionEntityManager.entity.OwnerID() : sessionEntityManager.entity.FundCode()"></strong></p>\r\n            <p>\r\n                <a id="btnReturnToWellSky" class="btn btn-primary btn-lg" data-bind="text: WebIntakeSettings.ReturnLabel, attr: { href: WebIntakeSettings.ReturnUrl }, click: close" role="button"></a>\r\n                <button type="button" id="btnPrint" class="btn btn-lg" data-bind="visible: !WebIntakeSettings.ReportName, click: print, event: {\'keydown\' : btnPrintOnKeyDown}">\r\n                    <span class="glyphicon glyphicon-print"></span> Print\r\n                </button>\r\n\r\n                <a class="btn btn-lg" id="btnPrintOne" target="_blank" data-bind="attr: { href: printUrl }, visible: !!WebIntakeSettings.ReportName, event: {\'keydown\' : btnPrintOneOnKeyDown}">\r\n                    <span class="glyphicon glyphicon-print"></span> Print\r\n                </a>\r\n            </p>\r\n        </div>\r\n    </div>    \r\n</div>';});

define('webIntakeShell',["require", "exports", 'assessments/assessment', 'entities/api', 'core/messageBox', 'core/constants', 'assessments/consumer-mapper', 'assessments/screen-repo'], function (require, exports, AssessmentViewModel, entities, messageBox, constants, mapper, screenDesignRepo) {
    exports.parentEntityManager;
    exports.sessionEntityManager;
    function activate() {
        var deferred = Q.defer();
        if (app.webIntake) {
            var ownerType = WebIntakeSettings.Type === 'VendorScreen' ? entities.entityTypes.Vendor : entities.entityTypes.INQUIRY;
            var assessmentType = WebIntakeSettings.Type === 'VendorScreen' ? entities.entityTypes.VendorAssessment : entities.entityTypes.InquiryAssessment;
            entities.createInstance(ownerType).then(function (em) {
                exports.parentEntityManager = em;
                em.entity.entityAspect.entityManager['acceptChanges']();
                return entities.createInstance(assessmentType, {});
            }).then(function (em) {
                exports.sessionEntityManager = em;
                exports.sessionEntityManager.entity.ScreenDesignID(WebIntakeSettings.ScreenDesignID);
                exports.sessionEntityManager.parentEntityManager = exports.parentEntityManager;
                exports.assessmentViewModel = new AssessmentViewModel();
                exports.assessmentViewModel.entityManager = exports.sessionEntityManager;
                deferred.resolve(null);
            }).done();
        }
        else if (app.consumerModule) {
            if (app.query.caseno && app.query.assessid) {
                entities.getInstance(entities.entityTypes.DEMOGRAPHIC, app.query.caseno).then(function (em) {
                    exports.parentEntityManager = em;
                    return entities.getInstance(entities.entityTypes.ConsumerAssessment, app.query.assessid);
                }).then(function (em) {
                    exports.sessionEntityManager = em;
                    exports.sessionEntityManager.parentEntityManager = exports.parentEntityManager;
                    exports.assessmentViewModel = new AssessmentViewModel();
                    exports.assessmentViewModel.entityManager = exports.sessionEntityManager;
                    deferred.resolve(null);
                }).done();
            }
            else if (app.query.caseno && app.query.screendesignid) {
                var form;
                screenDesignRepo.getScreenDesign(app.query.screendesignid).then(function (f) { return form = f; }).then(function () { return entities.getInstance(entities.entityTypes.DEMOGRAPHIC, app.query.caseno); }).then(function (em) {
                    exports.parentEntityManager = em;
                    return entities.createInstance(entities.entityTypes.ConsumerAssessment, {});
                }).then(function (em) {
                    exports.sessionEntityManager = em;
                    exports.sessionEntityManager.parentEntityManager = exports.parentEntityManager;
                    em.entity.OwnerID(entities.getEntityId(exports.sessionEntityManager.parentEntityManager.entity));
                    var openid = security.getOpenCloseId(em.parentEntityManager.entity, em.entity.FundCode());
                    if (openid === null) {
                        var errormsg = 'Consumer is not open to fund code "' + (em.entity.FundCode() === null ? '' : em.entity.FundCode()) + '"!';
                        alert(errormsg);
                        console.log(errormsg);
                        throw new Error(errormsg);
                    }
                    em.entity.OpenCloseID(openid);
                    em.entity.ScreenDesignID(form.SCREENDESIGNID);
                    em.entity.Assessment(form.SCREENDESIGNNAME);
                    mapper.mapToAssessment(exports.parentEntityManager.entity, em, form);
                    exports.assessmentViewModel = new AssessmentViewModel();
                    exports.assessmentViewModel.entityManager = exports.sessionEntityManager;
                    deferred.resolve(null);
                }).done();
            }
            else {
                throw new Error('Invalid args');
            }
        }
        else {
            throw new Error('Unknown app mode');
        }
        return deferred.promise.then(addTranslate);
    }
    exports.activate = activate;
    exports.assessmentViewModel;
    exports.isSubmitting = ko.observable(false);
    exports.showIntake = ko.observable(true);
    exports.isSaved = ko.observable(false);
    exports.printUrl = ko.observable("");
    function submit(status) {
        app.busyIndicator.setBusy('Processing...');
        exports.isSubmitting(true);
        if (!exports.assessmentViewModel.validate()) {
            exports.isSubmitting(false);
            app.busyIndicator.setReady();
            return;
        }
        var types = [];
        types.push(entities.entityTypes.InquiryAssessment);
        var entityManager;
        var allinstances = entities.getInstances(types);
        allinstances.forEach(function (manager, index) {
            if (index != 0) {
                entityManager = manager;
                entityManager.entity.Responses().filter(function (r) { return !r.entityAspect.entityState.isDetached(); }).forEach(function (r) {
                    if (!r.isAnswered()) {
                        r.entityAspect.setDeleted();
                    }
                });
                var temp = manager.exportEntities();
                exports.sessionEntityManager.importEntities(temp);
            }
        });
        exports.sessionEntityManager.entity.Status(status);
        exports.sessionEntityManager.saveChanges(true).then(function () {
            exports.showIntake(false);
            exports.isSubmitting(false);
            exports.printUrl(constants.services.breezeServiceBaseUrl + 'Inquiries/PdfReport?id=' + encodeURIComponent(exports.sessionEntityManager.entity['AppType']()));
            exports.isSaved(true);
            app.busyIndicator.setReady();
            $('#txtSuccess').focus();
        }).fail(function (reason) {
            if (reason.entityErrors) {
                exports.isSubmitting(false);
                app.busyIndicator.setReady();
            }
            else {
                return Q.reject(reason);
            }
        }).done();
    }
    exports.submit = submit;
    function saveDraft() {
        submit(WebIntakeSettings.DraftStatus);
    }
    exports.saveDraft = saveDraft;
    function savePending() {
        submit(WebIntakeSettings.PendingStatus);
        if ($('[required-val]').css("display") != "none") {
            $('[required-val]')[0].focus();
        }
        else if ($('[required-par]').css("display") != "none") {
            $('[required-par]')[0].focus();
        }
    }
    exports.savePending = savePending;
    function cancel() {
        sessionStorage.setItem('msgBoxSetFocus', '1');
        messageBox.show('webIntake.cancelTitle', 'webIntake.cancelMessage', [messageBox.no, messageBox.yes], [WebIntakeSettings.CancelConfirmationMessage], [WebIntakeSettings.CancelConfirmationTitle]).then(function (result) {
            $('[reporter-btn-cancel]').focus();
            sessionStorage.removeItem('msgBoxSetFocus');
            if (result !== messageBox.yes) {
                return;
            }
            close();
        }).done();
    }
    exports.cancel = cancel;
    function close() {
        try {
            window.close();
        }
        catch (e) {
            window.location.href = WebIntakeSettings.ReturnUrl;
        }
        return true;
    }
    exports.close = close;
    var textAreaArray;
    function print() {
        window.onbeforeprint = beforePrint;
        window.onafterprint = afterPrint;
        var temp = exports.showIntake();
        exports.showIntake(true);
        window.print();
        exports.showIntake(temp);
    }
    exports.print = print;
    function beforePrint() {
        var allInputs = $("textarea");
        var x = allInputs.length;
        textAreaArray = new Array(x);
        for (var i = 0; i < x; i++) {
            textAreaArray[i] = new Array(4);
        }
        var i = 0;
        for (i = 0; i < allInputs.length; i++) {
            $(allInputs[i]).replaceWith("<span id=" + allInputs[i].id + " style='white-space: pre-wrap;'>" + $('#' + allInputs[i].id).val() + "</span>");
            textAreaArray[i][0] = allInputs[i].id;
            textAreaArray[i][1] = allInputs[i].outerHTML.replace('>Enter response...', '>');
            textAreaArray[i][2] = $('#' + allInputs[i].id).html();
        }
    }
    function afterPrint() {
        var i = 0;
        var y = textAreaArray.length;
        for (i = 0; i < textAreaArray.length; i++) {
            $('#' + textAreaArray[i][0]).replaceWith(textAreaArray[i][1]);
            $('#' + textAreaArray[i][0]).append(textAreaArray[i][2]);
        }
    }
    function addTranslate() {
    }
    function btnPrintOnKeyDown(data, e) {
        if (e.keyCode == 9) {
            $('#txtSuccess').focus();
        }
        if (event.shiftKey && event.keyCode == 9) {
            $('#btnReturnToWellSky').focus();
        }
    }
    exports.btnPrintOnKeyDown = btnPrintOnKeyDown;
    function btnPrintOneOnKeyDown(data, e) {
        if (e.keyCode == 9) {
            $('#txtSuccess').focus();
        }
        if (event.shiftKey && event.keyCode == 9) {
            $('#btnReturnToWellSky').focus();
        }
    }
    exports.btnPrintOneOnKeyDown = btnPrintOneOnKeyDown;
    function txtSuccessKeyDownButton(data, e) {
        if (e.keyCode == 9) {
            $('#txtSuccessMessage2').focus();
        }
        if (event.shiftKey && event.keyCode == 9 && $('#btnPrint').is(':visible')) {
            $('#btnPrint').focus();
        }
        if (event.shiftKey && event.keyCode == 9 && $('#btnPrintOne').is(':visible')) {
            $('#btnPrintOne').focus();
        }
    }
    exports.txtSuccessKeyDownButton = txtSuccessKeyDownButton;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * Enables common http request scenarios.
 * @module http
 * @requires jquery
 * @requires knockout
 */
define('plugins/http',['jquery', 'knockout'], function ($, ko) {
    /**
     * @class HTTPModule
     * @static
     */
    return {
        /**
         * The name of the callback parameter to inject into jsonp requests by default.
         * @property {string} callbackParam
         * @default callback
         */
        callbackParam: 'callback',
        /**
         * Converts the data to JSON.
         * @method toJSON
         * @param {object} data The data to convert to JSON.
         * @return {string} JSON.
         */
        toJSON: function(data) {
            return ko.toJSON(data);
        },
        /**
         * Makes an HTTP GET request.
         * @method get
         * @param {string} url The url to send the get request to.
         * @param {object} [query] An optional key/value object to transform into query string parameters.
         * @param {object} [headers] The data to add to the request header.  It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
         * @return {Promise} A promise of the get response data.
         */
        get: function (url, query, headers) {
            return $.ajax(url, { data: query, headers: ko.toJS(headers) });
        },
        /**
         * Makes an JSONP request.
         * @method jsonp
         * @param {string} url The url to send the get request to.
         * @param {object} [query] An optional key/value object to transform into query string parameters.
         * @param {string} [callbackParam] The name of the callback parameter the api expects (overrides the default callbackParam).
         * @param {object} [headers] The data to add to the request header.  It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
         * @return {Promise} A promise of the response data.
         */
        jsonp: function (url, query, callbackParam, headers) {
            if (url.indexOf('=?') == -1) {
                callbackParam = callbackParam || this.callbackParam;

                if (url.indexOf('?') == -1) {
                    url += '?';
                } else {
                    url += '&';
                }

                url += callbackParam + '=?';
            }

            return $.ajax({
                url: url,
                dataType: 'jsonp',
                data: query,
                headers: ko.toJS(headers)
            });
        },
        /**
         * Makes an HTTP PUT request.
         * @method put
         * @param {string} url The url to send the put request to.
         * @param {object} data The data to put. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
         * @param {object} [headers] The data to add to the request header.  It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
         * @return {Promise} A promise of the response data.
         */
        put:function(url, data, headers) {
            return $.ajax({
                url: url,
                data: this.toJSON(data),
                type: 'PUT',
                contentType: 'application/json',
                dataType: 'json',
                headers: ko.toJS(headers)
            });
        },
        /**
         * Makes an HTTP POST request.
         * @method post
         * @param {string} url The url to send the post request to.
         * @param {object} data The data to post. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
         * @param {object} [headers] The data to add to the request header.  It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
         * @return {Promise} A promise of the response data.
         */
        post: function (url, data, headers) {
            return $.ajax({
                url: url,
                data: this.toJSON(data),
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                headers: ko.toJS(headers)
            });
        },
        /**
         * Makes an HTTP DELETE request.
         * @method remove
         * @param {string} url The url to send the delete request to.
         * @param {object} [query] An optional key/value object to transform into query string parameters.
         * @param {object} [headers] The data to add to the request header.  It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
         * @return {Promise} A promise of the get response data.
         */
        remove:function(url, query, headers) {
            return $.ajax({
                url: url,
                data: query,
                type: 'DELETE',
                headers: ko.toJS(headers)
            });
        }
    };
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * Enables automatic observability of plain javascript object for ES5 compatible browsers. Also, converts promise properties into observables that are updated when the promise resolves.
 * @module observable
 * @requires system
 * @requires binder
 * @requires knockout
 */
define('plugins/observable',['durandal/system', 'durandal/binder', 'knockout'], function(system, binder, ko) {
    var observableModule,
        toString = Object.prototype.toString,
        nonObservableTypes = ['[object Function]', '[object String]', '[object Boolean]', '[object Number]', '[object Date]', '[object RegExp]'],
        observableArrayMethods = ['remove', 'removeAll', 'destroy', 'destroyAll', 'replace'],
        arrayMethods = ['pop', 'reverse', 'sort', 'shift', 'slice'],
        additiveArrayFunctions = ['push', 'unshift'],
        es5Functions = ['filter', 'map', 'reduce', 'reduceRight', 'forEach', 'every', 'some'],
        arrayProto = Array.prototype,
        observableArrayFunctions = ko.observableArray.fn,
        logConversion = false,
        changeDetectionMethod = undefined,
        skipPromises = false,
        shouldIgnorePropertyName;

    /**
     * You can call observable(obj, propertyName) to get the observable function for the specified property on the object.
     * @class ObservableModule
     */

    if (!('getPropertyDescriptor' in Object)) {
        var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
        var getPrototypeOf = Object.getPrototypeOf;

        Object['getPropertyDescriptor'] = function(o, name) {
            var proto = o, descriptor;

            while(proto && !(descriptor = getOwnPropertyDescriptor(proto, name))) {
                proto = getPrototypeOf(proto);
            }

            return descriptor;
        };
    }

    function defaultShouldIgnorePropertyName(propertyName){
        var first = propertyName[0];
        return first === '_' || first === '$' || (changeDetectionMethod && propertyName === changeDetectionMethod);
    }

    function isNode(obj) {
        return !!(obj && obj.nodeType !== undefined && system.isNumber(obj.nodeType));
    }

    function canConvertType(value) {
        if (!value || isNode(value) || value.ko === ko || value.jquery) {
            return false;
        }

        var type = toString.call(value);

        return nonObservableTypes.indexOf(type) == -1 && !(value === true || value === false);
    }

    function createLookup(obj) {
        var value = {};

        Object.defineProperty(obj, "__observable__", {
            enumerable: false,
            configurable: false,
            writable: false,
            value: value
        });

        return value;
    }

    function makeObservableArray(original, observable, hasChanged) {
        var lookup = original.__observable__, notify = true;

        if(lookup && lookup.__full__){
            return;
        }

        lookup = lookup || createLookup(original);
        lookup.__full__ = true;

        es5Functions.forEach(function (methodName) {
            observable[methodName] = function () {
                return arrayProto[methodName].apply(original, arguments);
            };
        });

        observableArrayMethods.forEach(function(methodName) {
            original[methodName] = function() {
                notify = false;
                var methodCallResult = observableArrayFunctions[methodName].apply(observable, arguments);
                notify = true;
                return methodCallResult;
            };
        });

        arrayMethods.forEach(function(methodName) {
            original[methodName] = function() {
                if(notify){
                    observable.valueWillMutate();
                }

                var methodCallResult = arrayProto[methodName].apply(original, arguments);

                if(notify){
                    observable.valueHasMutated();
                }

                return methodCallResult;
            };
        });

        additiveArrayFunctions.forEach(function(methodName){
            original[methodName] = function() {
                for (var i = 0, len = arguments.length; i < len; i++) {
                    convertObject(arguments[i], hasChanged);
                }

                if(notify){
                    observable.valueWillMutate();
                }

                var methodCallResult = arrayProto[methodName].apply(original, arguments);

                if(notify){
                    observable.valueHasMutated();
                }

                return methodCallResult;
            };
        });

        original['splice'] = function() {
            for (var i = 2, len = arguments.length; i < len; i++) {
                convertObject(arguments[i], hasChanged);
            }

            if(notify){
                observable.valueWillMutate();
            }

            var methodCallResult = arrayProto['splice'].apply(original, arguments);

            if(notify){
                observable.valueHasMutated();
            }

            return methodCallResult;
        };

        for (var i = 0, len = original.length; i < len; i++) {
            convertObject(original[i], hasChanged);
        }
    }

    /**
     * Converts an entire object into an observable object by re-writing its attributes using ES5 getters and setters. Attributes beginning with '_' or '$' are ignored.
     * @method convertObject
     * @param {object} obj The target object to convert.
     */
    function convertObject(obj, hasChanged) {
        var lookup, value;

        if (changeDetectionMethod) {
            if(obj && obj[changeDetectionMethod]) {
                if (hasChanged) {
                    hasChanged = hasChanged.slice(0);
                } else {
                    hasChanged = [];
                }
                hasChanged.push(obj[changeDetectionMethod]);
            }
        }

        if(!canConvertType(obj)){
            return;
        }

        lookup = obj.__observable__;

        if(lookup && lookup.__full__){
            return;
        }

        lookup = lookup || createLookup(obj);
        lookup.__full__ = true;

        if (system.isArray(obj)) {
            var observable = ko.observableArray(obj);
            makeObservableArray(obj, observable, hasChanged);
        } else {
            for (var propertyName in obj) {
                if(shouldIgnorePropertyName(propertyName)){
                    continue;
                }

                if (!lookup[propertyName]) {
                    var descriptor = Object.getPropertyDescriptor(obj, propertyName);
                    if (descriptor && (descriptor.get || descriptor.set)) {
                        defineProperty(obj, propertyName, {
                            get:descriptor.get,
                            set:descriptor.set
                        });
                    } else {
                        value = obj[propertyName];

                        if(!system.isFunction(value)) {
                            convertProperty(obj, propertyName, value, hasChanged);
                        }
                    }
                }
            }
        }

        if(logConversion) {
            system.log('Converted', obj);
        }
    }

    function innerSetter(observable, newValue, isArray) {
        //if this was originally an observableArray, then always check to see if we need to add/replace the array methods (if newValue was an entirely new array)
        if (isArray) {
            if (!newValue) {
                //don't allow null, force to an empty array
                newValue = [];
                makeObservableArray(newValue, observable);
            }
            else if (!newValue.destroyAll) {
                makeObservableArray(newValue, observable);
            }
        } else {
            convertObject(newValue);
        }

        //call the update to the observable after the array as been updated.
        observable(newValue);
    }

    /**
     * Converts a normal property into an observable property using ES5 getters and setters.
     * @method convertProperty
     * @param {object} obj The target object on which the property to convert lives.
     * @param {string} propertyName The name of the property to convert.
     * @param {object} [original] The original value of the property. If not specified, it will be retrieved from the object.
     * @return {KnockoutObservable} The underlying observable.
     */
    function convertProperty(obj, propertyName, original, hasChanged) {
        var observable,
            isArray,
            lookup = obj.__observable__ || createLookup(obj);

        if(original === undefined){
            original = obj[propertyName];
        }

        if (system.isArray(original)) {
            observable = ko.observableArray(original);
            makeObservableArray(original, observable, hasChanged);
            isArray = true;
        } else if (typeof original == "function") {
            if(ko.isObservable(original)){
                observable = original;
            }else{
                return null;
            }
        } else if(!skipPromises && system.isPromise(original)) {
            observable = ko.observable();

            original.then(function (result) {
                if(system.isArray(result)) {
                    var oa = ko.observableArray(result);
                    makeObservableArray(result, oa, hasChanged);
                    result = oa;
                }

                observable(result);
            });
        } else {
            observable = ko.observable(original);
            convertObject(original, hasChanged);
        }

        if (hasChanged && hasChanged.length > 0) {
            hasChanged.forEach(function (func) {
                if (system.isArray(original)) {
                    observable.subscribe(function (arrayChanges) {
                        func(obj, propertyName, null, arrayChanges);
                    }, null, "arrayChange");
                } else {
                    observable.subscribe(function (newValue) {
                        func(obj, propertyName, newValue, null);
                    });
                }
            });
        }

        Object.defineProperty(obj, propertyName, {
            configurable: true,
            enumerable: true,
            get: observable,
            set: ko.isWriteableObservable(observable) ? (function (newValue) {
                if (newValue && system.isPromise(newValue) && !skipPromises) {
                    newValue.then(function (result) {
                        innerSetter(observable, result, system.isArray(result));
                    });
                } else {
                    innerSetter(observable, newValue, isArray);
                }
            }) : undefined
        });

        lookup[propertyName] = observable;
        return observable;
    }

    /**
     * Defines a computed property using ES5 getters and setters.
     * @method defineProperty
     * @param {object} obj The target object on which to create the property.
     * @param {string} propertyName The name of the property to define.
     * @param {function|object} evaluatorOrOptions The Knockout computed function or computed options object.
     * @return {KnockoutObservable} The underlying computed observable.
     */
    function defineProperty(obj, propertyName, evaluatorOrOptions) {
        var computedOptions = { owner: obj, deferEvaluation: true },
            computed;

        if (typeof evaluatorOrOptions === 'function') {
            computedOptions.read = evaluatorOrOptions;
        } else {
            if ('value' in evaluatorOrOptions) {
                system.error('For defineProperty, you must not specify a "value" for the property. You must provide a "get" function.');
            }

            if (typeof evaluatorOrOptions.get !== 'function' && typeof evaluatorOrOptions.read !== 'function') {
                system.error('For defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called "get".');
            }

            computedOptions.read = evaluatorOrOptions.get || evaluatorOrOptions.read;
            computedOptions.write = evaluatorOrOptions.set || evaluatorOrOptions.write;
        }

        computed = ko.computed(computedOptions);

        Object.defineProperty(obj, propertyName, {
            configurable: true,
            enumerable: true,
            value: computed
        });

        return convertProperty(obj, propertyName, computed);
    }

    observableModule = function(obj, propertyName){
        var lookup, observable, value;

        if (!obj) {
            return null;
        }

        lookup = obj.__observable__;
        if(lookup){
            observable = lookup[propertyName];
            if(observable){
                return observable;
            }
        }

        value = obj[propertyName];

        if(ko.isObservable(value)){
            return value;
        }

        return convertProperty(obj, propertyName, value);
    };

    observableModule.defineProperty = defineProperty;
    observableModule.convertProperty = convertProperty;
    observableModule.convertObject = convertObject;

    /**
     * Installs the plugin into the view model binder's `beforeBind` hook so that objects are automatically converted before being bound.
     * @method install
     */
    observableModule.install = function(options) {
        var original = binder.binding;

        binder.binding = function(obj, view, instruction) {
            if(instruction.applyBindings && !instruction.skipConversion){
                convertObject(obj);
            }

            original(obj, view);
        };

        logConversion = options.logConversion;
        if (options.changeDetection) {
            changeDetectionMethod = options.changeDetection;
        }

        skipPromises = options.skipPromises;
        shouldIgnorePropertyName = options.shouldIgnorePropertyName || defaultShouldIgnorePropertyName;
    };

    return observableModule;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * Serializes and deserializes data to/from JSON.
 * @module serializer
 * @requires system
 */
define('plugins/serializer',['durandal/system'], function(system) {
    /**
     * @class SerializerModule
     * @static
     */
    return {
        /**
         * The name of the attribute that the serializer should use to identify an object's type.
         * @property {string} typeAttribute
         * @default type
         */
        typeAttribute: 'type',
        /**
         * The amount of space to use for indentation when writing out JSON.
         * @property {string|number} space
         * @default undefined
         */
        space:undefined,
        /**
         * The default replacer function used during serialization. By default properties starting with '_' or '$' are removed from the serialized object.
         * @method replacer
         * @param {string} key The object key to check.
         * @param {object} value The object value to check.
         * @return {object} The value to serialize.
         */
        replacer: function(key, value) {
            if(key){
                var first = key[0];
                if(first === '_' || first === '$'){
                    return undefined;
                }
            }

            return value;
        },
        /**
         * Serializes the object.
         * @method serialize
         * @param {object} object The object to serialize.
         * @param {object} [settings] Settings can specify a replacer or space to override the serializer defaults.
         * @return {string} The JSON string.
         */
        serialize: function(object, settings) {
            settings = (settings === undefined) ? {} : settings;

            if(system.isString(settings) || system.isNumber(settings)) {
                settings = { space: settings };
            }

            return JSON.stringify(object, settings.replacer || this.replacer, settings.space || this.space);
        },
        /**
         * Gets the type id for an object instance, using the configured `typeAttribute`.
         * @method getTypeId
         * @param {object} object The object to serialize.
         * @return {string} The type.
         */
        getTypeId: function(object) {
            if (object) {
                return object[this.typeAttribute];
            }

            return undefined;
        },
        /**
         * Maps type ids to object constructor functions. Keys are type ids and values are functions.
         * @property {object} typeMap.
         */
        typeMap: {},
        /**
         * Adds a type id/constructor function mampping to the `typeMap`.
         * @method registerType
         * @param {string} typeId The type id.
         * @param {function} constructor The constructor.
         */
        registerType: function() {
            var first = arguments[0];

            if (arguments.length == 1) {
                var id = first[this.typeAttribute] || system.getModuleId(first);
                this.typeMap[id] = first;
            } else {
                this.typeMap[first] = arguments[1];
            }
        },
        /**
         * The default reviver function used during deserialization. By default is detects type properties on objects and uses them to re-construct the correct object using the provided constructor mapping.
         * @method reviver
         * @param {string} key The attribute key.
         * @param {object} value The object value associated with the key.
         * @param {function} getTypeId A custom function used to get the type id from a value.
         * @param {object} getConstructor A custom function used to get the constructor function associated with a type id.
         * @return {object} The value.
         */
        reviver: function(key, value, getTypeId, getConstructor) {
            var typeId = getTypeId(value);
            if (typeId) {
                var ctor = getConstructor(typeId);
                if (ctor) {
                    if (ctor.fromJSON) {
                        return ctor.fromJSON(value);
                    }

                    return new ctor(value);
                }
            }

            return value;
        },
        /**
         * Deserialize the JSON.
         * @method deserialize
         * @param {string} text The JSON string.
         * @param {object} [settings] Settings can specify a reviver, getTypeId function or getConstructor function.
         * @return {object} The deserialized object.
         */
        deserialize: function(text, settings) {
            var that = this;
            settings = settings || {};

            var getTypeId = settings.getTypeId || function(object) { return that.getTypeId(object); };
            var getConstructor = settings.getConstructor || function(id) { return that.typeMap[id]; };
            var reviver = settings.reviver || function(key, value) { return that.reviver(key, value, getTypeId, getConstructor); };

            return JSON.parse(text, reviver);
        },
        /**
         * Clone the object.
         * @method clone
         * @param {object} obj The object to clone.
         * @param {object} [settings] Settings can specify any of the options allowed by the serialize or deserialize methods.
         * @return {object} The new clone.
         */
        clone:function(obj, settings) {
            return this.deserialize(this.serialize(obj, settings), settings);
        }
    };
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * Layers the widget sugar on top of the composition system.
 * @module widget
 * @requires system
 * @requires composition
 * @requires jquery
 * @requires knockout
 */
define('plugins/widget',['durandal/system', 'durandal/composition', 'jquery', 'knockout'], function(system, composition, $, ko) {
    var kindModuleMaps = {},
        kindViewMaps = {},
        bindableSettings = ['model', 'view', 'kind'],
        widgetDataKey = 'durandal-widget-data';

    function extractParts(element, settings){
        var data = ko.utils.domData.get(element, widgetDataKey);

        if(!data){
            data = {
                parts:composition.cloneNodes(ko.virtualElements.childNodes(element))
            };

            ko.virtualElements.emptyNode(element);
            ko.utils.domData.set(element, widgetDataKey, data);
        }

        settings.parts = data.parts;
    }

    /**
     * @class WidgetModule
     * @static
     */
    var widget = {
        getSettings: function(valueAccessor) {
            var settings = ko.utils.unwrapObservable(valueAccessor()) || {};

            if (system.isString(settings)) {
                return { kind: settings };
            }

            for (var attrName in settings) {
                if (ko.utils.arrayIndexOf(bindableSettings, attrName) != -1) {
                    settings[attrName] = ko.utils.unwrapObservable(settings[attrName]);
                } else {
                    settings[attrName] = settings[attrName];
                }
            }

            return settings;
        },
        /**
         * Creates a ko binding handler for the specified kind.
         * @method registerKind
         * @param {string} kind The kind to create a custom binding handler for.
         */
        registerKind: function(kind) {
            ko.bindingHandlers[kind] = {
                init: function() {
                    return { controlsDescendantBindings: true };
                },
                update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                    var settings = widget.getSettings(valueAccessor);
                    settings.kind = kind;
                    extractParts(element, settings);
                    widget.create(element, settings, bindingContext, true);
                }
            };

            ko.virtualElements.allowedBindings[kind] = true;
            composition.composeBindings.push(kind + ':');
        },
        /**
         * Maps views and module to the kind identifier if a non-standard pattern is desired.
         * @method mapKind
         * @param {string} kind The kind name.
         * @param {string} [viewId] The unconventional view id to map the kind to.
         * @param {string} [moduleId] The unconventional module id to map the kind to.
         */
        mapKind: function(kind, viewId, moduleId) {
            if (viewId) {
                kindViewMaps[kind] = viewId;
            }

            if (moduleId) {
                kindModuleMaps[kind] = moduleId;
            }
        },
        /**
         * Maps a kind name to it's module id. First it looks up a custom mapped kind, then falls back to `convertKindToModulePath`.
         * @method mapKindToModuleId
         * @param {string} kind The kind name.
         * @return {string} The module id.
         */
        mapKindToModuleId: function(kind) {
            return kindModuleMaps[kind] || widget.convertKindToModulePath(kind);
        },
        /**
         * Converts a kind name to it's module path. Used to conventionally map kinds who aren't explicitly mapped through `mapKind`.
         * @method convertKindToModulePath
         * @param {string} kind The kind name.
         * @return {string} The module path.
         */
        convertKindToModulePath: function(kind) {
            return 'widgets/' + kind + '/viewmodel';
        },
        /**
         * Maps a kind name to it's view id. First it looks up a custom mapped kind, then falls back to `convertKindToViewPath`.
         * @method mapKindToViewId
         * @param {string} kind The kind name.
         * @return {string} The view id.
         */
        mapKindToViewId: function(kind) {
            return kindViewMaps[kind] || widget.convertKindToViewPath(kind);
        },
        /**
         * Converts a kind name to it's view id. Used to conventionally map kinds who aren't explicitly mapped through `mapKind`.
         * @method convertKindToViewPath
         * @param {string} kind The kind name.
         * @return {string} The view id.
         */
        convertKindToViewPath: function(kind) {
            return 'widgets/' + kind + '/view';
        },
        createCompositionSettings: function(element, settings) {
            if (!settings.model) {
                settings.model = this.mapKindToModuleId(settings.kind);
            }

            if (!settings.view) {
                settings.view = this.mapKindToViewId(settings.kind);
            }

            settings.preserveContext = true;
            settings.activate = true;
            settings.activationData = settings;
            settings.mode = 'templated';

            return settings;
        },
        /**
         * Creates a widget.
         * @method create
         * @param {DOMElement} element The DOMElement or knockout virtual element that serves as the target element for the widget.
         * @param {object} settings The widget settings.
         * @param {object} [bindingContext] The current binding context.
         */
        create: function(element, settings, bindingContext, fromBinding) {
            if(!fromBinding){
                settings = widget.getSettings(function() { return settings; }, element);
            }

            var compositionSettings = widget.createCompositionSettings(element, settings);

            composition.compose(element, compositionSettings, bindingContext);
        },
        /**
         * Installs the widget module by adding the widget binding handler and optionally registering kinds.
         * @method install
         * @param {object} config The module config. Add a `kinds` array with the names of widgets to automatically register. You can also specify a `bindingName` if you wish to use another name for the widget binding, such as "control" for example.
         */
        install:function(config){
            config.bindingName = config.bindingName || 'widget';

            if(config.kinds){
                var toRegister = config.kinds;

                for(var i = 0; i < toRegister.length; i++){
                    widget.registerKind(toRegister[i]);
                }
            }

            ko.bindingHandlers[config.bindingName] = {
                init: function() {
                    return { controlsDescendantBindings: true };
                },
                update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                    var settings = widget.getSettings(valueAccessor);
                    extractParts(element, settings);
                    widget.create(element, settings, bindingContext, true);
                }
            };

            composition.composeBindings.push(config.bindingName + ':');
            ko.virtualElements.allowedBindings[config.bindingName] = true;
        }
    };

    return widget;
});

/**
 * Durandal 2.2.0 Copyright (c) 2010-2016 Blue Spire Consulting, Inc. All Rights Reserved.
 * Available via the MIT license.
 * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
 */
/**
 * The entrance transition module.
 * @module entrance
 * @requires system
 * @requires composition
 * @requires jquery
 */
define('transitions/entrance',['durandal/system', 'durandal/composition', 'jquery'], function(system, composition, $) {
    var fadeOutDuration = 100;
    var endValues = {
        left: '0px',
        opacity: 1
    };
    var clearValues = {
        left: '',
        top: '',
        right: '',
        bottom:'',
        position:'',
        opacity: ''
    };

    var isIE = navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/MSIE/);

    var animation = false,
        domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
        elm = document.createElement('div');

    if(elm.style.animationName !== undefined) {
        animation = true;
    }

    if(!animation) {
        for(var i = 0; i < domPrefixes.length; i++) {
            if(elm.style[domPrefixes[i] + 'AnimationName'] !== undefined) {
                animation = true;
                break;
            }
        }
    }

    if(animation) {
        if(isIE){
            system.log('Using CSS3/jQuery mixed animations.');
        }else{
            system.log('Using CSS3 animations.');
        }
    } else {
        system.log('Using jQuery animations.');
    }

    function removeAnimationClasses(ele, fadeOnly){
        ele.classList.remove(fadeOnly ? 'entrance-in-fade' : 'entrance-in');
        ele.classList.remove('entrance-out');
    }

    /**
     * @class EntranceModule
     * @constructor
     */
    var entrance = function(context) {
        return system.defer(function(dfd) {
            function endTransition() {
                dfd.resolve();
            }

            function scrollIfNeeded() {
                if (!context.keepScrollPosition) {
                    $(document).scrollTop(0);
                }
            }

            if (!context.child) {
                $(context.activeView).fadeOut(fadeOutDuration, endTransition);
            } else {
                var duration = context.duration || 500;
                var $child = $(context.child);
                var fadeOnly = !!context.fadeOnly;
                var startValues = {
                    display: 'block',
                    opacity: 0,
                    position: 'absolute',
                    left: fadeOnly || animation ? '0px' : '20px',
                    right: 0,
                    top: 0,
                    bottom: 0
                };

                function startTransition() {
                    scrollIfNeeded();
                    context.triggerAttach();

                    if (animation) {
                        removeAnimationClasses(context.child, fadeOnly);
                        context.child.classList.add(fadeOnly ? 'entrance-in-fade' : 'entrance-in');
                        setTimeout(function () {
                            removeAnimationClasses(context.child, fadeOnly);
                            if(context.activeView){
                                removeAnimationClasses(context.activeView, fadeOnly);
                            }
                            $child.css(clearValues);
                            endTransition();
                        }, duration);
                    } else {
                        $child.animate(endValues, {
                            duration: duration,
                            easing: 'swing',
                            always: function() {
                                $child.css(clearValues);
                                endTransition();
                            }
                        });
                    }
                }

                $child.css(startValues);

                if(context.activeView) {
                    if (animation && !isIE) {
                        removeAnimationClasses(context.activeView, fadeOnly);
                        context.activeView.classList.add('entrance-out');
                        setTimeout(startTransition, fadeOutDuration);
                    } else {
                        $(context.activeView).fadeOut({ duration: fadeOutDuration, always: startTransition });
                    }
                } else {
                    startTransition();
                }
            }
        }).promise();
    };

    return entrance;
});


require(["main"]);
}());;
