if (!String.format) {
    String.format = function (format) {
        var args = Array.prototype.slice.call(arguments, 1);
        return format.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
              ? args[number]
              : match
            ;
        });
    };
}

(function () {
    /**
	 * Decimal adjustment of a number.
	 *
	 * @param	{String}	type	The type of adjustment.
	 * @param	{Number}	value	The number.
	 * @param	{Integer}	exp		The exponent (the 10 logarithm of the adjustment base).
	 * @returns	{Number}			The adjusted value.
	 */
    function decimalAdjust(type, value, exp) {
        // If the exp is undefined or zero...
        if (typeof exp === 'undefined' || +exp === 0) {
            return Math[type](value);
        }
        value = +value;
        exp = +exp;
        // If the value is not a number or the exp is not an integer...
        if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
            return NaN;
        }
        // Shift
        value = value.toString().split('e');
        value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
        // Shift back
        value = value.toString().split('e');
        return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
    }
    // Decimal round
    if (!Math.round10) {
        Math.round10 = function (value, exp) {
            return decimalAdjust('round', value, exp);
        };
    }
    // Decimal floor
    if (!Math.floor10) {
        Math.floor10 = function (value, exp) {
            return decimalAdjust('floor', value, exp);
        };
    }
    // Decimal ceil
    if (!Math.ceil10) {
        Math.ceil10 = function (value, exp) {
            return decimalAdjust('ceil', value, exp);
        };
    }
    Number.prototype.toFixedB = function toFixed(precision) {
        var multiplier = Math.pow(10, precision + 1),
            wholeNumber = Math.floor(this * multiplier);
        return (Math.round(wholeNumber / 10) * 10 / multiplier).toFixed(precision);
    }
    Number.prototype.toFixed10 = function (precision) {
        return Math.round10(this, -precision).toFixed(precision);
    }
})();

function getInternetExplorerVersion() {
    // Returns the version of Internet Explorer or a -1
    // (indicating the use of another browser).
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}
function checkVersion() {
    var msg = "You're not using Internet Explorer.";
    var ver = getInternetExplorerVersion();

    if (ver > -1) {
        if (ver >= 8.0)
            msg = "You're using a recent copy of Internet Explorer."
        else
            msg = "You should upgrade your copy of Internet Explorer.";
    }
}

window.onerror = function (msg, url, line) {
    if (typeof ajaxUrl != 'undefined' && url.indexOf(".js") < 0) {
        url = ajaxUrl.url;
    }

    var ignoreArray = ["Unable to get value of the property 'GetMessage': object is null or undefined", "'window.external' is null or not an object"];

    if ($.inArray(msg, ignoreArray) >= 0)
        return true;

    var exceptionLog = {};
    exceptionLog.IsNew = true;
    exceptionLog.Message = msg;
    exceptionLog.Source = url;
    exceptionLog.StackTrace = line;

    sendException(exceptionLog);
    return true;
};

function sendException(ex, hideMessage) {
    post({
        url: "/Shared/HandleException",
        data: kendo.stringify(ex),
        dataType: "json",
        callback: function (e) {
            if (!hideMessage) showMessage("Error", "Log Reference:" + e.LogID);
        }
    });
}

function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    if (bytes == 0) return '';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    if (i == 0) return bytes + ' ' + sizes[i];
    return Math.ceil((bytes / Math.pow(1024, i)).toFixed(1)) + ' ' + sizes[i];
};

/* Initializes view page's culture and session timeout handler */
function initializeView(timeout, session) {
    // clear session context, if new
    if (session === null) sessionContext.clear();
    else sessionContext.init(session);

    // globalization
    var culture = sessionStorage.getItem("CurrentCulture");
    kendo.culture(culture ? culture : "en-GB");

    // initialize session timeout
    sessionTimeout.init(timeout, session === null);

    // initialize ajax requests
    sessionStorage.setItem("CurrentRequests", null);
};

/* Applise property change event observer. */
function propertyChangeObserver() {
    this.bind("change", function (e) {
        if (e.items) {
            if (e.items.collectionChangeHandler) collectionChangeHandler(e);
        }
        else {
            if (e.field.indexOf(".") > -1) {
                var fields = e.field.split(".");
                for (i = fields.length - 1; i >= 0; i--) {
                    fields.splice(i, 1);
                    var entity = e.sender.get(fields.join("."));
                    if (entity != undefined && entity["IsDirty"] != undefined) {
                        entity.IsDirty = true;
                        break;
                    }
                }
            }
            else {
                if (e.sender != undefined && e.sender["IsDirty"] != undefined)
                    e.sender.IsDirty = true;
            }
        }
    });
}

/* Applies property change event handler. */
function propertyChangeHandler(fields, handler, runOnLoad) {
    this.bind("change", function (e) {
        var f = fields,
            h = handler;

        if ($.inArray(e.field, f) >= 0)
            h(e);
    });

    if (runOnLoad)
        handler({ sender: this });
}

/* Applies collection items change event handler. */
function collectionChangeHandler(e) {
    if (e.action == "remove") {
        if (e.field.indexOf(".Items") > -1) {
            if (!e.sender.get(e.field.substring(0, e.field.indexOf(".Items"))).DeletedItems)
                e.sender.get(e.field.substring(0, e.field.indexOf(".Items"))).DeletedItems = [];

            e.sender.get(e.field.substring(0, e.field.indexOf(".Items"))).DeletedItems.addifnotexists(e.items[0]);
        }
    }
    else if (e.action == "itemchange") {
        e.items[0].IsDirty = true;
    }
}

/* Creates view model for html view binding. */
function createObservable(baseModel, childModel) {
    if (childModel)
        baseModel = extendViewModel(baseModel, childModel);

    if (baseModel.init) baseModel.init();

    var model = kendo.observable(baseModel);

    if (model.setObservable)
        model.setObservable(model);
    else
        model.observable = model;

    model.currentUser = sessionContext.currentUser;
    return model;
}

/* Extends child view model based on base view model's methods-properties. */
function extendViewModel(base, child) {
    for (var i in base) {
        if (!(i in child)) {
            child[i] = base[i];
        }
        else {
            if ($.isFunction(base[i])) {
                child["base_" + i] = base[i];
            }
        }
    }
    return child;
}

/* Extends object a based on object b's methods-properties. */
function extend(e, s, b) {
    if (e == null) e = {};

    if (window[s] !== undefined) s = $.extend(true, {}, window[s]);
    else return;

    //extends object
    for (var i in s) {
        if (!(i in e)) e[i] = s[i];
    }

    //inherits base object, if applicable
    if (b !== undefined) {
        if (window[b] !== undefined) b = $.extend(true, {}, window[b]);
        else return;

        for (var i in b) {
            if (!(i in e)) e[i] = b[i];
            else {
                if ($.isFunction(b[i]))
                    e["base_" + i] = b[i];
            }
        }
    }
}

/* Creates object from the base object extension*/
function extendObject(base) {
    var entity = $.extend(true, {}, base, { UniqueId: getUniqueID(), CreatedDate: new Date(), ModifiedDate: new Date(), IsDirty: true, IsNew: true });

    if (entity.Extend)
        entity.Extend.apply(entity);

    return kendo.observable(entity);
}

/* Extends object and applies entity's Extend function. */
function extendEntity(p, e, s) {
    var entity = p[e];
    if (entity == null) entity = {};

    if (!entity.Extend)
        entity.Extend = s != undefined ? window[s].Extend : window[e].Extend;

    if (!entity.UniqueId)
        entity.UniqueId = getUniqueID();

    entity.Extend.apply(entity);
    entity = kendo.observable(entity);

    if (p instanceof kendo.data.ObservableObject) p.set(e, entity);
    else p[e] = entity;
}

/* Extends collection object and applies each entity's Extend function in the collection arrays. */
function extendCollection(p, c, n) {
    var collection = p[c];
    if (collection == null || !collection.Items)
        collection = kendo.observable($.extend(true, collection, EntityCollection));

    if (!collection.Extend)
        extend(collection, "EntityCollection");

    collection.EntityName = n;
    collection.Extend.apply(collection);

    if (p instanceof kendo.data.ObservableObject) p.set(c, collection);
    else p[c] = collection;
}

function disposeElements(container) {
    var fields = container.find("[data-destroyable]");
    $.each(fields, function (i, v) {
        disposeElement(v);
    });

    fields = $(document.body).find("[data-destroyable]")
    $.each(fields, function (i, v) {
        var parent = $(v).data("parentcontainer");
        if (parent && parent == container[0].id) disposeElement(v);
    });
}

function disposeKendoUIElement(container) {
    var fields = container.find(".k-list-container, .k-widget.k-window")
    $.each(fields, function (i, v) {
        disposeElement(v);
    });
}

function disposeElement(element) {
    var names = ["kendoDropDownList", "kendoWindow", "kendoAutoComplete", "kendoCalendar", "kendoDatePicker", "kendoTreeView", "kendoGrid", "KendoEditor"];
    var elem = $(element);
    $.each(names, function (i, n) {
        if (elem.data(n) && elem.data(n).destroy)
            elem.data(n).destroy();
    });
}

function deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}

function toggleElementsEnabled(element, enabled, options) {
    toggleElementEnabled(element, enabled, options);
    $.each(element.children, function (i, v) {
        toggleElementsEnabled(v, enabled, options);
    });
}

function toggleElementEnabled(element, enabled, options) {
    var roles = ["dropdownlist", "combobox", "datepicker", "numerictextbox", "button", "editor", "multiselect", "upload", "autocomplete"];
    var names = ["kendoDropDownList", "kendoComboBox", "kendoDatePicker", "kendoNumericTextBox", "kendoButton", "KendoEditor", "kendoMultiSelect", "kendoUpload", "kendoAutoComplete"];

    var elem = $(element);
    var idx = $.inArray(elem.data("role"), roles);
    var enable = $.isFunction(enabled) ? enabled(elem) : enabled;
    var applicable = false;

    if (elem.data("permanent-disabled") !== undefined) enable = false;
    if (idx >= 0) {
        if (elem.data(names[idx])) elem.data(names[idx]).enable(enable);
        else if (elem.data("role") == "editor" && elem.data("kendoEditor"))
            $(elem.data("kendoEditor").body).prop("contenteditable", enable);
        applicable = true;
    }
    else if (elem.is("a")) {
        elem.prop("disabled", !enable);
        if (!enable) elem.unbind("click");
        else elem.bind("click");
        applicable = true;
    }
    else if (elem.is("input") || elem.is("textarea")) {
        elem.prop("disabled", !enable);
        applicable = true;
    }

    if (options && applicable) {
        if (options.permanent && !enable && elem.data("permanent-disabled") === undefined)
            elem.data("permanent-disabled", true);
    }
}

function blockViewAccessibility(container, readonly) {
    if (readonly) {
        window.setTimeout(function () {
            $.each(container.children(), function (i, v) {
                toggleElementsEnabled(v, false, { permanent: true });
            });
        }, 500);   //add buffer (500 ms)        
    }
}

function redirectViewHandler(url, options) {
    if (options && options.permissions && !verifyPermissions(options.permissions, sessionContext.currentUser.Permissions)) {
        showMessage(localizedResource.ErrorModalTitle, localizedResource.UnauthorizedAccessMessage);
    }
    else {
        if (options && options.newWindow) {
            options.height = options.height || 1024;
            options.width = options.width || 1000;
            window.open(url, options.title || "", config = 'height=' + options.height + ',width=' + options.width + ', resizable=yes, toolbar=no, menubar=no, location=no, directories=no, status=no');
        }
        else {
            $("#c-page-overlay-dark").show();
            window.location.replace(url);
            if (options && options.downloadFile) $("#c-page-overlay-dark").hide();
        }
    }
}

function loadIntoParent(container, key, url, options) {
    var elementExists = false;
    var callback = options && options.callback ? options.callback : null;

    $.each($(container).children(), function (i, p) {
        if (p.id == key) {
            $(p).show();
            elementExists = true;
        }
        else
            $(p).hide();
    });

    if (!elementExists) {
        var element = $("<div class='c-main-tab-height' id='" + key + "' policy-view></div>").appendTo(container);
        if (callback)
            element.load(url, function () { callback() });
        else
            element.load(url);

        sessionTimeout.start();
    }
    else if (callback)
        callback();
}

function loadPartialViewHandler(element, url, options) {
    var container = $(element);

    if (options && options.dispose)
        disposeElements(container);

    if (options && options.callback)
        container.load(url, function () { options.callback() });
    else
        container.load(url);

    // start session timeout
    sessionTimeout.start();
}

function toggleLoading(arg) {
    var loading = $("#stguk-load");
    $("#stguk-loading").center();
    if (arg) loading.show();
    else loading.hide();
}

function validateAjaxRequest(url) {
    var valid = true;
    var requests = JSON.parse(sessionStorage.getItem("CurrentRequests"));
    if (requests != null) {
        valid = !Enumerable.From(requests).Any(function (x) { return x == url });
        if (valid) {
            requests.addifnotexists(url);
            sessionStorage.setItem("CurrentRequests", JSON.stringify(requests));
        }
    }
    else {
        requests = [];
        requests.addifnotexists(url);
        sessionStorage.setItem("CurrentRequests", JSON.stringify(requests));
    }
    return valid;
}

function clearAjaxRequest(url) {
    var requests = JSON.parse(sessionStorage.getItem("CurrentRequests"));
    if (requests != null) {
        requests.removeItem(url);
        sessionStorage.setItem("CurrentRequests", JSON.stringify(requests));
    }
}

function jsonReplace(key, value) {
    // used to replace the key values on the transaction
    if (key == "ActivityLogCollection" || key == "PolicyHistoryCollection" || key == "ProfileCollection" || key == "AddressCollection")
        return undefined;
    else
        return value;
}

function post(args) {
    if (args.continuousAjaxRequest || validateAjaxRequest(args.url)) { 
        if (args.useSendBeacon === true && navigator.sendBeacon) {
            var beaconResult = navigator.sendBeacon(args.url, new Blob([args.data], { type: 'text/plain; charset=UTF-8' }));

            if (!beaconResult) {
                var client = new XMLHttpRequest();
                client.open("POST", args.url, true);

                client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
                client.send(args.data);

                sleep(2000);
            }
        } else {
            $.ajax({
                async: args.async !== undefined ? args.async : true,
                url: args.url,
                type: "POST",
                dataType: args.dataType,
                data: escapeJson(args.data),
                headers: args.headers,
                beforeSend: function (x, o) {
                    //verify permission, if applicable
                    if (args.permissions && !verifyPermissions(args.permissions, sessionContext.currentUser.Permissions))
                        x.abort(); //cancel unauthorized request (status: canceled)

                    //show loading
                    if (!args.hideLoading)
                        toggleLoading(true);

                    //disable submit element, if applicable
                    if (args.submitElement)
                        toggleElementEnabled(args.submitElement, false);

                    //execute beforesend, if applicable
                    if (args.beforesend)
                        args.beforesend(x, o);
                }
            })
            .done(function (r, s, x) {
                if (r.error)
                    showMessage(localizedResource.ErrorModalTitle, r.error);
                else if (args.callback)
                    args.callback(r);
            })
            .fail(function (x, s, e) {
                if (s === "canceled") showMessage(localizedResource.ErrorModalTitle, localizedResource.UnauthorizedAccessMessage);
                else e ? showMessage(localizedResource.ErrorModalTitle, e.message ? e.message : e) : showMessage(localizedResource.ErrorModalTitle, s);
            })
            .always(function (x, s, e) {
                //clear current request
                clearAjaxRequest(args.url);

                //enable submit element, if applicable
                if (args.submitElement && args.resubmittable)
                    toggleElementEnabled(args.submitElement, true);

                // Restart session timeout, if applicable
                if (sessionTimeout) sessionTimeout.refresh();

                //hide loading
                if (!args.continuous || !args.hideLoading)
                    toggleLoading(false);
            });
        }        
    }
};


function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
} 

/* Converts a virtual (relative) path to an application absolute path. */
function getCotentUrl(path) {
    return window.location.protocol + '//' + window.location.host + '/' + path;
}

/* Generate and return GUID type of string */
function getUniqueID() {
    return kendo.guid().toUpperCase();
}

function dateDiff(d1, d2, includeTime) {
    var date1 = new Date(d1.getTime());
    var date2 = new Date(d2.getTime());

    if (!includeTime) {
        date1 = new Date(d1.getUTCFullYear(), d1.getUTCMonth(), d1.getUTCDate());
        date2 = new Date(d2.getUTCFullYear(), d2.getUTCMonth(), d2.getUTCDate());
    }
    return Math.round((date1 - date2) / 1000 / 86400);
}

function getCurrentDate() {
    var today = new Date();
    today.setHours(0, 0, 0, 0);
    return today;
};

function getNextDate(date) {
    var tomorrow = kendo.parseDate(date);
    tomorrow.setDate(tomorrow.getDate() + 1);
    tomorrow.setHours(0, 0, 0, 0);
    return tomorrow;
};

function getButtonName(value, list) {
    var button = Enumerable.From(list).Where(function (x) {
        return x.Value == value;
    }).FirstOrDefault();

    return button == null ? "" : button.Name;
}

function getUrlVars() {
    var vars = [], hash;
    if (window.location.href.indexOf('?') < 0) return vars;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function isExternalUrl(url) {
    var checkDomain = function (url) {
        if (url.indexOf('//') === 0) { url = location.protocol + url; }
        return url.toLowerCase().replace(/([a-z])?:\/\//, '$1').split('/')[0];
    };
    return ((url.indexOf(':') > -1 || url.indexOf('//') > -1) && checkDomain(location.href) !== checkDomain(url));
}

function formatDate(date, format) {
    return kendo.toString(kendo.parseDate(date), format);
}

function convertDate(a) {
    var re = /(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)/;

    for (var i in a) {
        if (a[i] && a[i].indexOf) {
            if (a[i].match && a[i].match(re)) {
                if (a.set)
                    a.set(i, kendo.parseDate(a[i]));
                else
                    a[i] = kendo.parseDate(a[i]);
            }
        }
    }
    return a;
}

function getFunctionName(fn) {
    var f = typeof fn == 'function';
    var s = f && ((fn.name && ['', fn.name]) || fn.toString().match(/function ([^\(]+)/));
    return (!f && 'not a function') || (s && s[1] || 'anonymous');
}

function nullableValue(e) {
    return e == 0 || e == null;
}

/* Show simple message window */
function showMessage(title, message, handlers) {
    return showDialog({
        title: title,
        message: message,
        dialogResult: handlers ? handlers.callback : null,
        openHandler: handlers ? handlers.open : null,
        IsYesOnly: true
    });
};

function confirmMessage(title, message, callback) {
    return showDialog({
        title: title,
        message: message,
        dialogResult: callback,
        IsYesNo: true,
        IsYesOnly: false
    });
};

/* Construct message using delimeter*/
function parseMessage(message, separator) {
    var m = '',
        array = message.split(separator);
    for (var i = 0; i < array.length; i++)
        m += '<span>' + array[i] + '</span><br><br>';
    return m;
}

function showDialog(options) {
    var name = "Dialog", message = "", width = "460px", height = "165px", align = "center";
    name = getUniqueID();

    if (options.messageAlign) align = options.messageAlign;

    var bindElements = function () {
        $("#btnDialogOk" + name).kendoButton({
            click: function (e) { if (options.dialogResult) options.dialogResult(true); w.Close(); },
            spriteCssClass: "k-icon c-fonts-web-16px k-i-check"
        });
        if (!options.IsYesOnly)
            $("#btnDialogCancel" + name).kendoButton({
                click: function (e) { if (options.dialogResult) options.dialogResult(false); w.Close(); },
                spriteCssClass: "k-icon c-fonts-web-16px k-i-cancel"
            });
    };

    var stringArray = ["<div id='winMessage" + name + "'><table border='0' cellpadding='0' cellspacing='0' class='textshadow' style='margin-left:auto; margin-right:auto;'><tr><td style='height:80px; padding:0px; text-align:" + align + ";'>"];
    stringArray.push(parseMessage(options.message, '||'));

    if (options.windowOptions) {
        width = options.windowOptions.width ? options.windowOptions.width : width;
        height = options.windowOptions.height ? options.windowOptions.height : height;
    }

    if (options.IsYesOnly) {
        stringArray.push("</td></tr><tr><td align='center'><button id='btnDialogOk" + name + "' class='c-darkburgandy-button c-default-button c-unique-button' style='width:100px;'>" + localizedResource.OkLabel + "</button>");
    }

    if (options.IsYesNo == true) {
        stringArray.push("</td></tr><tr><td align='center'><button id='btnDialogOk" + name + "' class='c-darkburgandy-button c-default-button c-unique-button' style='width:100px;'>" + localizedResource.YesLabel + "</button>");
        stringArray.push("<button id='btnDialogCancel" + name + "' class='c-lightGray-button c-default-button' style='width:100px;margin-left:10px;'>" + localizedResource.NoLabel + "</button>");
    }
    stringArray.push("</td></tr></table></div>");

    var w = new dynamicWindow("#" + name, { html: stringArray.join(""), width: width, height: height, title: options.title, actions: {}, open: options.openHandler });
    w.Show();
    bindElements();
    return w;
}

function dynamicWindow(name, options) {
    /********************* Private ***********************/
    if (!$(name)[0])
        $("<div id='" + name.replace('#', '') + "'></div>").appendTo('body');

    var window = $(name);
    var windowOptions = options;
    options.center = true;
    options.visible = false;
    options.resizable = false;
    options.modal = true;
    options.actions = options.actions ? options.actions : ["Close"];
    options.open = options.open ? options.open : function () { this.wrapper.addClass("c-win-fixedHeight") };
    /********************* Public ************************/
    this.Show = function () {
        if (!window.data("kendoWindow")) {
            window.kendoWindow(options);
        }
        else {
            window.data("kendoWindow").setOptions(options).refresh(options.content);
        }

        if (window.data("kendoWindow")) {
            if (options.html) window.data("kendoWindow").content(options.html);

            window.data("kendoWindow").center().open();
        }
    };
    this.Close = function () {
        window.data("kendoWindow").close().destroy();
    }
}

function bindEnterKey(container, handler, condition) {
    //Stop IE9 from submitting form
    container.keypress(function (e) {
        if (e.which == 13) {
            e.preventDefault();
        }
    });
    container.keyup(function (e) {
        if (e.which == 13) {
            if (condition) {
                if (condition()) handler();
            }
            else {
                handler();
            }
        }
    });
}

function setResponsivePanel(selector, options) {
    var panel = $(selector);
    panel.kendoResponsivePanel({
        toggleButton: options && options.togglebutton ? options.togglebutton : ".k-rpanel-toggle",
        orientation: options && options.orientation ? options.orientation : "top",
        breakpoint: options && options.breakpoint ? options.breakpoint : 768,

        open: options && options.openHandler ? options.openHandler : null,
        close: options && options.closeHandler ? options.closeHandler : null
    });

    panel.find("a").click(function (e) {
        e.preventDefault();
        panel.data("kendoResponsivePanel").close();
    });
};

function getDocumentIconCss(filename) {
    var extension = filename.substr((filename.lastIndexOf('.'))).toLowerCase();
    switch (extension) {
        case ".jpg":
        case ".jpeg":
        case ".png":
        case ".gif":
            return "c-c-sky-blue k-i-image";
        case ".doc":
        case ".docx":
            return "c-c-blue k-i-file-word";
        case ".pdf":
            return "c-c-darkred k-i-pdf";
        case ".txt":
            return "k-i-file-txt";
        case ".eml":
            return "c-c-blue k-i-email";
        case ".xlsx":
            return "c-c-darkgreen k-i-file-excel";
        case ".att":
            return "k-insertFile";
        default:
            return "k-i-file-txt";
    }
};

function resizeGrid(grid, wrappers) {
    var containerHeight = wrappers.container ? wrappers.container.height("100%").innerHeight() : grid.height("100%").innerHeight();
    var gridOtherHeight = 0;
    var overheadHeight = 0;

    var topHeight = wrappers.top ? wrappers.top.outerHeight(true) : 0;
    var headerHeight = wrappers.header ? wrappers.header.outerHeight(true) : 0;
    var footerHeight = wrappers.footer ? wrappers.footer.outerHeight(true) : 0;

    $.each(wrappers.overheads, function (k, v) {
        if (v.is(":visible")) overheadHeight += v.outerHeight(true);
    });

    var gridOtherElements = grid.children().not(".k-grid-content");
    gridOtherElements.each(function () {
        gridOtherHeight += $(this).outerHeight();
    });

    var minHeight = parseInt(grid.css('min-height'));
    var newHeight = containerHeight - topHeight - overheadHeight - gridOtherHeight - headerHeight - footerHeight;
    var gridHeight = newHeight + gridOtherHeight;
    if (minHeight > 0 && gridHeight < minHeight) gridHeight = minHeight;

    //re-size grid & grid content height
    grid.children(".k-grid-content").height(gridHeight - gridOtherHeight);
    grid.height(gridHeight);

    // When the window is resized, check the size to determine your classes
    $(window).resize(function () {
        if (($(window).width() >= 1091)) {
            $(".k-grid-pager").removeClass('k-pager-sm k-pager-md k-pager-lg').addClass('c-empty-class');
        }
    });
};

function escapeJson(val) {
    return val ? val.replace(/=/g, encodeURIComponent("=")).replace(/\?/g, encodeURIComponent("?")) : val;  //escapte '=' sign
}

function bindValidatorEvent(validator) {
    validator.elementValidated = function (e, r) {
        if (r.valid) e.unbind("blur.validation");
        else e.bind("blur.validation", function () { validator.validate() });
    };
};

function verifyPermissions(a, c) {
    if (a == null || c == null) return false;
    var permitted = false;
    var permissions = a instanceof Array ? $.map(a, function (n) { return n.toString() }) : a.toString().split(",");
    Enumerable.From(permissions).ForEach(function (p) {
        if ($.inArray(p, c) >= 0) {
            permitted = true;
            return;
        }
    });
    return permitted;
}

function scrollToElement(container, element) {
    container.animate({ scrollTop: element.offset().top / 2 }, 200);
};

function removeElements(container, selector) {
    var elements = container.find(selector);
    $.each(elements, function (i, v) {
        $(v).remove();
    });
};

function bindNumericFieldFocus(element) {
    element.bind("focus", function (e) { if (e.target.value === "0") e.target.value = null });
};

function setCurrency(amount, currencyID) {
    var symbol = getCurrencySymbol(currencyID);
    return kendo.toString(amount == null ? 0 : amount , "c").replace(kendo.culture().numberFormat.currency.symbol, symbol);
}

function getCurrencySymbol(currencyID) {
    var symbol = kendo.culture().numberFormat.currency.symbol;

    switch (currencyID) {
        case CurrenciesEnum.BritishPound:
            symbol = "£"; break;
        case CurrenciesEnum.Euro:
            symbol = "€"; break;
        case CurrenciesEnum.USDollar:
            symbol = "$"; break;
        case CurrenciesEnum.CzechKoruna:
            symbol = "Kč"; break;
        case CurrenciesEnum.HungarianForint:
            symbol = "Ft"; break;
        case CurrenciesEnum.PolishZloty:
            symbol = "zł"; break;
        case CurrenciesEnum.RomanianLei:
            symbol = "lei"; break;
        default:
            symbol = ""; break;
    }

    return symbol;
}

function getCountryCode(countryID) {
    var code = "";
    switch (countryID) {
        case CountryCodesEnum.ENG:
            code = "ENG"; break;
        case CountryCodesEnum.WAL:
            code = "WAL"; break;
        case CountryCodesEnum.SCT:
            code = "SCT"; break;
        case CountryCodesEnum.NIR: 
            code = "NIR"; break;
        case CountryCodesEnum.IOM:
            code = "IOM"; break;
        case CountryCodesEnum.CZE:
            code = "CZE"; break;
        case CountryCodesEnum.HUN: 
            code = "HUN"; break;
        case CountryCodesEnum.ITA: 
            code = "ITA"; break;
        case CountryCodesEnum.POL: 
            code = "POL"; break;
        case CountryCodesEnum.ROU: 
            code = "ROU"; break;
        case CountryCodesEnum.SVK: 
            code = "SVK"; break;
        case CountryCodesEnum.BHS: 
            code = "BHS"; break;
        default:
            code = ""; break;
    }
    return code;
}

/*Jquery Extensions*/
(function ($) {
    $.fn.extend({
        center: function (e) {
            var element = e ? e : window;
            return this.each(function () {
                var top = ($(element).height() - $(this).outerHeight()) / 2;
                var left = ($(element).width() - $(this).outerWidth()) / 2;
                $(this).css({ position: 'absolute', margin: 0, top: (top > 0 ? top : 0) + 'px', left: (left > 0 ? left : 0) + 'px' });
            });
        }
    });
})(jQuery);

/*STL Extensions*/
(function () {
    var contains = function (obj) {
        var i = this.length;
        while (i--) {
            if (this[i] === obj) {
                return true;
            }
            if (this[i].IsEqual && this[i].IsEqual(obj)) {
                return true;
            }
            if (this[i].is && this[i].is(obj)) {
                return true;
            }
        }
        return false;
    };
    var convertAllDateStrings = function () {
        for (var i = 0; i < this.length; i++) {
            convertDate(this[i]);
        }
    }
    var removeAll = function (func) {
        var retArray = [];
        for (var i = this.length - 1; i >= 0; i--) {
            if (!func || func(this[i])) {
                retArray.addRange(this.splice(i, 1));
            }
        }
        return retArray;
    };
    var removeItem = function (obj) {
        for (var i = this.length - 1; i >= 0; i--) {
            if ((this[i] === obj) || (this[i].IsEqual && this[i].IsEqual(obj)) || (this[i].is && this[i].is(obj))) {
                this.splice(i, 1);
            }
        }
    };
    var removeAt = function (uid) {
        for (var i = this.length - 1; i >= 0; i--) {
            if (this[i].UniqueId.toUpperCase() == uid.toUpperCase()) {
                this.splice(i, 1);
                return i;
            }
        }
    };
    var replaceByUid = function (obj) {
        var index = this.removeAt(obj.UniqueId);
        this.splice(index, 0, obj);
    };
    var addRange = function (list) {
        for (var i = 0; i < list.length; i++) {
            this.push(list[i]);
        }
    };
    var addextenditem = function (item, name) {
        if (!item.Extend) {
            item.Extend = window[name].Extend;
            item.Extend.apply(item);
        }
        this.addifnotexists(item);
    };
    var addifnotexists = function (item) {
        if (!this.contains(item)) {
            this.push(item);
        }
        else {
            this.updateItem(item);
        }
    };
    var updateItem = function (item) {
        for (var i = 0; i < this.length; i++) {
            if (this[i].UniqueId != null && this[i].UniqueId.toUpperCase() == item.UniqueId.toUpperCase() && this[i].Update)
                this[i].Update(item);
        }
    };
    var find = function (selector, childProperty) {
        var items = [];
        for (var i = 0; i < this.length; i++) {
            if (this[i].load)
                this[i].load();

            if (selector(this[i]))
                items.push(this[i]);

            items.addRange(this[i][childProperty].find(selector, childProperty));
        }
        return items;
    };
    var extendItems = function (name) {
        for (var i = 0; i < this.length; i++) {
            var e = this[i];
            if (!e.Extend)
                e.Extend = window[name].Extend;

            if (!e.UniqueId)
                e.UniqueId = getUniqueID();

            e.Extend.apply(e);
        }
    };
    var updateItems = function (list, name) {
        for (var i = 0; i < list.length; i++) {
            if (!this[i])
                this.addifnotexists(list[i]);

            var e = this[i];
            if (!e.Extend) {
                e.Extend = window[name].Extend;
                e.Extend.apply(e);
            }

            if (!e.UniqueId)
                e.UniqueId = getUniqueID();

            if (!e.Update)
                e.Update = window[name].Update;

            e.Update(list[i]);
        }
    };
    var toCollection = function () {
        var collection = { Items: [], DeletedItems: [] };

        collection.Items.addRange(this.data());
        if (this._deletedItems)
            collection.DeletedItems.addRange(this._deletedItems);

        return collection;
    };

    /* Apply functions */
    kendo.data.ObservableArray.prototype.convertAllDateStrings = Array.prototype.convertAllDateStrings = convertAllDateStrings;
    kendo.data.ObservableArray.prototype.find = Array.prototype.find = find;
    kendo.data.ObservableArray.prototype.addextenditem = Array.prototype.addextenditem = addextenditem;
    kendo.data.ObservableArray.prototype.addifnotexists = Array.prototype.addifnotexists = addifnotexists;
    kendo.data.ObservableArray.prototype.addRange = Array.prototype.addRange = addRange;
    kendo.data.ObservableArray.prototype.contains = Array.prototype.contains = contains;
    kendo.data.ObservableArray.prototype.removeAt = Array.prototype.removeAt = removeAt;
    kendo.data.ObservableArray.prototype.removeAll = Array.prototype.removeAll = removeAll;
    kendo.data.ObservableArray.prototype.removeItem = Array.prototype.removeItem = removeItem;
    kendo.data.ObservableArray.prototype.updateItem = Array.prototype.updateItem = updateItem;
    kendo.data.ObservableArray.prototype.updateItems = Array.prototype.updateItems = updateItems;
    kendo.data.ObservableArray.prototype.extendItems = Array.prototype.extendItems = extendItems;
    kendo.data.ObservableArray.prototype.replaceByUid = Array.prototype.extendItems = replaceByUid;

    /* Apply collection items change event handler*/
    kendo.data.ObservableArray.prototype.collectionChangeHandler = Array.prototype.collectionChangeHandler = collectionChangeHandler;

    /* Apply property change event observer */
    kendo.data.ObservableObject.prototype.propertyChangeObserver = propertyChangeObserver;
    kendo.data.ObservableArray.prototype.propertyChangeObserver = propertyChangeObserver;
    kendo.data.DataSource.prototype.propertyChangeObserver = propertyChangeObserver;
    kendo.data.DataSource.prototype.toCollection = toCollection;

    /* Apply property change event handlers */
    kendo.data.ObservableObject.prototype.propertyChangeHandler = propertyChangeHandler;
    kendo.data.ObservableArray.prototype.propertyChangeHandler = propertyChangeHandler;
    kendo.data.DataSource.prototype.propertyChangeHandler = propertyChangeHandler;

    Date.prototype.toISOString = function () {
        function pad(n) { return n < 10 ? '0' + n : n }
        return this.getFullYear() + '-'
             + pad(this.getMonth() + 1) + '-'
             + pad(this.getDate()) + 'T'
             + pad(this.getHours()) + ':'
             + pad(this.getMinutes()) + ':'
             + pad(this.getSeconds()) + (this.getTimezoneOffset() > 0 ? '-' : '+')
             + pad((Math.abs(this.getTimezoneOffset()) / 60)) + ':00'
    }
}());


kendo.data.binders.widget.trimValue = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = that.element.element ? that.element.element[0] : that.element;
        var value = that.bindings["trimValue"].get();
        if (value && value.length > 0) {
            that.bindings["trimValue"].set(value.trim());
        }
    },
});

kendo.data.binders.formatText = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = $(that.element);
        var format = elem.data("format");
        var value = that.bindings["formatText"].get();
        var formatted = kendo.toString(value, format);

        if (value) {
            elem.val(formatted);
            if (elem.text) elem.text(formatted);
        }
        else {
            elem.val("");
            if (elem.text) elem.text("");
        }
    }
});

kendo.data.binders.widget.multienabled = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);

        var el = element.element ? element.element[0] : element;
        var that = this;
        var path = bindings["multienabled"].path;
        var source = bindings["multienabled"].source;

        source[el.id + "multienabled"] = new Function("return " + path);

        var regex = /this.([a-z\.]*)/gi;
        var matches, output = [];

        while (matches = regex.exec(path)) {
            output.push(matches[1].replace(".ID", ""));
        }
        source.propertyChangeHandler(output, function (e) { that.refresh.apply(that) });

    },
    refresh: function () {
        var el = this.element.element ? this.element.element[0] : this.element;
        var source = this.bindings["multienabled"].source;
        var value = source[el.id + "multienabled"].apply(source);
        this.enableElement(el, value);
    },
    enableElement: function (element, value) {
        var roles = ["dropdownlist", "datepicker", "numerictextbox"];
        var names = ["kendoDropDownList", "kendoDatePicker", "kendoNumericTextBox"];

        var jqe = $(element);
        var idx = $.inArray(jqe.attr('data-role'), roles);
        if (jqe.data("permanent-disabled") !== undefined) value = false;

        if (idx >= 0) {
            if (jqe.data(names[idx]))
                jqe.data(names[idx]).enable(value);
        }
        else if (jqe.attr('data-role') == "editor") {
            $(jqe.data().kendoEditor.body).attr('contenteditable', value)
        }
        else if (jqe.is("a, div"))
            value ? jqe.show() : jqe.hide();
        else
            jqe.attr('disabled', !value);
    }
});

kendo.data.binders.multienabled = kendo.data.binders.widget.multienabled;

kendo.data.binders.multivisible = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);

        var that = this;
        var elem = that.element.element ? $(that.element.element) : $(that.element)
        var path = that.bindings["multivisible"].path;
        var source = that.bindings["multivisible"].source;

        source[elem[0].id + "multivisible"] = new Function("return " + path); 

        var regex = /this.([a-z\.]*)/gi;
        var matches, output = [];

        while (matches = regex.exec(path)) {
            output.push(matches[1].replace(".ID", ""));
        }
        source.propertyChangeHandler(output, function (e) { that.refresh.apply(that) });
    },
    refresh: function () {
        var that = this;
        var elem = that.element.element ? $(that.element.element) : $(that.element)
        var source = that.bindings["multivisible"].source;
        var value = source[elem[0].id + "multivisible"].apply(source);
        this.showElement(elem, value);
    },
    showElement: function (element, value) {
        if (value)
            element.show();
        else
            element.hide();
    }
});

kendo.data.binders.widget.multivisible = kendo.data.binders.multivisible;

kendo.data.binders.panelEnabled = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = $(that.element);
        var value = that.bindings["panelEnabled"].get();
        if (value) elem.removeClass("ui-state-disabled");
        else elem.addClass("ui-state-disabled");
    }
});

kendo.data.binders.widget.tooltips = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = that.element.element;
        var value = that.bindings["tooltips"].get();
        elem.attr("title", value);
    }
});

kendo.data.binders.tooltips = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = $(that.element);
        var value = that.bindings["tooltips"].get();
        elem.attr("title", value);
    }
});

kendo.data.binders.widget.cssClass = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var role = that.element.element.data("role");
        var cls = that.element.element.data("css-class");
        var elem = that.element.element;

        if (role == "numerictextbox")
            elem = $(that.element._inputWrapper[0].childNodes[0]);

        var value = that.bindings["cssClass"].get();
        if (value)
            elem.addClass(cls);
        else
            elem.removeClass(cls);
    }
});

kendo.data.binders.cssClass = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = $(that.element);
        var cls = elem.data("css-class");
        var value = that.bindings["cssClass"].get();

        if (value) elem.addClass(cls);
        else elem.removeClass(cls);
    }
});

kendo.data.binders.cssStyle = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = $(that.element);
        var value = that.bindings["cssStyle"].get();
        elem.removeClass();
        elem.addClass(value);
    }
});

kendo.data.binders.identity = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = $(that.element);

        var id = elem.attr("id");
        var name = elem.attr("name");
        var value = that.bindings["identity"].get();
        var regex = /-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}/i;

        if (!id || !name || !value) return;
        if (id.match(regex)) id = id.substring(0, id.indexOf(id.match(regex)));
        if (name.match(regex)) name = name.substring(0, name.indexOf(name.match(regex)));

        elem.attr("id", id + "-" + value);
        elem.attr("name", name + "-" + value);
    }
});

kendo.data.binders.widget.identity = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = that.element.element;

        var id = elem.attr("id");
        var name = elem.attr("name");
        var value = that.bindings["identity"].get();
        var regex = /-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}/i;

        if (!id || !name) return;
        if (id.match(regex)) id = id.substring(0, id.indexOf(id.match(regex)));
        if (name.match(regex)) name = name.substring(0, name.indexOf(name.match(regex)));

        elem.attr("id", id + "-" + value);
        elem.attr("name", name + "-" + value);
    }
});

kendo.data.binders.formatDate = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = $(that.element);
        var format = elem.data("format");
        var value = that.bindings["formatDate"].get();
        var formatted = kendo.toString(kendo.parseDate(value), format);

        if (value) {
            elem.val(formatted);
            if (elem.text) elem.text(formatted);
        }
        else {
            elem.val("");
            if (elem.text) elem.text("");
        }
    }
});

kendo.data.binders.selectedItem = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = $(that.element);
        var value = that.bindings["selectedItem"].get();
        var defaultCss = elem.data("defaultcss");
        var menuIndex = elem.data("menu-index");
        var selectedCss = defaultCss + "-selected"
        if (value) {
            if (value == menuIndex) elem.removeClass(defaultCss).addClass(selectedCss);
            else elem.removeClass(selectedCss).addClass(defaultCss);
        }
    }
});

kendo.data.binders.widget.selectedItem = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var elem = that.element.element;
        var value = that.bindings["selectedItem"].get();
        var defaultCss = elem.data("defaultcss");
        var menuIndex = elem.data("menu-index");
        var selectedCss = defaultCss + "-selected"
        if (value) {
            if (value == menuIndex) elem.removeClass(defaultCss).addClass(selectedCss);
            else elem.removeClass(selectedCss).addClass(defaultCss);
        }
    }
});

kendo.data.binders.enabled = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var value = that.bindings["enabled"].get();
        toggleElementsEnabled(that.element, value);
    }
});

kendo.data.binders.widget.enabled = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var value = that.bindings["enabled"].get();
        toggleElementsEnabled(that.element.element[0], value);
    }
});

kendo.data.binders.disabled = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var value = that.bindings["disabled"].get();
        toggleElementsEnabled(that.element, !value);
    }
});

kendo.data.binders.widget.disabled = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var value = that.bindings["disabled"].get();
        toggleElementsEnabled(that.element.element[0], !value);
    }
});

kendo.data.binders.widget.toggleChange = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
    }
});

kendo.data.binders.widget.toggleValue = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
        var that = this;
        that.element.element.on("click", function () {
            that.click();
        });
        that.element.element.on("change", function () {
            that.change();
        });
    },
    refresh: function () {
        var that = this;
        var bindValue = that.bindings["toggleValue"].get();
        var spriteSpan = that.element.element.find("span.k-sprite");
        var checkedClass = "k-icon k-i-check  c-c-burgundyBackground";
        var uncheckedClass = "c-unchecked-checkbutton c-c-whiteBackground";

        if (bindValue) {
            that.element.element.data("sprite-css-class", checkedClass)
            spriteSpan.removeClass(uncheckedClass).addClass(checkedClass);
        }
        else {
            that.element.element.data("sprite-css-class", uncheckedClass)
            spriteSpan.removeClass(checkedClass).addClass(uncheckedClass);
        }
    },
    click: function () {
        var that = this;
        var bindValue = that.bindings["toggleValue"].get();
        that.bindings["toggleValue"].set(!bindValue);
        that.element.element.trigger("change");
    },
    change: function () {
        var that = this;
        that.bindings["toggleChange"].get();
    }
});

kendo.data.binders.widget.buttonValue = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
        var that = this;
        that.element.element.on("click", function () {
            that.click();
        });
    },
    refresh: function () {
        var that = this;
        var buttonSize = that.element.element.data("size");
        var dataValue = that.element.element.data("value");
        var dataValues = that.element.element.data("values");
        var bindValue = that.bindings["buttonValue"].get();

        var selectedClass = "c-Select-RadioButton";
        var unselctedClass = "c-unSelect-RadioButton";

        if (buttonSize) {
            selectedClass = selectedClass + "-" + buttonSize;
            unselctedClass = unselctedClass + "-" + buttonSize;
        }

        if (dataValue != null) {
            if (dataValue != bindValue)
                that.element.element.removeClass(selectedClass).addClass(unselctedClass);
            else
                that.element.element.removeClass(unselctedClass).addClass(selectedClass); //selected
        }
        else if (dataValues != null) {
            if ($.inArray(bindValue.toString(), dataValues.split(",")) == -1)
                hat.element.element.removeClass(selectedClass).addClass("c-unSelect-RadioButton");
            else
                that.element.element.removeClass(unselctedClass).addClass(selectedClass); //selected
        }
    },
    click: function () {
        var that = this;
        var dataValue = that.element.element.data("value");
        var dataValues = that.element.element.data("values");
        var bindValue = that.bindings["buttonValue"].get();

        if (dataValue != null) {
            //set binding value
            that.bindings["buttonValue"].set(dataValue);
        }
        else if (dataValues != null) {
            //set binding values - use first value from data-values array
            that.bindings["buttonValue"].set(dataValues.split(",")[0]);
        }
    }
});

kendo.data.binders.dblclick = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
        var that = this;
        $(that.element).on("dblclick", function (e) {
            that.dblclick();
        });
    },
    refresh: function () {
        var that = this;
    },
    dblclick: function () {
        var that = this;
        return that.bindings["dblclick"].get();
    }
});

kendo.data.binders.widget.dblclick = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
        var that = this;

        if (this.options.name == "ListView") {
            $(this.element.wrapper).off("dblclick").on("dblclick", "div", function (e) {
                return that.bindings["dblclick"].get();
            });
        }
        if (this.options.name == "Grid") {
            $(this.element.wrapper).off("dblclick").on("dblclick", "tr", function (e) {
                return that.bindings["dblclick"].get();
            });
        }
    },
    refresh: function () {
        var that = this;
    }
});

kendo.data.binders.windowModel = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
    }
});

kendo.data.binders.windowInstance = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var actionElement = null;
        var windowElement = $(that.element);
        var source = that.bindings["windowInstance"].get().parent();
        var path = that.bindings["windowInstance"].path;
        var modelpath = that.bindings["windowModel"].path;
        var url = windowElement.data("url");
        var actions = windowElement.data("actions") ? windowElement.data("actions") : ["Close"];

        path = path.substring(path.lastIndexOf('.') + 1);

        var w = windowElement.kendoWindow({
            title: windowElement.data("title"),
            actions: actions,
            resizable: windowElement.data("resizable"),
            visible: windowElement.data("visible"),
            modal: windowElement.data("modal"),
            appendTo: windowElement.data("appendto"),
            width: windowElement.data("width"),
            height: windowElement.data("height"),
            minWidth: windowElement.data("min-width") ? windowElement.data("min-width") : windowElement.data("width"),
            minHeight: windowElement.data("min-height") ? windowElement.data("min-height") : windowElement.data("height"),
            maxWidth: windowElement.data("max-width") ? windowElement.data("max-width") : windowElement.data("width"),
            maxHeight: windowElement.data("max-height") ? windowElement.data("max-height") : windowElement.data("height"),
            refresh: function () {
                if (actionElement && actionElement[0]) toggleElementsEnabled(actionElement[0], false);

                if (window.windowModel) {
                    if (w.data("Params") && windowModel.setParams) windowModel.setParams(w.data("Params"));
                    that.bindings["windowModel"].set(windowModel);
                };

                if (w.data("Title"))
                    w.data("kendoWindow").title(w.data("Title"));

                w.data("kendoWindow").center().open();

                var model = that.bindings["windowModel"].get();
                if (model && model.onWindowRefresh) model.onWindowRefresh();
            },
            activate: function () {
                var model = that.bindings["windowModel"].get();
                if (model && model.onWindowActivate) model.onWindowActivate();
            },
            close: function () {
                var model = that.bindings["windowModel"].get();
                if (model && model.onWindowClose) model.onWindowClose();
                if (actionElement && actionElement[0]) toggleElementsEnabled(actionElement[0], true);

                kendo.unbind($(that.element).find("[window-container]"), model);
                $(that.element).empty();
            },
            resize: function () {
                var model = that.bindings["windowModel"].get();
                if (model && model.onWindowResize) model.onWindowResize();
            }
        });
        w.show = function (e) {
            if (e) actionElement = e;

            if (url)
                w.data("kendoWindow").refresh(url);
            else
                w.data("kendoWindow").refresh();
        };
        w.close = function () {
            w.data("kendoWindow").close();
        };
        source[path] = w;
    }
});

kendo.data.binders.accordion = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var value = that.bindings["accordion"].get();
        var template = kendo.template($("#" + $(that.element).data("template")).html());
        var result = kendo.render(template, value);
        var accordion = kendo.format("<div id='{0}-accordion'>{1}</div>", that.element.id, result);
        $(that.element).html(accordion);
    }
});

kendo.data.binders.permissions = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var element = $(that.element);
        var userPermissions = that.bindings["permissions"].get();
        var permittedActions = element.data("permittedactions");
        var permittedVisibility = element.data("permittedvisibility");
        var hideElement = permittedVisibility != null && permittedVisibility != undefined && !permittedVisibility;
        var permitted = verifyPermissions(permittedActions, userPermissions);

        if (!permitted) {
            if (hideElement) element.hide();
            toggleElementsEnabled(element[0], false, { permanent: true });
        }
    }
});

kendo.data.binders.widget.permissions = kendo.data.Binder.extend({
    init: function (element, bindings, options) {
        kendo.data.Binder.fn.init.call(this, element, bindings, options);
    },
    refresh: function () {
        var that = this;
        var element = that.element.element;
        var userPermissions = that.bindings["permissions"].get();
        var permittedActions = element.data("permittedactions");
        var permittedVisibility = element.data("permittedvisibility");
        var hideElement = permittedVisibility != null && permittedVisibility != undefined && !permittedVisibility;
        var permitted = verifyPermissions(permittedActions, userPermissions);

        if (!permitted) {
            if (hideElement) element.hide();
            toggleElementsEnabled(element[0], false, { permanent: true });
        }
    }
});
(function () {    
    var setResource = function () {
        $.ajax({
            async: false,
            type: "POST",
            url: getCotentUrl("Shared/RetrieveResourseValues"),
            dataType: "json",
            data: JSON.stringify(resources)
        })
            .done(function (data) {

                window.localizedResource = {};

                $.each(data, function (field, value) {
                    window.localizedResource[field] = value;
                });

                //save resource in session storage, if available
                if (sessionStorage) sessionStorage.setItem("LocalizedResource", JSON.stringify(window.localizedResource));
            });
    };

    var getResource = function () {
        if (sessionStorage == undefined || sessionStorage.getItem("LocalizedResource") == null)
            setResource();

        return sessionStorage == undefined ? window.localizedResource : JSON.parse(sessionStorage.getItem("LocalizedResource"));
    };

    var resources = {
        ActivityLogReplyMessage: "ActivityLogReplyMessage",
        CancelLabel: "CancelLabel",
        CommencementDateMessage: "CommencementDateMessage",
        ConfirmationModalTitle: "ConfirmationModalTitle",
        ConfirmReleaseFirmMessage: "ConfirmReleaseFirmMessage",
        ConfirmReleaseTransactionMessage: "ConfirmReleaseTransactionMessage",
        CorrespondenceDownloadMaxSizeExceededMessage: "CorrespondenceDownloadMaxSizeExceededMessage",
        CorrespondenceDownloadQueueLimitMessage: "CorrespondenceDownloadQueueLimitMessage",
        CorrespondencesUploadedMessage: "CorrespondencesUploadedMessage",
        CreatedByLabel: "CreatedByLabel",
        CreatedDateFromLabel: "CreatedDateFromLabel",
        CreatedDateToLabel: "CreatedDateToLabel",
        EndDateErrorMessage: "EndDateErrorMessage",
        EnquirySentMessage: "EnquirySentMessage",
        EnterRefundAmountNessage: "EnterRefundAmountNessage",
        ExistingTaskConfirmationMessage: "ExistingTaskConfirmationMessage",
        ErrorModalTitle: "ErrorModalTitle",
        FirmAddressRemoveConfimrationMessage: "FirmAddressRemoveConfimrationMessage",
        FirmAddressRemoveMessage: "FirmAddressRemoveMessage",
        FirmInactiveMessage: "FirmInactiveMessage",
        FieldRequiredMessage: "FieldRequiredMessage",
        FileOnQueueMessage: "FileOnQueueMessage",
        FirmDuplicateMessage: "FirmDuplicateMessage",
        FirmNotExistMessage: "FirmNotExistMessage",
        IndemnityLimitExceedMessage: "IndemnityLimitExceedMessage",
        IndemnityLimitMinimumMessage: "IndemnityLimitMinimumMessage",
        InformationModalTitle: "InformationModalTitle",        
        InvalidDateMessage: "InvalidDateMessage",
        InvalidFieldMessage: "InvalidFieldMessage",
        InvalidPremiumMessage: "InvalidPremiumMessage",
        InvaidTotalRefundAmountMessage: "InvaidTotalRefundAmountMessage",
        InvoiceCancelledMessage: "InvoiceCancelledMessage",
        InvoiceProductRequiredMessage: "InvoiceProductRequiredMessage",
        IssueFinalPoliciesConfirmMessage: "IssueFinalPoliciesConfirmMessage",
        IssueWithNoCoverNoteMessage: "IssueWithNoCoverNoteMessage",
        ModifiedByLabel: "ModifiedByLabel",
        NewProductRequestEmailSentdMessage: "NewProductRequestEmailSentdMessage",
        NewTaskConfirmationMessage: "NewTaskConfirmationMessage",
        NoCorrespondenceMessage: "NoCorrespondenceMessage",
        NoLabel: "NoLabel",
        OkLabel: "OkLabel",
        WarningModalTitle: "WarningModalTitle",
        YesLabel: "YesLabel",  
        SessionExpiredMessage: "SessionExpiredMessage",
        PasswordResetMessage: "PasswordResetMessage",
        ProductNotExistMessage: "ProductNotExistMessage",
        ProfileResetMessage: "ProfileResetMessage",
        QuestionAnswerCheckedMessage: "QuestionAnswerCheckedMessage",
        QuoteAbortConfirmMessage: "QuoteAbortConfirmMessage",
        QuoteAbortedMessage: "QuoteAbortedMessage",
        QuoteFromLabel: "QuoteFromLabel",
        QuoteNotEditableMessage: "QuoteNotEditableMessage",
        QuoteToLabel: "QuoteToLabel", 
        SearchOverMaxResultsMessage: "SearchOverMaxResultsMessage",
        SearchMostRecentQuotesMessage: "SearchMostRecentQuotesMessage",
        StartDateErrorMessage: "StartDateErrorMessage",
        TaskConfirmationLabel: "TaskConfirmationLabel",
        PolicyRemoveConfirmMessage: "PolicyRemoveConfirmMessage",
        ProfileAccountCreateMessage: "ProfileAccountCreateMessage", 
        PostCodeLengthMessage: "PostCodeLengthMessage",
        PostCodeFormatMessage: "PostCodeFormatMessage",
        CommencementDateIsRequiredMessage: "CommencementDateIsRequiredMessage",
        QuoteDeleteMessage: "QuoteDeleteMessage",
        CoverNoteCancelledMessage: "CoverNoteCancelledMessage",
        ProductCancelledMessage: "ProductCancelledMessage",
        ProfileAdminsMessage: "ProfileAdminsMessage",
        RefundSuccessMessage: "RefundSuccessMessage",
        SessionWillExpireInLabel: "SessionWillExpireInLabel",
        SessionExpiredMessage: "SessionExpiredMessage",
        SessionToExpireMessage: "SessionToExpireMessage",
        NameLabel: "NameLabel",
        AddressLabel: "AddressLabel",
        EmailLabel: "EmailLabel",
        MobileLabel: "MobileLabel",
        PhoneLabel: "PhoneLabel",
        FinalLabel: "FinalLabel",
        DraftLabel: "DraftLabel",
        FinanceAmountGreaterThanChequeMessage: "FinanceAmountGreaterThanChequeMessage",
        FinanceConfirmApplyPaymentMessage: "FinanceConfirmApplyPaymentMessage",
        FinanceNoChequeNumberMessage: "FinanceNoChequeNumberMessage",
        FinanceChequeAmountMessage: "FinanceChequeAmountMessage",
        FinancePleaseEnterCriteriaMessage: "FinancePleaseEnterCriteriaMessage",
        PaymentDeleteSuccessfulMessage: "PaymentDeleteSuccessfulMessage",
        FinancePleaseEnterPaymentCriteriaMessage: "FinancePleaseEnterPaymentCriteriaMessage",
        FinanceConfirmReversePaymentMessage: "FinanceConfirmReversePaymentMessage",
        FinanceConfirmDeletePaymentMessage: "FinanceConfirmDeletePaymentMessage",
        FinanceCannotReverseMessage:"FinanceCannotReverseMessage",
        PaymentReversedSuccessfulMessage: "PaymentReversedSuccessfulMessage",
        PaymentTransferedMessage: "PaymentTransferedMessage",
        ChooseInvoiceToTransferMessage: "ChooseInvoiceToTransferMessage",
        WriteOffAmountAppliedMessage: "WriteOffAmountAppliedMessage",
        PaymentAppliedSuccessfulMessage: "PaymentAppliedSuccessfulMessage",
        FileDirNotSelectedtMessage: "FileDirNotSelectedtMessage",
        DeleteDocumentConfirmMessage: "DeleteDocumentConfirmMessage",
        DeleteFolderConfirmMessage: "DeleteFolderConfirmMessage",
        ConfirmGetQuoteAction: "ConfirmGetQuoteAction",
        DuplicateAddressProduct: "DuplicateAddressProduct",
        ConfirmChangeBespokeMessage: "ConfirmChangeBespokeMessage",
        ConfirmProcessInternally: "ConfirmProcessInternally",
        OrderedPolicyCannotRemoveMessage: "OrderedPolicyCannotRemoveMessage",
        DraftDeleteConfirmMessage: "DraftDeleteConfirmMessage",
        ExclusiveProductSelectionMessage: "ExclusiveProductSelectionMessage",
        SameGroupCoverageRiskSelectedMessage: "SameGroupCoverageRiskSelectedMessage",
        FinalizeDraftConfirmMessage: "FinalizeDraftConfirmMessage",
        IndemnityLimitMinimumMessage: "IndemnityLimitMinimumMessage",
        IndemnityLimitMaximumMessage: "IndemnityLimitMaximumMessage",
        ReinsuredNotGreaterThanIndemnityLimitMessage: "ReinsuredNotGreaterThanIndemnityLimitMessage",
        PremiumRequiredMessage: "PremiumRequiredMessage",
        ProductRequiredMessage:"ProductRequiredMessage",
        NoUnorderedProductsMessage: "NoUnorderedProductsMessage",
        EndorsementIssueddMessage: "EndorsementIssueddMessage",
        EndorsementCancelledMessage: "EndorsementCancelledMessage",
        UndoDraftConfirmMessage: "UndoDraftConfirmMessage",
        ReportLabel: "ReportLabel",
        FolderLabel: "FolderLabel",
        AllowClientEditMessage: "AllowClientEditMessage",
        SearchCommencementDateMessage: "SearchCommencementDateMessage",
        NonSearchCommencementDateMessage: "NonSearchCommencementDateMessage",
        MixSearchCommencementDateMessage: "MixSearchCommencementDateMessage",
        LinkedReportLabel: "LinkedReportLabel",
        PleaseClearFlagsMessage:"PleaseClearFlagsMessage",
        QuickQuoteReferredMessage: "QuickQuoteReferredMessage",
        NewFolderLabel: "NewFolderLabel",
        BlockReturnUploadedMessage: "BlockReturnUploadedMessage",
        PleaseChooseLabel: "PleaseChooseLabel",
        ContactSavedMessage: "ContactSavedMessage",
        AssumptionLookupLabel: "AssumptionLookupLabel",
        RequirementLookupLabel: "RequirementLookupLabel",
        AssumptionPromptLabel: "AssumptionPromptLabel",
        RequirementPromptLabel: "RequirementPromptLabel",
        FirmChangeSaveMessage: "FirmChangeSaveMessage",
        FileUsedByLabel: "FileUsedByLabel",
        TypeAssumptionDescriptionLabel: "TypeAssumptionDescriptionLabel",
        TypeRequirementDescriptionLabel: "TypeRequirementDescriptionLabel",
        ArRecordRemoveConfirmation: "ArRecordRemoveConfirmation",
        CorrespondenceUnderwritterSignature:"CorrespondenceUnderwritterSignature",
        QuoteEmailSentMessage: "QuoteEmailSentMessage",
        OfficeAddressCountToolTip: "OfficeAddressCountToolTip",
        DuplicateContactMessage: "DuplicateContactMessage",
        ImportedSuccessMessage: "ImportedSuccessMessage",
        HasBeenImportedBeforeMessage: "HasBeenImportedBeforeMessage",
        RecordAmountNotMatchingDetails: "RecordAmountNotMatchingDetails",
        RecordAmountNotMatchingDetails: "RecordAmountNotMatchingDetails",
        ClientRegistrationConfirmationMessage: "ClientRegistrationConfirmationMessage",
        BlockImportErrorMessage: "BlockImportErrorMessage",
        UnauthorizedAccessMessage: "UnauthorizedAccessMessage",
        BlockImportErrorMessage: "BlockImportErrorMessage",
        RiskSummaryDeleteMessage: "RiskSummaryDeleteMessage",
        ForgotPasswordMessage: "ForgotPasswordMessage",
        CommissionLimitMessage: "CommissionLimitMessage",
        DevelopmentOptionMessage: "DevelopmentOptionMessage",
        ForgotPasswordMessage: "ForgotPasswordMessage",
        CorrespondenceEmailFooter: "CorrespondenceEmailFooter",
        IndemnityLimitQuickQuoteLimitMessage: "IndemnityLimitQuickQuoteLimitMessage",        
        SelectUploadFolderMessage: "SelectUploadFolderMessage",
        StewartUKPhoneNumber: "StewartUKPhoneNumber",
        IssueFinalPolicyMessage: "IssueFinalPolicyMessage",
        InvalidCriteriaFirmMessage:"InvalidCriteriaFirmMessage",
        EmailSTLReferenceLabel: "EmailSTLReferenceLabel",
        ConfirmDeleteCorrespondenceMessage:"ConfirmDeleteCorrespondenceMessage",
        TypeFirmNameToSearchAndSelectLabel: "TypeFirmNameToSearchAndSelectLabel",
        SelectUploadFolderMessage: "SelectUploadFolderMessage",
        CancelQuoteConfirmMessage: "CancelQuoteConfirmMessage",
        PleaseSelectInvoiceToPayMessage:"PleaseSelectInvoiceToPayMessage",
        AddressLookUpMessage: "AddressLookUpMessage",
        AddressesForLabel: "AddressesForLabel",
        AddQuoteLabel: "AddQuoteLabel",
        NumberOfProductLimitMessage: "NumberOfProductLimitMessage",
        EntityNotSavedMessage: "EntityNotSavedMessage",
        BlockPolicyCountErrorMessage: "BlockPolicyCountErrorMessage",
        ClientRegistrationFailedMessage: "ClientRegistrationFailedMessage",
        RecaptchaFailedMessage: "RecaptchaFailedMessage",
        EmailNotMatchingMessage: "EmailNotMatchingMessage",
        ValidEmailListMessage: "ValidEmailListMessage",        
        PolicyConvertToBespokeMessage: "PolicyConvertToBespokeMessage",
        EmailReferenceLabel: "EmailReferenceLabel",
        EmailReferenceLabel2: "EmailReferenceLabel2",
        NoFinalDraftBeforeIssuing:"NoFinalDraftBeforeIssuing",
        YourRefNoLabel: "YourRefNoLabel",
        BroswerSupportMessage:"BroswerSupportMessage",
        ConfirmationOfQuoteLabel: "ConfirmationOfQuoteLabel",
        DocumentNotFoundMessage: "DocumentNotFoundMessage",
        DocumentInUseMessage: "DocumentInUseMessage",
        FirmEditedByLabel: "FirmEditedByLabel",
        ContactEditedByLabel: "ContactEditedByLabel",
        PolicyEndorsementCommencementDateValidationMessage: "PolicyEndorsementCommencementDateValidationMessage",
        PleaseSelectPolicyStatusReasonLabel: "PleaseSelectPolicyStatusReasonLabel",
        PolicyStatusChangeNoteMessage: "PolicyStatusChangeNoteMessage",
        PleaseChoosePolicyTypeMessage: "PleaseChoosePolicyTypeMessage",
        PremiumIsOverriddenMessage:"PremiumIsOverriddenMessage",
        DeleteFileConfirmationLabel: "DeleteFileConfirmationLabel",
        NonCreditWithCrecitialsMessage: "NonCreditWithCrecitialsMessage",
        CreateCorrespondenceLabel: "CreateCorrespondenceLabel",
        InvoiceCancelMessage: "InvoiceCancelMessage",
        CoverNoteCancelMessage: "CoverNoteCancelMessage",
        ProductCancelMessage: "ProductCancelMessage",
        PaymentTransferredWarningMessage: "PaymentTransferredWarningMessage",
        InvoiceNotBePaidForNSFMessage: "InvoiceNotBePaidForNSFMessage",
        PaymentTransferLabel: "PaymentTransferLabel",
        TransferOverpaymentLabel: "TransferOverpaymentLabel",
        OverpaymentTransferLabel: "OverpaymentTransferLabel",
        FinanceNoPaidDateReceivedMessage: "FinanceNoPaidDateReceivedMessage",
        TaxRateChangeMessage: "TaxRateChangeMessage",
        VATRateChangeMessage: "VATRateChangeMessage",
        DiscountCanNotAddedMessage: "DiscountCanNotAddedMessage",
        FirmReceivesLabel: "FirmReceivesLabel",
        SLCClientLabel: "SLCClientLabel",
        SLCBespokePremiumMessage: "SLCBespokePremiumMessage",
        SLCStandardPremiumMessage: "SLCStandardPremiumMessage",        
        DuplicateContactEmailMessage: "DuplicateContactEmailMessage",
        SingleInvoiceFirmRequiredMessage: "SingleInvoiceFirmRequiredMessage",
        InvalidPasswordMessage: "InvalidPasswordMessage",
        OutstandingPolicyRequirementsMessage: "OutstandingPolicyRequirementsMessage",
        PleaseChooseFinalDraftMessage: "PleaseChooseFinalDraftMessage",
        PolicyTemplateRequiredMessage: "PolicyTemplateRequiredMessage",
        PolicyWithoutTemplateMessage: "PolicyWithoutTemplateMessage",        
        PleaseSelectReinsurerMessage: "PleaseSelectReinsurerMessage",
        PaymentTransferOnSameFirmOnlyMessage: "PaymentTransferOnSameFirmOnlyMessage",
        PaymentTransferNoOutstandingInvoices: "PaymentTransferNoOutstandingInvoices",        
        CorrespondencePostScript: "CorrespondencePostScript",
        CorrespondenceDisclaimer: "CorrespondenceDisclaimer",
        CommissionExpireComfirmMessage: "CommissionExpireComfirmMessage",
        CommissionValueRequiredMessage: "CommissionValueRequiredMessage",
        PolicyTypesRequiredMessage: "PolicyTypesRequiredMessage",
        PropertyTypesRequiredMessage: "PropertyTypesRequiredMessage",
        CommissionPeriodOverlappedMessage: "CommissionPeriodOverlappedMessage",
        FirmCommissionDuplicatedMessage: "FirmCommissionDuplicatedMessage",
        BlockCommissionDuplicatedMessage: "BlockCommissionDuplicatedMessage",
        PremiumMatrixUpdateConfirmMessage: "PremiumMatrixUpdateConfirmMessage",
        NetPremiumTotalLabel: "NetPremiumTotalLabel",
        PremiumTireOverlappedMessage: "PremiumTireOverlappedMessage",
        IndemnityLimitRequiredMessage: "IndemnityLimitRequiredMessage",
        PremiumIsRateOverriddenMessage: "PremiumIsRateOverriddenMessage",
        PremiumEffectiveDateMessage: "PremiumEffectiveDateMessage",
        ConfirmCancelPolicyMessage: "ConfirmCancelPolicyMessage",
        PolicyCancellationMessage: "PolicyCancellationMessage",
        DescriptionLabel: "DescriptionLabel",
        ReviewReinsuranceMessage: "ReviewReinsuranceMessage",
        FinalsIssueMessage: "FinalsIssueMessage",
        CoverNoteIssueMessage: "CoverNoteIssueMessage",
        FinalPoliciesIssueMessage: "FinalPoliciesIssueMessage",
        ProceedWithOrderMessage: "ProceedWithOrderMessage",
        LargeReinsuranceAmountDecreaseMessage: "LargeReinsuranceAmountDecreaseMessage",
        LargeLOIDecreaseMessage: "LargeLOIDecreaseMessage",
        CancellationReasonLabel: "CancellationReasonLabel",
        CancelPolicyLabel: "CancelPolicyLabel",
        CancelEndorsementLabel: "CancelEndorsementLabel",
        PendingCancellationLabel: "PendingCancellationLabel",
        InvoiceReIssuedToolTip: "InvoiceReIssuedToolTip",
        CancelledCoverNoteLabel: "CancelledCoverNoteLabel",
        CancelledLabel: "CancelledLabel",
        ProductLabel: "ProductLabel",
        PremiumLabel: "PremiumLabel",
        IndemnityLimitLabel: "IndemnityLimitLabel",
        DuplicatePropertyOnRowsMessage: "DuplicatePropertyOnRowsMessage",
        InvalidIptPeriodMessage: "InvalidIptPeriodMessage",
        IptRateNotFoundMessage: "IptRateNotFoundMessage",
        OverriddenPremiumMessage: "OverriddenPremiumMessage",
        ZeroPremiumWarningMessage: "ZeroPremiumWarningMessage",
        ExceededMaxCoverageMessage: "ExceededMaxCoverageMessage",
        NotificationLabel: "NotificationLabel",
        SearchAgentSelectedMessage: "SearchAgentSelectedMessage",
        SearchAgentNotificationMessage: "SearchAgentNotificationMessage",
        TypeRiskNameToSearchLabel: "TypeRiskNameToSearchLabel",
        TypePostcodeAddressSearchLabel: "TypePostcodeAddressSearchLabel",
        PaymentToMultipleInvoiceCurrencyMessage: "PaymentToMultipleInvoiceCurrencyMessage",
        UnlockFailedMessage: "UnlockFailedMessage",
        XPLSIntegrationCCEmailReminderMessage: "XPLSIntegrationCCEmailReminderMessage",
    };

    //get localized resource
    window.localizedResource = getResource();

    //bind culture changed event
    $(window).bind("culturechanged", function () { setResource(); });
}());




var sessionContext = (function () {
    var context = {};
    var currentUser = null;

    context.init = function (e) {
        currentUser = sessionStorage.getItem("CurrentUser");
        if (currentUser == null && e) context.refresh(e);
        else currentUser = $.parseJSON(currentUser);
        context.currentUser = currentUser;
    };

    context.refresh = function (e) {
        currentUser = e;
        currentUser.IsExternal = e.AccessType == AccessTypesEnum.External;
        currentUser.IsInternal = e.AccessType == AccessTypesEnum.Internal;
        sessionStorage.setItem("CurrentUser", JSON.stringify(currentUser));
    };

    context.clear = function () {
        context.currentUser = null;
    };
    return context;
})();

var sessionTimeout = (function () {
    var timeout = {};

    var subscribers = [];
    var redirect = "";
    var interval = null;    
    var message = null;
    var started = false;

    timeout.elapsed = 0;
    timeout.duration = 0;

    /* public functions*/
    timeout.init = function (t, r) {
        timeout.duration = t;
        timeout.elapsed = t * 60;
        if (r) timeout.refresh();
    };

    timeout.start = function () {
        if (_canStart()) {
            message = null;
            started = window.setTimeout(_expireSession, parseInt(timeout.duration) * 60 * 1000);
            interval = window.setInterval(function () {
                //set session item elapsed
                timeout.elapsed--;
                $(timeout).trigger("elapsed", { field: "elapsed" });

                //show warning message 5 min. before expired
                if (timeout.elapsed == 300) {
                    message = confirmMessage(localizedResource.WarningModalTitle, localizedResource.SessionToExpireMessage, function (r) {
                        if (r) timeout.extend();
                    });
                }
            }, 1000);
        }
    };

    timeout.clear = function () {
        window.clearTimeout(started);
        window.clearInterval(interval);

        timeout.elapsed = timeout.duration * 60;

        started = false;
        interval = null;
    };

    timeout.refresh = function () {
        timeout.clear();
        timeout.start();
    };

    timeout.end = function () {
        try {
            _execSubscribers();
            _logout();
        }
        finally {
            sessionStorage.clear();
            sessionContext.clear();
            timeout.clear();
        }
    };

    timeout.subscribe = function (k, h) {
        if (!Enumerable.From(subscribers).Any(function (x) { return x.key == k }))
            subscribers.push({ key: k, handler: h });
    };

    timeout.extend = function () {
        $.ajax({
            async: false,
            type: "POST",
            dataType: "json",
            url: getCotentUrl("/Shared/ExtendSession")            
        })
        .done(function (d) {
            timeout.refresh();
        });
    };

    /* private fucntions */
    var _canStart = function () {
        return !started && timeout.duration != null && sessionContext.currentUser != null
    };

    var _logout = function () {
        post({
            async: false,
            type: "POST",
            dataType: "json",
            url: getCotentUrl("Security/Logout"),
            callback: function (data) {
                redirect = data.redirect;
            },
            headers: {
                RequestVerificationToken: antiforgeryToken
            }           
        });
    };

    var _expireSession = function () {
        //close previous message, if any
        if (message) message.Close();

        //end session timeout
        timeout.end();        

        //show message       
        showMessage(localizedResource.InformationModalTitle, localizedResource.SessionExpiredMessage, { callback: _redirectUrl });
    }

    var _execSubscribers = function () {
        $.each(subscribers, function (i, s) {
            s.handler();
        });
        subscribers = [];
    };

    var _redirectUrl = function () {
        var url = kendo.format("{0}?ReturnUrl={1}", redirect, encodeURIComponent(window.location.pathname));
        if (window.windowModel && window.windowModel.window) window.windowModel.window.close();
        redirectViewHandler(url);
    };
    return timeout;
})();
/* Collection Synchronizer */
var Synchronizer = (function () {
    var synchronizer = {};

    synchronizer.UniqueIdPropertyName = "UniqueId";
    synchronizer.MatchFunction = function (item, changedItem, that) {
        /// <summary> Function used to match entities </summary>
        /// <param name="item" type="object"></param>
        /// <param name="that" type="object"></param>
        /// <returns> true/false </returns>
        return item[that.UniqueIdPropertyName] == changedItem.UniqueId;
    };

    var ItemAdded = function (collection, changedItem) {
        /// <summary> Add an item to the collection if it does not exist </summary>
        /// <param name="collection" type="Array"></param>
        /// <param name="changedItem" type="object"></param>
        var that = this;

        if (!Enumerable.From(collection.Items).Any(function (x) { return that.MatchFunction(x, changedItem, that) })) {
            collection.Items.push(changedItem);
        }
    };

    var ItemChanged = function (collection, changedItem) {
        /// <summary> If an item is changed, find it and call the change method. </summary>
        /// <param name="collection" type="Array"></param>
        /// <param name="changedItem" type="object"></param>
        var that = this;

        Enumerable.From(collection.Items).ForEach(function (x) {
            if (that.MatchFunction(x, changedItem, that)) x.Update(changedItem);
        });
    };

    var ItemRemoved = function (collection, changedItem) {
        /// <summary> Remove an item from the collection and add it to the deleted items collection if it exists. </summary>
        /// <param name="collection" type="Array"></param>
        /// <param name="deletedCollection" type="Array"></param>
        /// <param name="changedItem" type="object"></param>
        var that = this;

        collection.Items.removeAll(function (x) { return that.MatchFunction(x, changedItem, that) });
    };

    synchronizer.OverrideMatchFunction = function (match) {
        /// <summary> Override the default match function </summary>
        /// <param name="match" type="Function"></param>
        this.DefaultMatchFunction = this.MatchFunction;
        this.MatchFunction = match;
    };

    synchronizer.RestoreMatchFunction = function () {
        /// <summary> Restore the match function to its orginal state </summary>
        this.MatchFunction = this.DefaultMatchFunction;
    };

    synchronizer.HandleItemChanged = function (collection, changedItem, e) {
        /// <summary> Handle when an item changes </summary>
        /// <param name="collection" type="Array"></param>
        /// <param name="deletedCollection" type="Array"></param>
        /// <param name="changedItem" type="object"></param>
        /// <param name="e" type="object"></param>
        if (e.action == "add") {
            ItemAdded.apply(this, [collection, changedItem]);
        }
        else if (e.action == "itemchange") {
            ItemChanged.apply(this, [collection, changedItem]);
        }
        else if (e.action == "remove") {
            ItemRemoved.apply(this, [collection, changedItem]);
        }
    };

    return synchronizer;
}());

var TransactionSynchronizer = (function () {
    var synchronizer = $.extend(true, {}, Synchronizer);

    synchronizer.InvoiceCollectionChanged = function (e) {
        /// <summary> Handle the Policy Changed event </summary>
        /// <param name="e" type="object"></param>
        /// <param name="entity" type="entity object"></param>

        synchronizer.UniqueIdPropertyName = "TransactionID";

        if (e.action == "add") {
            var entity = e.sender;
            entity["Invoice"] = Enumerable.From(entity.InvoiceCollection.Items).Last();
        }
        else if (e.action == "remove") {
            var entity = e.sender;
            entity["Invoice"] = entity.InvoiceCollection.Items.length > 0 ? Enumerable.From(entity.InvoiceCollection.Items).Last() : extendObject(Invoice);
        }
    };

    return synchronizer;
}());

var InvoiceItemSynchronizer = (function () {
    var synchronizer = $.extend(true, {}, Synchronizer);
    
    synchronizer.PolicyCollectionChanged = function (e) {
        /// <summary> Handle the Policy Changed event </summary>
        /// <param name="e" type="object"></param>
        /// <param name="entity" type="entity object"></param>

        synchronizer.UniqueIdPropertyName = "PolicyUniqueId";

        if (e.action == "remove") {
            var entity = e.sender;
            $.each(entity.InvoiceCollection.Items, function (i, item) {
                synchronizer.HandleItemChanged.apply(synchronizer, [item.InvoiceItemCollection, e.items[0], e]);
            });
        }
    };

    return synchronizer;
}());

var ReinsuranceSynchronizer = (function () {
    var synchronizer = $.extend(true, {}, Synchronizer);

    synchronizer.PolicyCollectionChanged = function (e) {
        /// <summary> Handle the Policy Changed event </summary>
        /// <param name="e" type="object"></param>
        /// <param name="entity" type="entity object"></param>

        synchronizer.UniqueIdPropertyName = "PolicyUniqueId";

        if (e.action == "remove") {
            var entity = e.sender;
            if (entity.Invoice) synchronizer.HandleItemChanged.apply(synchronizer, [entity.Invoice.ReinsuranceCollection, e.items[0], e]);            
        }
    };

    return synchronizer;
}());

var DraftSynchronizer = (function () {
    var synchronizer = $.extend(true, {}, Synchronizer);

    synchronizer.DraftDocumentsChanged = function (e) {
        synchronizer.UniqueIdPropertyName = "UniqueId";

        var entity = e.sender;
        if (e.items) synchronizer.HandleItemChanged.apply(synchronizer, [entity.DocumentCollection, e.items[0], e]);
    };

    return synchronizer;
}());
function confirmationValidator(container) {
	return container.kendoValidator({
		validateOnBlur: false,
		rules: {
			notesrequired: function (input) {
				if (input.is("[notesrequired]")) {
				    var value = input.val().trim();
					var label = input[0].kendoBindingTarget.source.notelabel;
					var required = input[0].kendoBindingTarget.source.noterequired;
					input.attr("data-notesrequired-msg", kendo.format(localizedResource.FieldRequiredMessage, label));
					if (required) return value && value !== '';
				}
				return true;
			}
		},
		messages: {
		    notesrequired: "Requ"
		}
	}).data("kendoValidator");
}
var Department = (function() {
        var department = {};
        department.DepartmentID = 0;
        department.Name = null;
        department.Description = null;
        return department;
}());
var Employee = (function() {
        var employee = {};
        employee.EmployeeID = 0;
        employee.DepartmentID = { ID: 0, Value: "" };
        employee.FirstName = null;
        employee.LastName = null;
        employee.Title = null;
        employee.Phone = null;
        employee.Email = null;
        employee.Username = null;
        employee.HiredDate = null;
        employee.Stamp = null;
        employee.IdentityKey = null;
        employee.EmployeeStatusID = { ID: 1, Value: "Active" };
        employee.Name = " ";
        employee.RegionCollection = {};
        employee.PermissionCollection = {};
        employee.AccessType = 1;
        employee.Permissions = null;
        employee.Extend = function(){
                extend(this,"Employee");
                extendCollection(this,"RegionCollection","EmployeeRegion");
                extendCollection(this,"PermissionCollection","UserPermission");
                this.IsDirty = false;
                this.IsNew = this.EmployeeID == 0;
        }
        
        employee.Update = function(entity){
                var e = entity;
                this.set("EmployeeID",e.EmployeeID);
                this.set("DepartmentID",e.DepartmentID);
                this.set("FirstName",e.FirstName);
                this.set("LastName",e.LastName);
                this.set("Title",e.Title);
                this.set("Email",e.Email);
                this.set("Username",e.Username);
                this.set("HiredDate",e.HiredDate);
                this.set("Stamp",e.Stamp);
                this.set("IdentityKey",e.IdentityKey);
                this.set("Permissions",e.Permissions);
                this.set("IsNew",e.IsNew);
                this.IsDirty = e.IsDirty;
                this.RegionCollection.Update(e.RegionCollection);
                this.PermissionCollection.Update(e.PermissionCollection);
        }
        
        employee.IsEqual = function(entity){
                var e = entity;
                return this.EmployeeID == e.EmployeeID;
        }
        
        employee.ShouldSaveIdentityAccount = false;
        return employee;
}());
var EmployeeRegion = (function() {
        var employeeregion = {};
        employeeregion.EmployeeRegionID = 0;
        employeeregion.EmployeeID = 0;
        employeeregion.RegionID = { ID: 0, Value: "" };
        employeeregion.Extend = function(){
                extend(this,"EmployeeRegion");
                this.IsDirty = false;
                this.IsNew = this.EmployeeRegionID == 0;
        }
        
        employeeregion.Update = function(entity){
                var e = entity;
                this.set("EmployeeRegionID",e.EmployeeRegionID);
                this.set("EmployeeID",e.EmployeeID);
                this.set("IsNew",e.IsNew);
                this.IsDirty = e.IsDirty;
        }
        
        employeeregion.IsEqual = function(entity){
                var e = entity;
                return this.EmployeeRegionID == e.EmployeeRegionID;
        }
        
        return employeeregion;
}());
var EmployeeSearchCriteria = (function() {
        var employeesearchcriteria = {};
        employeesearchcriteria.EmployeeID = 0;
        employeesearchcriteria.Employee = null;
        employeesearchcriteria.DepartmentID = { ID: 0, Value: "" };
        employeesearchcriteria.UserName = null;
        employeesearchcriteria.FirstName = null;
        employeesearchcriteria.LastName = null;
        employeesearchcriteria.Title = null;
        return employeesearchcriteria;
}());
var EmployeeSearchResult = (function() {
        var employeesearchresult = {};
        employeesearchresult.EmployeeID = 0;
        employeesearchresult.DepartmentID = 0;
        employeesearchresult.FirstName = null;
        employeesearchresult.LastName = null;
        employeesearchresult.Title = null;
        employeesearchresult.Email = null;
        employeesearchresult.Username = null;
        employeesearchresult.Picture = null;
        employeesearchresult.HiredDate =  new Date();
        employeesearchresult.PendingTaskCount = 0;
        employeesearchresult.Name = " ";
        return employeesearchresult;
}());
var Permission = (function() {
        var permission = {};
        permission.PermissionID = 0;
        permission.Name = null;
        permission.Sequence = 0;
        permission.Module = { ID: 0, Value: "" };
        permission.Description = null;
        permission.IsSelected = false;
        permission.Extend = function(){
                extend(this,"Permission");
                this.IsDirty = false;
                this.IsNew = this.PermissionID == 0;
        }
        
        permission.Update = function(entity){
                var p = entity;
                this.set("PermissionID",p.PermissionID);
                this.set("Name",p.Name);
                this.set("Sequence",p.Sequence);
                this.set("Module",p.Module);
                this.set("Description",p.Description);
                this.set("IsDirty",p.IsDirty);
                this.set("IsNew",p.IsNew);
        }
        
        permission.IsEqual = function(entity){
                var p = entity;
                return this.PermissionID == p.PermissionID;
        }
        
        return permission;
}());
var PermissionSearchCriteria = (function() {
        var permissionsearchcriteria = {};
        permissionsearchcriteria.PermissionSetTypeID = { ID: 0, Value: "" };
        permissionsearchcriteria.Module = 0;
        permissionsearchcriteria.Name = null;
        permissionsearchcriteria.Description = null;
        permissionsearchcriteria.PermissionSet = null;
        permissionsearchcriteria.PermissionSets = null;
        return permissionsearchcriteria;
}());
var PermissionSet = (function() {
        var permissionset = {};
        permissionset.PermissionSetID = 0;
        permissionset.PermissionSetTypeID = { ID: 0, Value: "" };
        permissionset.Name = null;
        permissionset.Description = null;
        permissionset.PermissionCollection = {};
        permissionset.IsSelected = false;
        permissionset.Extend = function(){
                extend(this,"PermissionSet");
                extendCollection(this,"PermissionCollection","PermissionSetItem");
                this.IsDirty = false;
                this.IsNew = this.PermissionSetID == 0;
        }
        
        permissionset.Update = function(entity){
                var e = entity;
                this.set("PermissionSetID",e.PermissionSetID);
                this.set("Name",e.Name);
                this.set("Description",e.Description);
                this.set("IsNew",e.IsNew);
                this.IsDirty = e.IsDirty;
                this.PermissionCollection.Update(e.PermissionCollection);
        }
        
        permissionset.IsEqual = function(entity){
                var e = entity;
                return this.PermissionSetID == e.PermissionSetID;
        }
        
        return permissionset;
}());
var PermissionSetItem = (function() {
        var permissionsetitem = {};
        permissionsetitem.PermissionSetItemID = 0;
        permissionsetitem.PermissionSetID = 0;
        permissionsetitem.PermissionID = 0;
        permissionsetitem.Permission = null;
        permissionsetitem.Extend = function(){
                extend(this,"PermissionSetItem");
                extendEntity(this,"Permission");
                this.IsDirty = false;
                this.IsNew = this.PermissionSetItemID == 0;
        }
        
        permissionsetitem.Update = function(entity){
                var e = entity;
                this.set("PermissionSetID",e.PermissionSetID);
                this.set("PermissionSetItemID",e.PermissionSetItemID);
                this.IsDirty = false;
                this.IsNew = false;
        }
        
        permissionsetitem.IsEqual = function(entity){
                var e = entity;
                return this.UniqueId.toUpperCase() == e.UniqueId.toUpperCase();
        }
        
        return permissionsetitem;
}());
var Region = (function() {
        var region = {};
        region.RegionID = 0;
        region.Name = null;
        region.Description = null;
        return region;
}());
var UserAccount = (function() {
        var useraccount = {};
        useraccount.UserStatusID = { ID: 0, Value: "" };
        useraccount.UserTypeID = { ID: 0, Value: "" };
        useraccount.FirstName = null;
        useraccount.LastName = null;
        useraccount.Title = null;
        useraccount.Email = null;
        useraccount.Phone = null;
        useraccount.DepartmentID = { ID: 0, Value: "" };
        useraccount.LocationID = { ID: 0, Value: "" };
        useraccount.PrimaryApplicationID = { ID: 0, Value: "" };
        useraccount.AllowedApplications = null;
        useraccount.Username = null;
        useraccount.LockedOut = false;
        useraccount.IdentityKey = null;
        useraccount.IsDirty = false;
        return useraccount;
}());
UserStatusesEnum = {
        Active: 1,
        Inactive: 2
};
UserTypesEnum = {
        Domain: 1,
        External: 2
};
OfficesEnum = {
        PleaseChoose: 0,
        London: 5
};
ApplicationsEnum = {
        STEWART_SOLUTION: 2
};
var UserPermission = (function() {
        var userpermission = {};
        userpermission.UserPermissionID = 0;
        userpermission.EmployeeID = null;
        userpermission.ProfileID = null;
        userpermission.PermissionSetID = 0;
        userpermission.PermissionSet = null;
        userpermission.Extend = function(){
                extend(this,"UserPermission");
                extendEntity(this,"PermissionSet");
                this.IsDirty = false;
                this.IsNew = this.UserPermissionID == 0;
        }
        
        userpermission.Update = function(entity){
                var e = entity;
                this.set("UserPermissionID",e.UserPermissionID);
                this.set("EmployeeID",e.EmployeeID);
                this.set("ProfileID",e.ProfileID);
                this.set("PermissionSetID",e.PermissionSetID);
                this.set("PermissionSet",e.PermissionSet);
                this.set("IsNew",e.IsNew);
                this.IsDirty = e.IsDirty;
        }
        
        userpermission.IsEqual = function(entity){
                var e = entity;
                return this.PermissionSetID == e.PermissionSetID;
        }
        
        return userpermission;
}());
DepartmentsEnum = {
        ProductDevelopment: 1,
        IT: 2,
        BusinessDevelopment: 3,
        Underwriting: 4,
        Finance: 5,
        Compliance: 6,
        Verification: 7,
        QualityAssurance: 8,
        Claims: 9,
        Operations: 10
};
PermissionsEnum = {
        CreateEditStandardPolicy: 101,
        CreateEditBespokePolicy: 102,
        CreateEditBlockPolicy: 103,
        CancelInvoicePolicy: 104,
        PurchaseOnlineQuote: 105,
        ViewOnlineStatements: 106,
        CreateEditBlockCommission: 107,
        CreateEditFirm: 201,
        CreateEditAccount: 202,
        UnlockAccount: 203,
        ViewAccount: 204,
        CreateEditFirmCommission: 205,
        ProcessPayment: 301,
        ReverseCheque: 302,
        IssueRefund: 303,
        WriteOffBalance: 304,
        ViewReports: 401,
        CreateEditEmployee: 601,
        CreateEditPermissionSet: 602,
        CreateEditOnlinePremium: 701,
        ViewRecentlyCreatedTask: 801,
        AssignTask: 802,
        ViewAssignedTask: 803
};
PermissionSetsEnum = {
        SystemAdministrator: 1001,
        QuickQuoteProcessor: 1002,
        Underwriter: 1003,
        BlockPolicyProcessor: 1004,
        PolicyCancellationGroup: 1005,
        ProflieAdministrator: 1006,
        AccountingAdministrator: 1007,
        ReportViewer: 1008,
        SecurityAdministrator: 1009,
        CommissionAdministrator: 1010,
        PremiumAdministrator: 1011,
        TaskAllocator: 1012,
        TaskCreator: 1013,
        TaskAssignee: 1014,
        FirmAdministrator: 2001,
        FirmGeneralUser: 2002,
        OnlineQuotePurchase: 2003,
        OutstandingPaidMattersReports: 2004
};
PermissionSetTypesEnum = {
        Internal: 1,
        External: 2
};
RegionsEnum = {
        England: 1,
        Wales: 2,
        Scotland: 3,
        NorthernIreland: 4
};


var EntityCollection = (function() {
        var entitycollection = {};
        entitycollection.Items = [];
        entitycollection.DeletedItems = [];
        entitycollection.Extend = function(){
                this.Items.extendItems(this.EntityName);
        }
        
        entitycollection.Update = function(entity){
                var e = entity;
                this.Items.updateItems(e.Items,this.EntityName);
                this.set("DeletedItems",e.DeletedItems);
        }
        
        entitycollection.IsEqual = function(entity){
                return false;
        }
        
        entitycollection.IsNew = false;
        entitycollection.EntityName = null;
        return entitycollection;
}());
ModulesEnum = {
        Transaction: 1,
        Profile: 2,
        Finance: 3,
        Report: 4,
        Claims: 5,
        Security: 6,
        Library: 7,
        Task: 8
};
AnswersEnum = {
        No: 0,
        Yes: 1
};
EntityTypesEnum = {
        Transaction: 0,
        ActivityLog: 1,
        Policy: 2,
        PolicyEndorsement: 3,
        Document: 4,
        Invoice: 5,
        Template: 6
};
RevisionStatusesEnum = {
        Draft: 0,
        Final: 1
};
AccessTypesEnum = {
        External: 0,
        Internal: 1
};
ExternalSearchTypesEnum = {
        Created: 1,
        Invoiced: 2,
        Referred: 3
};
InternalSearchTypesEnum = {
        LastViewed: 1,
        Paid: 2,
        AllTasks: 3,
        UnderwriterTasks: 4,
        RecentTasks: 5
};
TransactionContainersEnum = {
        None: 0,
        Block: 1,
        Foreign: 2
};
ProductTypesEnum = {
        Policy: 0,
        Endorsement: 1
};
OverrideTypesEnum = {
        General: 1,
        StandardPremium: 2,
        ZeroPremium: 3
};
PolicyEventsEnum = {
        Issuance: 1,
        Cancellation: 2,
        Reversion: 3
};
IntegrationCountriesEnum = {
        England: 1,
        Wales: 1,
        Scotland: 3,
        NorthernIreland: 4
};
DownloadStatusEnum = {
        Completed: 1,
        Failed: 2
};
NotificationTypesEnum = {
        All: 0,
        Referral: 1
};
InvoiceSearchOrdersEnum = {
        IssuedDate: 1,
        InvoiceNumber: 2
};
TaxTypesEnum = {
        IPT: 1,
        VAT: 2
};
var Address = (function() {
        var address = {};
        address.Postcode = null;
        address.FullAddress = null;
        address.CountryID = { ID: 0, Value: "" };
        address.Type = null;
        return address;
}());
var Client = (function() {
        var client = {};
        client.FirmName = "";
        client.OfficeAddress = "";
        client.FirmType = { ID: 0, Value: "" };
        client.Other = "";
        client.Phone = "";
        client.Website = "";
        client.FirstName = "";
        client.LastName = "";
        client.ContactEmail = "";
        client.FirmEmail = "";
        client.AccountingEmail = "";
        client.AdditionalUsers = "";
        client.Response = null;
        client.Sucess = null;
        client.Extend = function(){
                extend(this,"Client");
        }
        
        client.Update = function(entity){
                var c = entity;
                this.set("UniqueId",c.UniqueId);
                this.set("Success",c.Sucess);
        }
        
        client.IsEqual = function(entity){
                var e = entity;
                return this.UniqueId.toUpperCase() == e.UniqueId.toUpperCase();
        }
        
        return client;
}());
var EnumEntity = (function() {
        var enumentity = {};
        enumentity.ID = 0;
        enumentity.Name = null;
        enumentity.CssStyle = null;
        enumentity.Description = null;
        return enumentity;
}());
var LoginCredentials = (function() {
        var logincredentials = {};
        logincredentials.Username = null;
        logincredentials.Password = null;
        logincredentials.Domain = null;
        return logincredentials;
}());
var LookupCriteria = (function() {
        var lookupcriteria = {};
        lookupcriteria.Country = null;
        lookupcriteria.CountryID = { ID: 0, Value: "" };
        lookupcriteria.SearchTerm = null;
        lookupcriteria.LastId = null;
        lookupcriteria.SearchFor = null;
        lookupcriteria.Filter = null;
        lookupcriteria.MaxSuggestions = 0;
        lookupcriteria.MaxResults = 0;
        return lookupcriteria;
}());
var TreeNode = (function() {
        var treenode = {};
        treenode.id = null;
        treenode.text = null;
        treenode.type = null;
        treenode.expanded = false;
        treenode.imageUrl = null;
        treenode.linkUrl = null;
        treenode.spriteCssClass = null;
        treenode.entity = null;
        treenode.entityType = null;
        treenode.disabled = false;
        treenode.hasChildren = false;
        treenode.items = null;
        treenode.isSelectable = false;
        return treenode;
}());
var UploadContext = (function() {
        var uploadcontext = {};
        uploadcontext.TransactionID = 0;
        uploadcontext.EntityType = 0;
        uploadcontext.EntityUniqueId = null;
        uploadcontext.Folder = 0;
        return uploadcontext;
}());
var DraftContext = (function() {
        var draftcontext = {};
        draftcontext.Quote = null;
        draftcontext.Transaction = null;
        draftcontext.Policy = null;
        draftcontext.PolicyEndorsement = null;
        draftcontext.Invoice = null;
        draftcontext.Draft = null;
        draftcontext.FinalizeDraft = false;
        draftcontext.FinalizeDocument = false;
        draftcontext.BuildPolicyTemplates = function(){
                var templates = [];
                var repeaters = {};
                repeaters.push(EntityTypesEnum.Policy,this.Policy.UniqueId);
                repeaters.push(EntityTypesEnum.Invoice,this.Invoice.UniqueId);
                templates.AddRange(this.Draft.DraftTemplates.Select(d.Document).ToTemplate(repeaters,this.FinalizeDocument));
                return ;
        }
        
        draftcontext.BuildEndorsementTemplates = function(){
                var templates = [];
                var repeaters = {};
                repeaters.push(EntityTypesEnum.Policy,this.Policy.UniqueId);
                repeaters.push(EntityTypesEnum.PolicyEndorsement,this.PolicyEndorsement.UniqueId);
                repeaters.push(EntityTypesEnum.Invoice,this.Invoice.UniqueId);
                templates.AddRange(this.Draft.DraftTemplates.Select(d.Document).ToTemplate(repeaters,this.FinalizeDocument));
                return ;
        }
        
        return draftcontext;
}());
var FolderContext = (function() {
        var foldercontext = {};
        foldercontext.TransactionID = 0;
        foldercontext.ParentUniqueId = null;
        foldercontext.FolderID = 0;
        foldercontext.Folder = null;
        foldercontext.Folders = null;
        foldercontext.Documents = null;
        return foldercontext;
}());
var PolicyContext = (function() {
        var policycontext = {};
        policycontext.Policy = null;
        policycontext.Invoice = null;
        policycontext.InvoiceCollection = null;
        return policycontext;
}());
var XmlSearchCriteria = (function() {
        var xmlsearchcriteria = {};
        xmlsearchcriteria.Culture = "en-GB";
        xmlsearchcriteria.EffectiveDate =  new Date();
        xmlsearchcriteria.Rules = null;
        xmlsearchcriteria.RuleParam = {};
        return xmlsearchcriteria;
}());

$.extend(true, EntityCollection, {
    setupHandlers: function () {
        this.propertyChangeHandler(["Items"], function (e) {
            if (e.action == "add" && e.items[0]) {
                //extend entity if applicable
                if (!e.items[0].Extend && e.sender.EntityName) {
                    e.items[0].Extend = window[e.sender.EntityName].Extend;
                    e.items[0].Extend.apply(e.items[0]);
                }

                //apply property change observer
                if (e.items[0].propertyChangeObserver)
                    e.items[0].propertyChangeObserver();

                //setup entity handlers
                if (e.items[0].setupHandlers)
                    e.items[0].setupHandlers();
            }
        });

        for (var i = 0; i < this.Items.length; i++) {
            this.Items[i].propertyChangeObserver();

            if (this.Items[i].setupHandlers)
                this.Items[i].setupHandlers();
        };
    },
    sortItems: function (e) {
        var field = "$." + e.field;
        if (e.descending)
            this.set("Items", Enumerable.From(this.Items).OrderByDescending(field).ToArray());
        else
            this.set("Items", Enumerable.From(this.Items).OrderBy(field).ToArray());
    }
});
var Clause = (function() {
        var clause = {};
        clause.ClauseID = 0;
        clause.ClauseCategoryID = { ID: 0, Value: "" };
        clause.Description = null;
        clause.HistoryCollection = null;
        clause.RiskCategories = null;
        return clause;
}());
var ClauseHistory = (function() {
        var clausehistory = {};
        clausehistory.ClauseHistoryID = 0;
        clausehistory.ClauseID = 0;
        clausehistory.Wording = null;
        clausehistory.Sequence = 0;
        clausehistory.Culture = "en-GB";
        clausehistory.EffectiveDate = null;
        clausehistory.IneffectiveDate = null;
        return clausehistory;
}());
var ClauseSearchResult = (function() {
        var clausesearchresult = {};
        clausesearchresult.ClauseHistoryID = 0;
        clausesearchresult.ClauseID = 0;
        clausesearchresult.Description = null;
        clausesearchresult.ClauseCategoryID = { ID: 0, Value: "" };
        clausesearchresult.Wording = null;
        clausesearchresult.Sequence = 0;
        clausesearchresult.Culture = "en-GB";
        clausesearchresult.EffectiveDate = null;
        clausesearchresult.IneffectiveDate = null;
        clausesearchresult.RiskCategories = null;
        return clausesearchresult;
}());
var Country = (function() {
        var country = {};
        country.CountryID = 0;
        country.Name = null;
        country.Abbreviation = null;
        country.Code = null;
        country.Culture = null;
        country.Description = null;
        country.IsActive = false;
        return country;
}());
var Currency = (function() {
        var currency = {};
        currency.CurrencyID = 0;
        currency.Name = null;
        currency.Description = null;
        currency.Acronym = null;
        currency.Symbol = null;
        return currency;
}());
var Endorsement = (function() {
        var endorsement = {};
        endorsement.EndorsementID = 0;
        endorsement.EndorsementTypeID = { ID: 0, Value: "" };
        endorsement.Name = null;
        endorsement.Description = null;
        endorsement.EffectiveDate = null;
        endorsement.IneffectiveDate = null;
        endorsement.Rules = null;
        endorsement.IsSelected = false;
        endorsement.ProductName = null;
        endorsement.ProductNumber = null;
        endorsement.ProductType = { ID: 1, Value: "Endorsement" };
        endorsement.Documents = null;
        endorsement.Countries = null;
        endorsement.PolicyTypes = null;
        endorsement.PropertyTypes = null;
        endorsement.CountryNames = null;
        endorsement.PolicyTypeNames = null;
        endorsement.PropertyTypeNames = null;
        endorsement.Extend = function(){
                extend(this,"Endorsement");
                this.IsDirty = false;
                this.IsNew = this.EndorsementID == 0;
        }
        
        endorsement.Update = function(entity){
                var e = entity;
                if(e != null)
                        {
                        this.set("RiskID",e.EndorsementID);
                        this.set("Name",e.Name);
                        this.set("Description",e.Description);
                        this.set("IsNew",e.IsNew);
                        this.IsDirty = e.IsDirty;
                }
}

endorsement.IsEqual = function(entity){
        var e = entity;
        return this.EndorsementID == e.EndorsementID;
}

return endorsement;
}());
var EndorsementClauseSearchCriteria = (function() {
        var endorsementclausesearchcriteria = {};
        endorsementclausesearchcriteria.EndorsementID = 0;
        endorsementclausesearchcriteria.PolicyTypeID = 0;
        return endorsementclausesearchcriteria;
}());
var EndorsementSearchCriteria = (function() {
        var endorsementsearchcriteria = {};
        endorsementsearchcriteria.CountryID = 0;
        endorsementsearchcriteria.Culture = null;
        endorsementsearchcriteria.Name = null;
        endorsementsearchcriteria.Rules = null;
        endorsementsearchcriteria.EffectiveDate =  new Date();
        return endorsementsearchcriteria;
}());
var LibrarySearchCriteria = (function() {
        var librarysearchcriteria = {};
        librarysearchcriteria.IsOnline = false;
        librarysearchcriteria.RiskID = 0;
        librarysearchcriteria.CountryID = 0;
        librarysearchcriteria.ClauseID = 0;
        librarysearchcriteria.RequirementID = 0;
        librarysearchcriteria.RequirementTypeID = 0;
        librarysearchcriteria.ClauseCategoryID = 0;
        librarysearchcriteria.CorrespondenceTypeID = 0;
        librarysearchcriteria.CorrespondenceCategoryID = 0;
        librarysearchcriteria.Culture = null;
        librarysearchcriteria.RiskCategoryID = 0;
        librarysearchcriteria.TemplateTypeID = 0;
        librarysearchcriteria.Rules = null;
        librarysearchcriteria.EffectiveDate =  new Date();
        return librarysearchcriteria;
}());
var Premium = (function() {
        var premium = {};
        premium.PremiumID = 0;
        premium.Name = null;
        premium.EffectiveDate = null;
        premium.IneffectiveDate = null;
        premium.Rules = null;
        premium.DetailCollection = {};
        premium.RiskID = 0;
        premium.PolicyTypeID = { ID: 0, Value: "" };
        premium.CountryID = { ID: 0, Value: "" };
        premium.PropertyTypeID = { ID: 0, Value: "" };
        premium.BasePremiumID = 0;
        premium.Extend = function(){
                extend(this,"Premium");
                extendCollection(this,"DetailCollection","PremiumDetail");
                this.IsDirty = false;
                this.IsNew = this.PremiumID == 0;
        }
        
        premium.Update = function(entity){
                var e = entity;
                if(e != null)
                        {
                        this.set("PremiumID",e.PremiumID);
                        this.set("Name",e.Name);
                        this.set("RiskID",e.RiskID);
                        this.set("EffectiveDate",e.EffectiveDate);
                        this.set("IneffectiveDate",e.IneffectiveDate);
                        this.set("IsNew",e.IsNew);
                        this.IsDirty = e.IsDirty;
                }
}

premium.IsEqual = function(entity){
        var e = entity;
        return this.RiskID == e.RiskID;
}

return premium;
}());
var PremiumDetail = (function() {
        var premiumdetail = {};
        premiumdetail.PremiumDetailID = 0;
        premiumdetail.PremiumID = 0;
        premiumdetail.Minimum = 0;
        premiumdetail.Maximum = 0;
        premiumdetail.Premium = 0;
        premiumdetail.Extend = function(){
                extend(this,"PremiumDetail");
                this.IsDirty = false;
                this.IsNew = this.PremiumDetailID == 0;
        }
        
        premiumdetail.Update = function(entity){
                var e = entity;
                if(e != null)
                        {
                        this.set("PremiumDetailID",e.PremiumDetailID);
                        this.set("PremiumID",e.PremiumID);
                        this.set("Minimum",e.Minimum);
                        this.set("Maximum",e.Maximum);
                        this.set("Premium",e.Premium);
                        this.set("IsNew",e.IsNew);
                        this.IsDirty = e.IsDirty;
                }
}

premiumdetail.IsEqual = function(entity){
        var e = entity;
        return this.PremiumDetailID == e.PremiumDetailID;
}

return premiumdetail;
}());
var PremiumSearchCriteria = (function() {
        var premiumsearchcriteria = {};
        premiumsearchcriteria.Name = null;
        premiumsearchcriteria.RiskID = 0;
        premiumsearchcriteria.PolicyTypeID = 0;
        premiumsearchcriteria.Culture = null;
        premiumsearchcriteria.Rules = null;
        premiumsearchcriteria.EffectiveDate = null;
        return premiumsearchcriteria;
}());
var ProductSearchCriteria = (function() {
        var productsearchcriteria = {};
        productsearchcriteria.ProductType = { ID: 0, Value: "Policy" };
        productsearchcriteria.CountryID = { ID: 1, Value: "" };
        productsearchcriteria.PolicyTypeID = { ID: 0, Value: "" };
        productsearchcriteria.PropertyTypeID = { ID: 0, Value: "" };
        productsearchcriteria.IsOnline = false;
        productsearchcriteria.Name = null;
        productsearchcriteria.EffectiveDate = null;
        productsearchcriteria.IneffectiveDate = null;
        return productsearchcriteria;
}());
var QualificationFlag = (function() {
        var qualificationflag = {};
        qualificationflag.QualificationFlagID = 0;
        qualificationflag.Description = null;
        qualificationflag.Message = null;
        qualificationflag.Field = null;
        qualificationflag.EffectiveDate = null;
        qualificationflag.IneffectiveDate = null;
        return qualificationflag;
}());
var Requirement = (function() {
        var requirement = {};
        requirement.RequirementID = 0;
        requirement.Description = null;
        requirement.HistoryCollection = null;
        return requirement;
}());
var RequirementHistory = (function() {
        var requirementhistory = {};
        requirementhistory.RequirementHistoryID = 0;
        requirementhistory.RequirementID = 0;
        requirementhistory.Wording = null;
        requirementhistory.Answer = false;
        requirementhistory.Sequence = 0;
        requirementhistory.Culture = "en-GB";
        requirementhistory.EffectiveDate = null;
        requirementhistory.IneffectiveDate = null;
        return requirementhistory;
}());
var RequirementSearchResult = (function() {
        var requirementsearchresult = {};
        requirementsearchresult.RequirementHistoryID = 0;
        requirementsearchresult.RequirementID = 0;
        requirementsearchresult.RequirementTypeID = { ID: 0, Value: "" };
        requirementsearchresult.Description = null;
        requirementsearchresult.Wording = null;
        requirementsearchresult.Answer = false;
        requirementsearchresult.Sequence = 0;
        requirementsearchresult.RiskID = 0;
        requirementsearchresult.RiskCategory = 0;
        return requirementsearchresult;
}());
var Risk = (function() {
        var risk = {};
        risk.RiskID = 0;
        risk.RiskTypeID = { ID: 0, Value: "" };
        risk.RiskTermID = 0;
        risk.IsOnline = false;
        risk.Name = null;
        risk.Description = null;
        risk.MaxIndemnityLimit = 0;
        risk.EffectiveDate = null;
        risk.IneffectiveDate = null;
        risk.Rules = null;
        risk.MaxCoverage = 0;
        risk.WithCertificate = false;
        risk.Keywords = null;
        risk.RiskTerm = null;
        risk.IsBlockPolicy = false;
        risk.RiskCategory = { ID: 0, Value: "" };
        risk.RiskCovers = null;
        risk.IsSelected = false;
        risk.ProductName = null;
        risk.ProductNumber = null;
        risk.ProductType = { ID: 0, Value: "Policy" };
        risk.Documents = null;
        risk.Countries = null;
        risk.PolicyTypes = null;
        risk.PropertyTypes = null;
        risk.CountryNames = null;
        risk.PolicyTypeNames = null;
        risk.PropertyTypeNames = null;
        risk.Country = "Foreign Countries";
        risk.PropertyType = "Mixed Use";
        risk.FullDescription = "";
        risk.Extend = function(){
                extend(this,"Risk");
                this.IsDirty = false;
                this.IsNew = this.RiskID == 0;
        }
        
        risk.Update = function(entity){
                var e = entity;
                if(e != null)
                        {
                        this.set("RiskID",e.RiskID);
                        this.set("Name",e.Name);
                        this.set("Description",e.Description);
                        this.set("RiskTermID",e.RiskTermID);
                        this.set("RiskTypeID",e.RiskTypeID);
                        this.set("RiskCategory",e.RiskCategory);
                        this.set("RiskCovers",e.RiskCovers);
                        this.set("IsSelected",e.IsSelected);
                        this.set("IsOnline",e.IsOnline);
                        this.set("IsNew",e.IsNew);
                        this.IsDirty = e.IsDirty;
                }
}

risk.IsEqual = function(entity){
        var e = entity;
        return this.RiskID == e.RiskID;
}

return risk;
}());
var RiskCategory = (function() {
        var riskcategory = {};
        riskcategory.RiskCategoryID = 0;
        riskcategory.Name = null;
        riskcategory.Description = null;
        riskcategory.IsOnline = false;
        riskcategory.ItemCollection = {};
        return riskcategory;
}());
var RiskCategoryItem = (function() {
        var riskcategoryitem = {};
        riskcategoryitem.RiskCategoryItemID = 0;
        riskcategoryitem.RiskCategoryID = 0;
        riskcategoryitem.RiskID = null;
        riskcategoryitem.ClauseID = null;
        riskcategoryitem.RequirementID = null;
        return riskcategoryitem;
}());
var RiskCover = (function() {
        var riskcover = {};
        riskcover.RiskCoverID = 0;
        riskcover.Name = null;
        riskcover.Description = null;
        riskcover.IsSearch = false;
        return riskcover;
}());
var RiskCoverSearchCriteria = (function() {
        var riskcoversearchcriteria = {};
        riskcoversearchcriteria.RiskID = 0;
        riskcoversearchcriteria.IsSearch = false;
        return riskcoversearchcriteria;
}());
var RiskCoverSearchResult = (function() {
        var riskcoversearchresult = {};
        riskcoversearchresult.RiskCoverID = 0;
        riskcoversearchresult.RiskID = 0;
        riskcoversearchresult.Name = null;
        riskcoversearchresult.Description = null;
        riskcoversearchresult.IsSearch = false;
        return riskcoversearchresult;
}());
var RiskSearchCriteria = (function() {
        var risksearchcriteria = {};
        risksearchcriteria.RiskID = 0;
        risksearchcriteria.RiskCategoryID = 0;
        risksearchcriteria.Name = null;
        risksearchcriteria.IsOnline = 0;
        risksearchcriteria.Culture = null;
        risksearchcriteria.Rules = null;
        risksearchcriteria.EffectiveDate =  new Date();
        risksearchcriteria.GetKeywords = 0;
        return risksearchcriteria;
}());
var RiskTerm = (function() {
        var riskterm = {};
        riskterm.RiskTermID = 0;
        riskterm.Name = null;
        riskterm.Description = null;
        riskterm.Culture = "en-GB";
        riskterm.EffectiveDate = null;
        riskterm.IneffectiveDate = null;
        return riskterm;
}());
var Tax = (function() {
        var tax = {};
        tax.TaxID = 0;
        tax.Rate = 0;
        tax.Description = null;
        tax.EffectiveDate = null;
        tax.IneffectiveDate = null;
        tax.RatePeriod = null;
        return tax;
}());
var Template = (function() {
        var template = {};
        template.TemplateID = 0;
        template.TemplateTypeID = { ID: 0, Value: "" };
        template.Name = null;
        template.Description = null;
        template.Sequence = 0;
        template.RequiresUserInput = false;
        template.HistoryCollection = null;
        return template;
}());
var TemplateFolder = (function() {
        var templatefolder = {};
        templatefolder.FolderID = 0;
        templatefolder.Name = null;
        templatefolder.ParentFolderId = 0;
        templatefolder.RepeatingType = null;
        templatefolder.Templates = null;
        templatefolder.Folders = null;
        templatefolder.HasItems = function(){
                if(templates.Count > 0)
                        return true;
                return false;
        }
        
        return templatefolder;
}());
var TemplateHistory = (function() {
        var templatehistory = {};
        templatehistory.TemplateHistoryID = 0;
        templatehistory.TemplateID = 0;
        templatehistory.Contents = null;
        templatehistory.Version = 0;
        templatehistory.Culture = "en-GB";
        templatehistory.EffectiveDate = null;
        templatehistory.IneffectiveDate = null;
        templatehistory.Rules = null;
        return templatehistory;
}());
var TemplateSearchResult = (function() {
        var templatesearchresult = {};
        templatesearchresult.TemplateHistoryID = 0;
        templatesearchresult.TemplateID = 0;
        templatesearchresult.TemplateTypeID = { ID: 0, Value: "" };
        templatesearchresult.Name = null;
        templatesearchresult.Contents = null;
        templatesearchresult.Version = 0;
        templatesearchresult.Sequence = 0;
        templatesearchresult.FolderId = 0;
        templatesearchresult.Culture = "en-GB";
        templatesearchresult.EffectiveDate = null;
        templatesearchresult.IneffectiveDate = null;
        templatesearchresult.RequiresUserInput = false;
        templatesearchresult.IsSelected = false;
        templatesearchresult.IsVisible = true;
        templatesearchresult.DataRetrievalType = "Stewart.StepsUK.Document.Data.TransactionDataRetriever,Stewart.StepsUK.Document";
        templatesearchresult.Parameters = null;
        templatesearchresult.Path = null;
        templatesearchresult.RepeatingKey = 0;
        templatesearchresult.RepeatingType = null;
        templatesearchresult.IsFinalDocument = false;
        templatesearchresult.Stream = null;
        templatesearchresult.TemplateName = null;
        templatesearchresult.ConditionType = null;
        templatesearchresult.IsValid = false;
        templatesearchresult.RepeatingDataKeys = null;
        templatesearchresult.TemplateType = 6;
        return templatesearchresult;
}());
ClauseCategoriesEnum = {
        AdditionalClause: 1,
        Escalator: 2,
        Exclusions: 3,
        InsuredUse: 4,
        TheDefects: 5,
        TheInsured: 6,
        Endorsement: 7
};
ContactMethodsEnum = {
        Email: 1,
        Fax: 2,
        Post: 3
};
CountriesEnum = {
        England: 1,
        Wales: 2,
        Scotland: 3,
        NorthernIreland: 4,
        IsleOfMan: 5,
        CzechRepublic: 6,
        Hungary: 7,
        Italy: 8,
        Poland: 9,
        Romania: 10,
        SlovakRepublic: 11,
        TheBahamas: 12,
        RepublicOfIreland: 13
};
CountryCodesEnum = {
        ENG: 1,
        WAL: 2,
        SCT: 3,
        NIR: 4,
        IOM: 5,
        CZE: 6,
        HUN: 7,
        ITA: 8,
        POL: 9,
        ROU: 10,
        SVK: 11,
        BHS: 12,
        IRL: 13
};
CurrenciesEnum = {
        BritishPound: 1,
        Euro: 2,
        USDollar: 3,
        CzechKoruna: 4,
        HungarianForint: 5,
        PolishZloty: 6,
        RomanianLei: 7
};
EndorsementTypesEnum = {
        AdditionalRiskCover: 1,
        AdditionalDeedReferredTo: 2,
        AdditionalLandCovered: 3,
        PolicyTermAltered: 4,
        PropertyDescriptionAltered: 5,
        InsuredNameChange: 6,
        EscalatorClauseAddition: 7,
        LimitOfIndemnityIncrease: 8,
        AdditionalInterestNoted: 9,
        SubstituteCover: 10,
        SubstitutePlan: 11,
        ContinuationOfPolicy: 12,
        AssignmentOfReceivables: 13,
        TopUp: 14,
        ChangeOfName: 15,
        AdditionOfLand: 16,
        ConsequentialLoss: 17,
        AmendmentToScheduleB: 18,
        Improvements: 19,
        Other: 20,
        DecreaseInLimitOfIndemnity: 21
};
RequirementStatusesEnum = {
        Waived: 1,
        Received: 2,
        Outstanding: 3,
        NotApplicable: 4,
        OnHold: 5
};
RequirementTypesEnum = {
        Assumption: 1,
        Requirement: 2
};
RiskCategoriesEnum = {
        AbsentLandlord: 1,
        Access: 2,
        AdoptionOfRoadSewer: 3,
        ChancelRepair: 4,
        ContingentBuildings: 5,
        DeedOfEnlargement: 6,
        DefectiveTitle: 7,
        Environmental: 8,
        FlyingCreepingFreehold: 9,
        ForfeitureOfLeaseBankruptcy: 10,
        ForfeitureOfSuperiorLease: 11,
        FreeholdFlat: 12,
        FreeholdRentCharge: 13,
        FreeholdRestrictiveCovenants: 14,
        GoodLeaseholdTitle: 15,
        InsolvencyActTransferAtUndervalue: 16,
        LeaseholdRestrictiveCovenants: 17,
        LocalSearches: 18,
        MaisonetteFlatIndemnity: 19,
        NHBCArchitectsCertificate: 20,
        OutstandingCharges: 21,
        OutstandingLeaseholdInterest: 22,
        PlanningMatters: 23,
        RestrictiveConditions: 24,
        RightToBuy: 25,
        RightsAffectingProperty: 26,
        Services: 27,
        GratuitousAlienation: 28,
        FraudSolution: 29,
        JapaneseKnotweed: 30,
        ForfeitureOfLeaseHousingActPossessionLenderOnly: 31,
        MostOrderedResidentialPolicies: 32,
        MostOrderedCommercialPolicies: 33,
        ACCESSSERVICES: 101,
        ADVERSEPOSSESSIONPOSSESSORYTITLE: 102,
        BLOCKPOLICY: 103,
        CHANCEL: 104,
        DEEDOFPOSTPONEMENT: 105,
        DEFECTIVETITLE: 106,
        ENVIRONMENTAL: 107,
        FLYINGFREEHOLD: 108,
        FREEHOLDFLAT: 110,
        FREEHOLDRESTRICTIVECOVENANTS: 111,
        GENERAL: 112,
        GENERALMISCELLANEOUS: 113,
        INSOLVENCY: 114,
        INSUREDUSE: 115,
        JUDICIALREVIEW: 116,
        LANDCHARGES: 117,
        LEASEHOLD: 118,
        LOCALSEARCH: 119,
        MININGRIGHTS: 120,
        NHBC: 121,
        OUTSTANDINGLEASE: 122,
        PLANNINGMATTERS: 123,
        RAILWAYLEASE: 124,
        RENTCHARGE: 125,
        RESTRICTIVECONDITIONS: 126,
        RIGHTSTOPARK: 128,
        RIGHTSAFFECTINGPROPERTY: 129,
        RIGHTSOFLIGHT: 130,
        RIGHTSOFREVERTER: 131,
        TOWNVILLAGEGREEN: 132,
        TREEPRESERVATIONORDER: 133,
        UNADOPTEDDRAIN: 134,
        LEASEHOLDRESTRICTIVECOVENANTS: 135,
        FOREIGNPOLICY: 136,
        OTHER: 999
};
RiskTypesEnum = {
        AbsentLandlordAndGoodLeaseholdTitleIndemnity: 1,
        AbsentLandlordAndMaisonetteIndemnity: 2,
        AbsentLandlordIndemnity: 3,
        AccessAndFreeholdRestrictiveCovenantIndemnity: 4,
        AccessAndOutstandingRightsAndEasementsIndemnity: 5,
        AccessAndServicesIndemnity: 6,
        AccessIndemnity: 7,
        AccessServicesAndFreeholdRestrictiveCovenantIndemnity: 8,
        AccessServicesAndOutstandingRightsAndEasementsIndemnity: 9,
        AdoptionOfRoadAndSewerIndemnity: 10,
        AdoptionOfRoadAndSewerIndemnityLenderOnly: 11,
        AdoptionOfRoadIndemnity: 12,
        AdoptionOfRoadIndemnityLenderOnly: 13,
        AdoptionOfSewerIndemnity: 14,
        AdoptionOfSewerIndemnityLenderOnly: 15,
        AdversePossessionIndemnity: 16,
        BreachOfPlanningOrLackOfPlanningAndFreeholdRestrictiveCovenantIndemnity: 17,
        BreachOfPlanningOrLackOfPlanningIndemnity: 18,
        BreachOfTreePreservationOrderIndemnity: 19,
        ChancelRepairIndemnity: 20,
        ChancelRepairIndemnityLenderOnly: 21,
        ContingentBuildingsIndemnity: 22,
        DeedOfEnlargementIndemnity: 23,
        DeedOfPostponementIndemnity: 24,
        DefectiveTitleAndAccessIndemnity: 25,
        DefectiveTitleAndFreeholdRestrictiveCovenantIndemnity: 26,
        DefectiveTitleAndMinesAndMineralsIndemnity: 27,
        DefectiveTitleAndOutstandingRightsIndemnity: 28,
        DefectiveTitleIndemnity: 29,
        DefectiveTitleIndemnityLenderOnly: 30,
        DefectiveTitleAccessAndOutstandingRightsIndemnity: 31,
        DefectiveTitleAccessAndServicesIndemnity: 32,
        DefectiveTitleAccessServicesAndFreeholdRestrictiveCovenantIndemnity: 33,
        DefectiveTitleAccessServicesAndOutstandingRightsIndemnity: 34,
        DefectiveTitleAccessServicesOutstandingRightsAndFreeholdRestrictiveCovenantIndemnity: 35,
        DefectiveTitleFreeholdRestrictiveCovenantMinesAndMineralsIndemnity: 36,
        DefectiveTitleFreeholdRestrictiveCovenantOutstandingRightsAndMinesAndMineralsIndemnity: 37,
        DefectiveTitleOutstandingRightsAndFreeholdRestrictiveCovenantIndemnity: 38,
        EnvironmentalSearchValidationIndemnity: 39,
        FailedEnvironmentalSearchIndemnity: 40,
        FlyingOrCreepingFreeholdIndemnity: 41,
        ForfeitureOfLeaseBankruptcyIndemnity: 42,
        ForfeitureOfSuperiorLeaseIndemnity: 43,
        FreeholdFlatIndemnity: 44,
        FreeholdRentChargeAndFreeholdRestrictiveCovenantIndemnity: 45,
        FreeholdRentChargeIndemnity: 46,
        FreeholdRestrictiveCovenantIndemnity: 47,
        FreeholdRestrictiveCovenantMiningAndMineralRightsIndemnity: 48,
        FreeholdRestrictiveCovenantMiningAndMineralRightsOutstandingRightsAndEasementsIndemnity: 49,
        GoodLeaseholdTitleIndemnity: 50,
        InsolvencyActIndemnity: 51,
        InsolvencyActIndemnityGiftedDepositBlock: 52,
        InsolvencyActIndemnityMatrimonialOrderBlock: 53,
        InsolvencyActIndemnityNewTransferBlock: 54,
        InsolvencyActIndemnityNewTransferLenderOnlyBlock: 55,
        JudicialReviewIndemnity: 56,
        LackOfBuildingRegulationConsentInclFENSAAndFreeholdRestrictiveCovenantIndemnity: 57,
        LackOfBuildingRegulationConsentInclFENSAIndemnity: 58,
        LackOfBuildingRegulationConsentAndLeaseholdRestrictiveCovenantIndemnity: 59,
        LackOfConservationAreaAndBuildingRegulationConsentInclFENSAIndemnity: 60,
        LackOfConservationAreaConsentIndemnity: 61,
        LackOfConservationAreaBuildingRegulationConsentInclFENSAAndFreeholdRestrictiveCovenantIndemnity: 62,
        LackOfFENSAAndOtherInstallationCertificatesIndemnity: 63,
        LackOfListedBuildingAndBuildingRegulationConsentInclFENSAIndemnity: 64,
        LackOfListedBuildingConsentIndemnity: 65,
        LackOfListedBuildingBuildingRegulationConsentInclFENSAAndFreeholdRestrictiveCovenantIndemnity: 66,
        LackOfNHBCOrArchitectsCertificateIndemnityLenderOnly: 67,
        LackOfPlanningAndBuildingRegulationConsentInclFENSAIndemnity: 68,
        LackOfPlanningBuildingRegulationConsentInclFENSAAndFreeholdRestrictiveCovenantIndemnity: 69,
        LackOfPlanningBuildingRegulationConsentAccessAndServicesIndemnity: 70,
        LackOfPlanningBuildingRegulationsAndLeaseholdRestrictiveCovenantIndemnity: 71,
        LeaseholdRestrictiveCovenantIndemnity: 72,
        LimitedOrNoTitleGuaranteeIndemnity: 73,
        LostTitleDeedsIndemnityUnregistered: 74,
        MaisonetteIndemnity: 75,
        ManorialRightsIndemnity: 76,
        ManorialMiningAndMineralRightsIndemnity: 77,
        MiningAndMineralRightsIndemnity: 78,
        NIAccessAndFreeholdRestrictiveCovenantIndemnity: 79,
        NIAccessAndOutstandingRightsAndEasementsIndemnity: 80,
        NIAccessAndOutstandingRightsIndemnity: 81,
        NIAccessAndServicesIndemnity: 82,
        NIAccessIndemnity: 83,
        NIAccessServicesAndFreeholdRestrictiveCovenantIndemnity: 84,
        NIAccessServicesAndOutstandingRightsIndemnity: 85,
        NIAdoptionOfRoadAndSewerIndemnity: 86,
        NIAdoptionOfRoadAndSewerIndemnityLenderOnly: 87,
        NIAdoptionOfRoadIndemnity: 88,
        NIAdoptionOfRoadIndemnityLenderOnly: 89,
        NIAdoptionOfSewerIndemnity: 90,
        NIAdoptionOfSewerIndemnityLenderOnly: 91,
        NIBreachOfPlanningOrLackOfPlanningIndemnity: 92,
        NIBreachOfPlanningOrLackOfPlanningBuildingRegulationConsentAndFreeholdRestrictiveCovenantIndemnity: 93,
        NIBreachOfTreePreservationOrderIndemnity: 94,
        NIDefectiveTitleAndAccessIndemnity: 95,
        NIDefectiveTitleAndFreeholdRestrictiveCovenantIndemnity: 96,
        NIDefectiveTitleAndMiningAndMineralsIndemnity: 97,
        NIDefectiveTitleAndOutstandingRightsIndemnity: 98,
        NIDefectiveTitleIndemnity: 99,
        NIDefectiveTitleIndemnityLenderOnly: 100,
        NIDefectiveTitleAccessAndOutstandingRightsIndemnity: 101,
        NIDefectiveTitleAccessAndServicesIndemnity: 102,
        NIDefectiveTitleAccessServicesAndFreeholdRestrictiveCovenantIndemnity: 103,
        NIDefectiveTitleAccessServicesAndOutstandingRightsIndemnity: 104,
        NIDefectiveTitleAccessServicesOutstandingRightsAndFreeholdRestrictiveCovenantIndemnity: 105,
        NIDefectiveTitleFreeholdRestrictiveCovenantMiningAndMineralsIndemnity: 106,
        NIDefectiveTitleFreeholdRestrictiveCovenantOutstandingRightsAndMiningAndMineralsIndemnity: 107,
        NIDefectiveTitleOutstandingRightsAndFreeholdRestrictiveCovenantIndemnity: 108,
        NIFlyingOrCreepingFreeholdIndemnity: 109,
        NIFreeholdRestrictiveCovenantIndemnity: 110,
        NIFreeholdRestrictiveCovenantMiningAndMineralRightsIndemnity: 111,
        NIFreeholdRestrictiveCovenantMiningAndMineralRightsOutstandingRightsAndEasementsIndemnity: 112,
        NIInsolvencyActGiftedDepositIndemnity: 113,
        NIInsolvencyActMatrimonialCourtOrderIndemnity: 114,
        NIInsolvencyActNewTransferIndemnity: 115,
        NIInsolvencyActPreviousTransferIndemnity: 116,
        NIInsolvencyActIndemnity: 117,
        NIJudicialReviewIndemnity: 118,
        NILackOfBuildingRegulationConsentAndFreeholdRestrictiveCovenantIndemnity: 119,
        NILackOfBuildingRegulationConsentIndemnity: 120,
        NILackOfConservationAreaAndBuildingRegulationConsentIndemnity: 121,
        NILackOfConservationAreaConsentIndemnity: 122,
        NILackOfConservationAreaBuildingRegulationConsentAndFreeholdRestrictiveCovenantIndemnity: 123,
        NILackOfListedBuildingAndBuildingRegulationConsentIndemnity: 124,
        NILackOfListedBuildingConsentIndemnity: 125,
        NILackOfListedBuildingBuildingRegulationConsentAndFreeholdRestrictiveCovenantIndemnity: 126,
        NILackOfNHBCOrArchitectsCertificateIndemnityLenderOnly: 127,
        NILackOfPlanningAndBuildingRegulationConsentIndemnity: 128,
        NILimitedOrNoTitleGuaranteeIndemnity: 129,
        NILostTitleDeedsIndemnityUnregistered: 130,
        NIManorialRightsIndemnity: 131,
        NIManorialMiningAndMineralRightsIndemnity: 132,
        NIMiningAndMineralRightsIndemnity: 133,
        NINoSearchIndemnity: 134,
        NINoSearchIndemnityLenderOnly: 135,
        NIObstructionOfRightsIndemnity: 136,
        NIOutstandingRightsAndEasementsIndemnity: 137,
        NIOutstandingRightsAccessAndFreeholdRestrictiveCovenantIndemnity: 138,
        NIOutstandingRightsAccessServicesAndFreeholdRestrictiveCovenantIndemnity: 139,
        NIPossessoryTitleDueToLostTitleDeedsIndemnity: 140,
        NIRightOfLightCompensationOnlyIndemnity: 141,
        NIRightOfLightAndFreeholdRestrictiveCovenantIndemnity: 142,
        NIRightOfLightIndemnity: 143,
        NIRightOfLightIndemnityWithExcess: 144,
        NIRightToOverhangIndemnity: 145,
        NIRightToParkIndemnity: 146,
        NIServicesIndemnity: 147,
        NISewerOrDrainIndemnity: 148,
        NIUnknownFreeholdRestrictiveCovenantsRightsAndEasementsIndemnity: 149,
        NoEnvironmentalSearchIndemnity: 150,
        NoSearchIncludingChancelIndemnity: 151,
        NoSearchIncludingChancelIndemnityLenderOnly: 152,
        NoSearchChancelRepairIndemnityBlock: 153,
        NoSearchChancelRepairIndemnityLenderOnlyBlock: 154,
        NoSearchIndemnity: 155,
        NoSearchIndemnityBlock: 156,
        NoSearchIndemnityLenderOnly: 157,
        NoSearchIndemnityLenderOnlyBlock: 158,
        ObstructionOfRightsIndemnity: 159,
        OutstandingChargesAndFreeholdRestrictiveCovenantIndemnity: 160,
        OutstandingChargesIndemnity: 161,
        OutstandingLeaseIndemnity: 162,
        OutstandingRightsAndEasementsIndemnity: 163,
        OutstandingRightsAccessAndFreeholdRestrictiveCovenantIndemnity: 164,
        OutstandingRightsAccessServicesAndFreeholdRestrictiveCovenantIndemnity: 165,
        PartyWallIndemnity: 166,
        PossessoryTitleIndemnity: 167,
        RailwayLeaseIndemnity: 168,
        RightOfLightCompensationOnlyIndemnity: 169,
        RightOfLightAndFreeholdRestrictiveCovenantIndemnity: 170,
        RightOfLightIndemnity: 171,
        RightOfLightIndemnityWithExcess: 172,
        RightsOfReverterActIndemnity: 173,
        RightsToOverhangIndemnity: 174,
        RightsToParkIndemnity: 175,
        ScotlandAccessAndOutstandingRightsAndServitudesIndemnity: 176,
        ScotlandAccessAndRestrictiveConditionsIndemnity: 177,
        ScotlandAccessAndServicesIndemnity: 178,
        ScotlandAccessIndemnity: 179,
        ScotlandAccessOutstandingRightsAndRestrictiveConditionsIndemnity: 180,
        ScotlandAccessServicesAndOutstandingRightsAndServitudesIndemnity: 181,
        ScotlandAccessServicesAndRestrictiveConditionsIndemnity: 182,
        ScotlandAccessServicesOutstandingRightsAndRestrictiveConditionsIndemnity: 183,
        ScotlandAdoptionOfRoadIndemnity: 184,
        ScotlandAdoptionOfRoadIndemnityLenderOnly: 185,
        ScotlandBankruptcyActGiftedDepositIndemnity: 186,
        ScotlandBankruptcyActMatrimonialCourtOrderIndemnity: 187,
        ScotlandBankruptcyActNewTransferIndemnity: 188,
        ScotlandBankruptcyActPreviousTransferIndemnity: 189,
        ScotlandBankruptcyActIndemnity: 190,
        ScotlandBreachOfTreePreservationOrderIndemnity: 191,
        ScotlandDeedOfPostponementIndemnity: 192,
        ScotlandDefectiveTitleLenderOnly: 193,
        ScotlandDefectiveTitleAndAccessIndemnity: 194,
        ScotlandDefectiveTitleAndMiningAndMineralsIndemnity: 195,
        ScotlandDefectiveTitleAndOutstandingRightsAndServitudesIndemnity: 196,
        ScotlandDefectiveTitleAndRestrictiveConditionsIndemnity: 197,
        ScotlandDefectiveTitleIndemnity: 198,
        ScotlandDefectiveTitleAccessAndOutstandingRightsIndemnity: 199,
        ScotlandDefectiveTitleAccessAndServicesIndemnity: 200,
        ScotlandDefectiveTitleAccessServicesAndOutstandingRightsIndemnity: 201,
        ScotlandDefectiveTitleAccessServicesAndRestrictiveConditionsIndemnity: 202,
        ScotlandDefectiveTitleAccessServicesOutstandingRightsAndRestrictiveConditionsIndemnity: 203,
        ScotlandDefectiveTitleOutstandingRightsAndRestrictiveConditionsIndemnity: 204,
        ScotlandDefectiveTitleRestrictiveConditionsAndMiningAndMineralsIndemnity: 205,
        ScotlandDefectiveTitleRestrictiveConditionsOutstandingRightsAndMiningAndMineralsIndemnity: 206,
        ScotlandFreeholdRestrictiveConditionsIndemnity: 207,
        ScotlandInsolvencyActIndemnity: 208,
        ScotlandJudicialReviewIndemnity: 209,
        ScotlandLackOfBuildingRegulationConsentAndRestrictiveConditionsIndemnity: 210,
        ScotlandLackOfBuildingRegulationConsentIndemnity: 211,
        ScotlandLackOfConservationAreaConsentIndemnity: 212,
        ScotlandLackOfListedBuildingConsentIndemnity: 213,
        ScotlandLackOfNHBCOrArchitectsCertificateIndemnityLenderOnly: 214,
        ScotlandLackOfOrRestrictedWarrandiceIndemnity: 215,
        ScotlandLackOfPlanningAndBuildingRegulationConsentIndemnity: 216,
        ScotlandLackOfPlanningAndRestrictiveConditionsIndemnity: 217,
        ScotlandLackOfPlanningIndemnity: 218,
        ScotlandLackOfPlanningBuildingRegulationConsentAndRestrictiveConditionsIndemnity: 219,
        ScotlandLackOfPlanningBuildingRegulationConsentAccessAndServicesIndemnity: 220,
        ScotlandLostTitleDeedsIndemnityUnregistered: 221,
        ScotlandMiningAndMineralRightsIndemnity: 222,
        ScotlandOutstandingRightsAndServitudesIndemnity: 223,
        ScotlandRestrictiveConditionsAndMiningAndMineralsIndemnity: 224,
        ScotlandRestrictiveConditionsOutstandingRightsAndMiningAndMineralsIndemnity: 225,
        ScotlandRightToOverhangIndemnity: 226,
        ScotlandServicesIndemnity: 227,
        ScotlandSewerOrDrainIndemnity: 228,
        ScotlandUnknownRestrictiveConditionsRightsAndServitudesIndemnity: 229,
        SearchDelayIndemnity: 230,
        SearchDelayIndemnityBlock: 231,
        SearchDelayIndemnityLenderOnlyBlock: 232,
        SearchValidationIndemnity: 233,
        SearchValidationIndemnityBlock: 234,
        SearchValidationIndemnityLenderOnlyBlock: 235,
        ServicesIndemnity: 236,
        SewerOrDrainIndemnity: 237,
        TownOrVillageGreenIndemnity: 238,
        UnadoptedDrainsIndemnity: 239,
        UnknownRestrictiveCovenantsRightsAndEasementsIndemnity: 240,
        RestrictiveCovenantsRightsAndEasementsIndemnity: 241,
        ScotlandRestrictiveConditionsRightsAndServitudesIndemnity: 242,
        NIFreeholdRestrictiveCovenantsRightsAndEasementsIndemnity: 243,
        ConveyancingIndemnityLenderOnlyBlock: 244,
        PersonalSearchIndemnityErrorsAndOmissionsBlock: 245,
        PersonalSearchIndemnityMissingAnswersBlock: 246,
        PersonalSearchIndemnityErrorsAndOmissionsAndMissingAnswersBlock: 247,
        StewartplusIndemnityBlock: 248,
        NILeaseholdRestrictiveCovenantIndemnity: 249,
        NILeaseholdRestrictiveCovenantOutstandingRightsAndEasementsIndemnity: 250,
        PersonalSearchIndemnityDWErrorsAndOmissionsAndMissingAnswersBlock: 251,
        PersonalSearchIndemnityDWErrorsAndOmissionsBlock: 252,
        EnvironmentalIndemnityBlock: 253,
        EnvironmentalAndChancelIndemnityBlock: 254,
        LackOfPlanningBuildingRegulationAndConservationAreaConsentIndemnity: 255,
        LackOfPlanningBuildingRegulationAndListedBuildingConsentIndemnity: 256,
        NILackOfPlanningBuildingRegulationAndConservationAreaConsentIndemnity: 257,
        NILackOfPlanningBuildingRegulationAndListedBuildingConsentIndemnity: 258,
        FullTitleForOwner: 259,
        FullTitleForLender: 260,
        KnownDefectForOwner: 261,
        KnownDefectForLender: 262,
        GapCoverForOwnerRegistration: 263,
        GapCoverForLoanRegistration: 264,
        StewartplusFraudIndemnityLenderOnlyBlock: 265,
        StewartplusFraudIndemnityPurchaserAndLenderBlock: 266,
        StewartplusIndemnityLenderOnlyBlock: 267,
        SStewartplusIndemnityPurchaserAndLenderBlock: 268,
        FraudSolutionPolicy: 269,
        FraudSolutionPolicyBlock: 270,
        ScotlandFraudSolutionPolicy: 271,
        ScotlandFraudSolutionPolicyBlock: 272,
        LackOfInstallationsBlock: 273,
        ConveyancingNoSearchesBlock: 274,
        ScotlandLackOfPlanningBuildingRegulationAndListedBuildingConsentIndemnity: 275,
        ResidentialJapaneseKnotweedInsuranceIndemnity: 276,
        INNSAContractorMembersInsuranceBackedGuaranteeBlock: 277,
        ForfeitureOfLeaseHousingActPossessionLenderOnlyIndemnity: 278
};
TemplateTypesEnum = {
        Policy: 1,
        Endorsement: 2,
        Quote: 3,
        Correspondence: 4
};

$.extend(true, Premium, {
    setProperties: function () {        
        var that = this;

        //set country
        if ((that.RiskID > 0 && that.RiskID < 200) || (that.RiskID > 1000 && that.RiskID < 1200))
            that.set("CountryID", { ID: CountriesEnum.England }); //incl. Wales and Isle of Man 
        else if ((that.RiskID > 200 && that.RiskID < 300) || (that.RiskID > 1200 && that.RiskID < 1300))
            that.set("CountryID", { ID: CountriesEnum.Scotland });
        else if ((that.RiskID > 300 && that.RiskID < 400) || (that.RiskID > 1300 && that.RiskID < 1400))
            that.set("CountryID", { ID: CountriesEnum.NorthernIreland });

        //set property type
        if (that.RiskID < 1000) that.set("PropertyTypeID", { ID: 1 }); //residential
        else that.set("PropertyTypeID", { ID: 2 }); //commercial
    }
});
function MessageViewModel(container, actions, args) {
    var that = null;

    this.message = null;

    this.setParams = function (p) {
        that.set("message", p.message);
        that.set("callback", p.callback);
        that.window = p.window;
    };

    this.setObservable = function (o) {
        that = o;
    };

    this.okHandler = function (e) {        
        if (that.callback) that.callback();
        that.window.close();
    };
}
function ConfirmationViewModel(container, actions, args) {
    var that = null;

    this.message = null;
    this.validator = null;
    this.notes = null; //optional
    this.notelabel = null; //optional
    this.noterequired = false; //optional

    this.setParams = function (p) {
        that.set("message", p.message);
        that.set("callback", p.callback);
        that.set("notelabel", p.notelabel); //optional
        that.set("noterequired", p.noterequired); //optional
        that.window = p.window;
    };

    this.setObservable = function (o) {
        that = o;

        that.validator = args.validator;
    };

    this.cancelHandler = function (e) {
        that.window.close();
    };

    this.okHandler = function (e) {
        if (that.validator.validate()) {
            if (that.callback) that.callback({ notes: that.notes });
            that.window.close();
        }
    };
}
function CookieViewModel(container, actions, args) {
    var that = null;
    this.showNotification = false;
    this.cookieName = args.cName;
    this.cookieVersion = args.cVersion;

    this.setObservable = function (o) {
        that = o;
        that.verifyCookie();
    };

    this.verifyCookie = function () {
        post({
            url: actions.verifyCookie,
            dataType: "json",
            callback: function (data) {
                if (data.showCookieNotice)
                    that.set("showNotification", true);
                else
                    that.set("showNotification", false);
            },
            headers: {
                RequestVerificationToken: antiforgeryToken
            }
        });
    }

    this.acceptNotification = function () {
        post({
            url: actions.setCookie,
            dataType: "json",
            callback: function (data) {
                if (data.status == "OK")
                    that.set("showNotification", false);
            },
            headers: {
                RequestVerificationToken: antiforgeryToken
            }
        });
    }
        
    this.displayFileHandler = function (e) {
        var url = e.sender.element.data("url");
        var permissions = e.sender.element.data("permittedactions");
        if (permissions && !verifyPermissions(permissions, sessionContext.currentUser.Permissions)) {
            showMessage(localizedResource.ErrorModalTitle, localizedResource.UnauthorizedAccessMessage);
            return;
        }
        else window.open(url);
    };
}
function RibbonViewModel(container, element) {
    var that = null;
    var invalidElements = [];

    this.taskWindow = {};
    this.taskWindowModel = {};  

    this.entity = null;
    this.validator = null;
    this.panelbar = null;

    this.saveAction = null;
    this.saveAndReleaseAction = null;
    this.saveCallback = null;
    this.saveElement = "#ribbon-save";

    this.releaseAction = null;
    this.savePermissions = null;
    this.entityReleased = false;

    this.setObservable = function (o) {
        that = o;

        that.set("savePermissions", $(that.saveElement).data("permittedactions"));

       sessionTimeout.subscribe("ribbonsave", that.saveAndReleaseHandler);

        $(window).unbind("resize.ribbon").bind("resize.ribbon", function () {
            if (that.panelbar) that.panelbar.accordion("refresh");
        });

        //listen to beforeunload event to release locks when browser tab/browser is closed
        //this is not fired in iOS devices
        $(window).unbind("beforeunload.ribbon").bind("beforeunload.ribbon", function (e) {  
            that.unloadViewModelHandler();
        });
    };

    this.removeUnloadHandler = function () {
        $(window).unbind("beforeunload.ribbon")
    };

    this.initialize = function (e) {
        that.entity = e.entity;
        that.validator = e.validator;
        that.saveAction = e.saveAction;
        that.saveAndReleaseAction = e.saveAndReleaseAction;
        that.saveCallback = e.saveCallback;
        that.releaseAction = e.releaseAction;
        that.panelbar = e.panelbar;

        that.trigger("change", { field: "saveVisibilityHandler" });
    };

    // used to release entity locks as beforeunload event not fired on iOS
    this.releaseAndNavigateUrlHandler = function (e) {    
        var options = {};
        var url = e.sender.element.data("url");

        options.newWindow = e.sender.element.data("new-window");
        options.width = e.sender.element.data("width");
        options.height = e.sender.element.data("height");
        options.permissions = e.sender.element.data("permittedactions");

         //call to release locks here to ensure releasing of locks in iOS devices
        that.unloadViewModelHandler();
        if (url) redirectViewHandler(url, options);
    };

    this.navigateUrlHandler = function (e) {
        var options = {};
        var url = e.sender.element.data("url");

        options.newWindow = e.sender.element.data("new-window");
        options.width = e.sender.element.data("width");
        options.height = e.sender.element.data("height");
        options.permissions = e.sender.element.data("permittedactions");

        if (url) redirectViewHandler(url, options);
    };

    this.openCalculatorHandler = function (e) {
        var calculator = $("#ribbon-calculator").data("kendoWindow");
        var url = e.sender.element.data("url");
        calculator.open();
    };

    this.closeCalculatorHandler = function (e) {
    };

    this.saveEntityHandler = function (e) {
        if ((e && e.canSave) || canSave()) {
            post({
                url: that.saveAction,
                dataType: "json",
                data: (that.entity.ActivityLogCollection != null && that.entity.PolicyHistoryCollection != null) ? JSON.stringify(that.entity, jsonReplace) : JSON.stringify(that.entity),
                callback: function (d) {
                    if (that.entity && that.entity.Update)
                        that.entity.Update(d);

                    if (that.saveCallback)
                        that.saveCallback(d);                    
                },
                headers: {
                    RequestVerificationToken: antiforgeryToken
                },
                permissions: that.savePermissions,
                submitElement: that.saveElement,
                resubmittable: true
            });
        }
        else {
            if (that.saveCallback)
                that.saveCallback(invalidElements);
        }
    };

    this.saveAndReleaseHandler = function (e) {
        if (canSave()) {
            if (navigator && navigator.sendBeacon && that.saveAndReleaseAction != null) {
                that.saveAction = that.saveAndReleaseAction;                
            }
            post({
                url: that.saveAction,
                async: false,
                dataType: "json",
                data: (that.entity.ActivityLogCollection != null && that.entity.PolicyHistoryCollection != null) ? JSON.stringify(that.entity, jsonReplace) : JSON.stringify(that.entity),
                callback: function (d) {                    
                    releaseEntityLock({ entity: d, callback: e ? e.callback : null });
                },
                headers: {
                    RequestVerificationToken: antiforgeryToken
                },
                hideLoading: true,
                permissions: that.savePermissions,
                useSendBeacon: true
            });
        }
        else {
            releaseEntityLock({ entity: that.entity, callback: e ? e.callback : null });
        }
    };
    
    var canSave = function () {
        return that.saveAction && that.entity != null && !that.entity.IsDeleted && !that.entity.IsReadOnly && sessionContext.currentUser &&
            validateFieldsHandler() && verifyPermissions(that.savePermissions, sessionContext.currentUser.Permissions);
    };

    this.unloadViewModelHandler = function () {
        that.saveAndReleaseHandler();
    };

    this.saveVisibilityHandler = function () {
        return that.saveAction && verifyPermissions(that.savePermissions, sessionContext.currentUser.Permissions);
    };  

    var validateFieldsHandler = function (e) {
        var valid = true;
        if (that.validator != null) {
            var fields = that.validator.element.find("[validationmessage],[validationfield]");
            $.each(fields, function (k, v) {
                var element = $(v);
                if (!that.validator.validateInput(element)) {
                    invalidElements.addifnotexists(element);
                    valid = false;
                }
                else {
                    invalidElements.removeItem(element);
                }
            });
        }
        return valid;
    };

    var releaseEntityLock = function (e) {
        if (that.releaseAction && !e.entity.IsReadOnly && sessionContext.currentUser && !that.entityReleased) {
            that.entityReleased = true; //to avoid calling twice on non-iOS devices
            post({
                url: that.releaseAction,
                async: false,
                data: (e.entity.ActivityLogCollection != null && e.entity.PolicyHistoryCollection != null) ? JSON.stringify(e.entity, jsonReplace) : JSON.stringify(e.entity),
                dataType: "json",
                callback: function () {
                    if (e.callback) e.callback();
                },
                hideLoading: true,
                useSendBeacon: true
            });
        }
        else {
            if (e.callback) e.callback();
        }
    };

    var refresh = function () {
        that.entity = null;
        that.validator = null;
        that.panelbar = null;
        that.saveAction = null;
        that.saveCallback = null;
        that.releaseAction = null;
        that.savePermissions = null;
        that.saveAndReleaseAction = null;
    }

    this.createTaskHandler = function () {
        toggleElementsEnabled($("#index-createtask-btn"), false);
        that.taskWindow.data("Params", { transaction: null, window: that.taskWindow });
        that.taskWindow.show($("#index-createtask-btn"));
    };
}
function SearchViewModel(action) {
    var that = null;

    //these properties can be set the criteria in the child view model
    this.container = null;
    this.validator = null;
    this.criteria = null;
    this.token = null;
    this.pageSize = null;
    this.results = [];
    this.searchResultsMessage = null;
    this.searchMessageVisible = false;
    this.searchMessageColor = "#952333";
    this.maxResults = 100;
    this.gridSizeClass = "c-sm-h8-grid";

    this.setObservable = function (o) {
        that = o;
    };

    this.searchEntityHandler = function () {
        if (that.canSearch()) {
            post({
                url: action,
                dataType: "json",
                data: kendo.stringify(that.criteria),
                beforesend: that.searchBeforesendHandler,
                callback: function (e) {
                    e.convertAllDateStrings();
                    that.set("results", new kendo.data.DataSource({
                        data: e,
                        pageSize: that.pageSize != null ? that.pageSize : 25
                    }));

                    if (that.validator)
                        that.validator.hideMessages();

                    that.toggleSearchResultsMessage(e);

                    if (that.callbackSearchHandler)
                        that.callbackSearchHandler(e);
                },
                headers: {
                    RequestVerificationToken: that.token
                }
            });
        }
    };

    this.toggleSearchResultsMessage = function (e) {
        if (e && e.length >= that.maxResults) {
            that.set("searchMessageColor", "#952333");
            that.set("searchMessageVisible", true);
            that.set("searchResultsMessage", kendo.format(localizedResource.SearchOverMaxResultsMessage, that.maxResults));
        }
        else {
            that.set("searchMessageVisible", false);
            that.set("searchResultsMessage", null);
        }
    };

    //overridable function
    this.searchBeforesendHandler = function (x, o) {
    };

    this.resetCriteriaHandler = function () {
        that.set("criteria", null);
    };

    this.canSearch = function () {
        if (that.validator != null) return that.validator.validate() && that.criteria != null;
        else return that.criteria != null;
    };

    this.panelbarSelectHandler = function (e) {
        var animation = e.sender.options.animation;
        var timeout = animation && animation.expand.duration;
        window.setTimeout(function () { that.resizeGridHandler(); }, timeout + 100);   //add buffer (100 ms) + animation duration 
    };

    this.panelbarExpandHandler = function (e) {
        that.container.toggleClass(that.gridSizeClass, true);

    };

    this.panelbarCollapseHandler = function (e) {
        that.container.toggleClass(that.gridSizeClass, false);

    };

    this.resultDataBoundHandler = function () {
        window.setTimeout(function () { that.resizeGridHandler(); }, 300);   //add buffer (300 ms)    
    };

    this.resizeGridHandler = function () {
        resizeGrid($("#search-result"), { top: $("#search-criteria"), header: $("#search-grid-header"), footer: $("#search-footer") });
    };
}
function MainLayoutViewModel(container, actions, args) {
    var that = null;

    this.selectedMenuItem = null;
    this.topMenuVisibility = true;
    this.progressValue = null;

    this.setObservable = function (o) {
        that = o;

        that.set("progressValue", sessionTimeout.elapsed);        

        sessionTimeout.subscribe("mainlayout", function () {
            that.set("currentUser", null);
        });

        $(sessionTimeout).bind("elapsed", function (e) {
            that.set("progressValue", sessionTimeout.elapsed);
        });

        //set selected menu item for main toolbar
        that.set("selectedMenuItem", args.selectedMenu != null ? args.selectedMenu : 0);
    };

    this.logoutHandler = function () {
        if (ribbonViewModel) {
            //ribbonViewModel.saveAndReleaseHandler({ callback: signoutHandler });
            ribbonViewModel.saveAndReleaseHandler();
            signoutHandler();
        }    
        else signoutHandler();
    };

    this.releaseAndNavigateUrlHandler = function (e) {
        var url = e.sender.element.data("url");
        if (ribbonViewModel) {
            ribbonViewModel.unloadViewModelHandler();
        }
        if (url) redirectViewHandler(url);
    };

    this.navigateUrlHandler = function (e) {
        var url = e.sender.element.data("url");
        if (url) redirectViewHandler(url);
    };

    this.topMenuVisibilityHandler = function (e) {
        return that.currentUser != null && that.topMenuVisibility;
    };

    this.extendTimeHandler = function () {
        sessionTimeout.extend();
        $(".k-progressbar").css("background-color", "#0063FF");
    };

    this.onProgressBarChange = function (e) {
        minutes = "0" + Math.floor(e.value / 60);
        seconds = "0" + e.value % 60;
        e.sender.progressStatus.text(localizedResource.SessionWillExpireInLabel + " " + minutes.substr(minutes.length - 2) + ":" + seconds.substr(seconds.length - 2));

        if (e.value == 300) // 5 min.
            $(".k-progressbar").css("background-color", "#9A0000");
        else if (e.value == 0)
            e.sender.progressStatus.text(localizedResource.SessionExpiredMessage);
    };

    var signoutHandler = function () {
        post({
            url: actions.logoutAction,
            dataType: "json",
            callback: function (data) {
                sessionStorage.clear();
                sessionContext.clear();
                redirectViewHandler(data.redirect);
            },
            headers: {
                RequestVerificationToken: antiforgeryToken
            }
        });
    };   
};
