/* Minification failed. Returning unminified contents.
(3359,53-54): run-time error JS1014: Invalid character: `
(3359,59-64): run-time error JS1306: Invalid numeric literal: 100vh
(3359,68-69): run-time error JS1193: Expected ',' or ')': {
(3359,99-100): run-time error JS1004: Expected ';': )
(3359,100-101): run-time error JS1014: Invalid character: `
(3368,35-36): run-time error JS1195: Expected expression: >
(3370,14-15): run-time error JS1195: Expected expression: )
(3425,5-6): run-time error JS1002: Syntax error: }
(3426,51-52): run-time error JS1004: Expected ';': {
(3437,1-2): run-time error JS1002: Syntax error: }
(3439,33-34): run-time error JS1004: Expected ';': {
(9174,52-53): run-time error JS1014: Invalid character: `
(9174,63-64): run-time error JS1014: Invalid character: `
(11357,197-198): run-time error JS1195: Expected expression: )
(11357,199-200): run-time error JS1195: Expected expression: >
(11357,202-203): run-time error JS1195: Expected expression: )
(11357,204-205): run-time error JS1195: Expected expression: >
(11357,9091-9092): run-time error JS1195: Expected expression: >
(11357,9202-9203): run-time error JS1002: Syntax error: }
(11357,9332-9333): run-time error JS1002: Syntax error: }
(11357,9487-9488): run-time error JS1002: Syntax error: }
(11357,9502-9503): run-time error JS1197: Too many errors. The file might not be a JavaScript file: >
(3435,9-24): run-time error JS1018: 'return' statement outside of function: return backdrop
(3424,9-22): run-time error JS1018: 'return' statement outside of function: return dialog
*/
if (this.JSON && !this.JSON.dateParser) {
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.?\d*))(?:Z|(\+|-)([\d|:]*))$/;
var reISONoTimezone = /^(\d{4})-(\d{2})-(\d{2})[ ](\d{2}):(\d{2}):(\d{2}(?:\.?\d*))$/;
var reISONoTimezoneFormat = "yyyy-MM-dd HH:mm:ss";
const oriJSONOBJ = JSON;
oriJSONOBJ.useDateParser = function (reset) {
///
/// Globally enables JSON date parsing for JSON.parse().
/// replaces the default JSON parser with parse plus dateParser extension
///
/// when set restores the original JSON.parse() function
// if any parameter is passed reset
if (typeof reset != "undefined") {
if (oriJSONOBJ._parseSaved) {
oriJSONOBJ.parse = oriJSONOBJ._parseSaved;
oriJSONOBJ._parseSaved = null;
}
} else {
if (!oriJSONOBJ.parseSaved) {
oriJSONOBJ._parseSaved = oriJSONOBJ.parse;
oriJSONOBJ.parse = oriJSONOBJ.parseWithDate;
}
}
};
oriJSONOBJ.dateParser = function (key, value) {
if (typeof value === 'string') {
if (reISONoTimezone.exec(value)) {
var date = Date.parseExact(value, reISONoTimezoneFormat);
if (date != null) {
return date;
}
}
else if (reISO.exec(value)) {
return new Date(value);
}
}
return value;
};
oriJSONOBJ.parseWithDate = function (json) {
var parse = oriJSONOBJ._parseSaved ? oriJSONOBJ._parseSaved : oriJSONOBJ.parse;
try {
var res = parse(json, oriJSONOBJ.dateParser);
return res;
} catch (e) {
// orignal error thrown has no error message so rethrow with message
throw new Error("JSON content could not be parsed");
}
};
oriJSONOBJ.dateStringToDate = function (dtString, nullDateVal) {
if (!nullDateVal)
nullDateVal = null;
if (!dtString)
return nullDateVal;
if (dtString.getTime)
return dtString;
if (dtString[0] === '"' || dtString[0] === "'")
dtString = dtString.substr(1, dtString.length - 2);
if (reISONoTimezone.exec(dtString)) {
return Date.parseExact(dtString, reISONoTimezoneFormat);
}
else if (reISO.exec(dtString)) {
return new Date(dtString);
}
return nullDateVal;
};
oriJSONOBJ.useDateParser();
}
// Warn if overriding existing method
if (Array.prototype.equals)
console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l = this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "equals", { enumerable: false });
Object.defineProperty(Array.prototype, "distinct", {
enumerable: false,
value: function () {
var result = [];
this.each(function (item) { result.add(item) });
return result;
}
});
Object.defineProperty(Array.prototype, "itemEquals", {
enumerable: false,
value: function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
var distinctedThis = this.distinct();
// compare lengths - can save a lot of time
if (distinctedThis.length != array.distinct().length)
return false;
for (var i = 0, l = distinctedThis.length; i < l; i++) {
if (array.indexOf(this[i]) < 0) {
return false;
}
}
return true;
}
});
Object.isEquals = function (obj1, obj2) {
if (obj1 == obj2)
return true;
if (Array.isArray(obj1) && obj1.itemEquals(obj2)) {
return true;
}
if (Date.IsDate(obj1) && JSON.stringify(obj1) == JSON.stringify(obj2)) {
return true;
}
return false;
}
Object.isDeepEquals = function (obj1, obj2, isPartial) {
if (obj1 == obj2)
return true;
if (Array.isArray(obj1) && obj1.itemEquals(obj2)) {
return true;
}
if (typeof obj1 == "object") {
if (isPartial) {
var obj1Key = Object.keys(obj1);
var obj2Key = Object.keys(obj2);
var keys = obj1Key.length > obj2Key.length ? obj2Key : obj1Key;
var replacer = function (k, v) {
if (k && keys.indexOf(k) < 0) {
return undefined;
}
return v;
};
return JSON.stringify(obj1, replacer) == JSON.stringify(obj2, replacer);
}
else if (JSON.stringify(obj1) == JSON.stringify(obj2)) {
return true;
}
}
return false;
}
Array.prototype.find = function (fn) {
// if the other array is a falsy value, return
if (typeof (fn) == "function") {
for (var i = 0; i < this.length; i++) {
if (fn(this[i], i, this)) {
return this[i];
}
}
}
return null;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "find", { enumerable: false });
Array.prototype.each = function (fn) {
if (typeof (fn) == "function") {
var temp = ([]).concat(this);
for (var i = 0; i < temp.length; i++) {
if (fn.call(this, temp[i], i, this) == false)
break;
}
}
}
Object.defineProperty(Array.prototype, "each", { enumerable: false });
Array.prototype.findAll = function (fn) {
// if the other array is a falsy value, return
var result = [];
if (typeof (fn) == "function") {
for (var i = 0; i < this.length; i++) {
if (fn(this[i], i, this)) {
result.push(this[i]);
}
}
}
return result;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "findAll", { enumerable: false });
Array.prototype.remove = function (item) {
var index = this.indexOf(item);
if (index >= 0) {
this.splice(index, 1);
return true;
}
return false;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "remove", { enumerable: false });
Array.prototype.add = function (item, index) {
var isExist = this.indexOf(item) >= 0;
if (!isExist) {
index = typeof (index) === "number" ? index : this.length;
this.splice(index, 0, item);
return true;
}
return false;
}
// Hide method from for-in loops
Object.defineProperty(Array.prototype, "add", { enumerable: false });
Object.isEmptyValue = function (value) {
return value === "" || value === null || value === undefined;
}
Object.defineProperty(Array.prototype, "select", {
enumerable: false,
value: function (fn, isDistinct) {
// if the other array is a falsy value, return
var result = [];
if (typeof (fn) == "function") {
for (var i = 0; i < this.length; i++) {
var value = fn(this[i], i, this);
if (typeof (value) !== "undefined" && value != null) {
result[isDistinct ? 'add' : 'push'](value);
}
}
}
return result;
}
});
Object.defineProperty(Array.prototype, "selectMany", {
enumerable: false,
value: function (fn, isDistinct) {
// if the other array is a falsy value, return
var result = [];
if (typeof (fn) == "function") {
for (var i = 0; i < this.length; i++) {
var value = fn(this[i], i, this);
if (typeof (value) !== "undefined" && Array.isArray(value)) {
value.each(function (item) {
result[isDistinct ? 'add' : 'push'](item);
});
}
}
}
return result;
}
});
Object.defineProperty(Array.prototype, "group", {
enumerable: false,
value: function (fn) {
// if the other array is a falsy value, return
var result = [];
if (typeof (fn) == "function") {
for (var i = 0; i < this.length; i++) {
var value = fn(this[i], i, this);
var existingGroup = result.find(function (item) { return item.Key == value; });
if (existingGroup == null) {
existingGroup = {
Key: value,
Items: []
};
result.add(existingGroup);
}
existingGroup.Items.add(this[i]);
}
}
return result;
}
});
Date.IsDate = function (object) {
return Object.prototype.toString.call(object) === '[object Date]';
}
Date.prototype.toJSON = function () {
return this.toString("yyyy-MM-dd HH:mm:ss");
}
if (!String.prototype.formatString) {
Object.defineProperty(String.prototype, "formatString", {
value: function () {
result = this;
if (arguments) {
for (var i = 0; i < arguments.length; i++) {
var regex = new RegExp("\\{" + i + "\\}", "g");
result = result.replace(regex, arguments[i]);
}
}
return result;
},
enumerable: false
});
}
// register collection changes listener
if (!Array.prototype.OnCollectionChange) {
functions = ['push', 'pop', 'shift', 'unshift', 'sort', 'reverse', 'splice'];
var stub = function (mtd) {
var old = Array.prototype[mtd];
Array.prototype[mtd] = function () {
var result = null;
if (this.OnCollectionChange) {
var oldValue = ([]).concat(this);
result = old.apply(this, arguments);
var newValue = ([]).concat(this);
this.OnCollectionChange(oldValue, newValue, result, this);
}
else {
result = old.apply(this, arguments);
}
return result
}
}
for (_i = 0, _len = functions.length; _i < _len; _i++) {
stub(functions[_i]);
}
}
var EventManager = {
HasTransitionSupport: function () {
var thisBody = document.body || document.documentElement;
var thisStyle = thisBody.style;
var support = (
thisStyle.transition !== undefined ||
thisStyle.WebkitTransition !== undefined ||
thisStyle.MozTransition !== undefined ||
thisStyle.MsTransition !== undefined ||
thisStyle.OTransition !== undefined
);
return support;
},
IsTouchEvent: function () {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
},
RegisterEvent: function (element, eventNames, fn, isUnique) {
if (!element) return;
eventNames = eventNames.split(" ");
for (var i = 0; i < eventNames.length; i++) {
var eventName = eventNames[i];
if (!element["__" + eventName]) {
element["__" + eventName] = [];
}
if (isUnique && element["__" + eventName].indexOf(fn) >= 0)
continue;
element["__" + eventName].push(fn);
if (element.addEventListener) {
element.addEventListener(eventName, fn, false);
}
else {
if (element.attachEvent) { // IE before version 9
element.attachEvent("on" + eventName, fn);
}
}
}
},
RemoveEvents: function (element, eventNames, event) {
if (!element) return;
eventNames = eventNames.split(" ");
for (var i = 0; i < eventNames.length; i++) {
var events = [];
var eventName = eventNames[i];
if (element["__" + eventName]) {
if (!event) {
events = element["__" + eventName];
}
else if (!Array.isArray(event)) {
events = [event];
}
for (var j = 0; j < events.length; j++) {
if (element.removeEventListener) {
element.removeEventListener(eventName, events[j]);
}
else {
if (element.detachEvent) { // IE before version 9
element.detachEvent("on" + eventName, events[j]);
}
}
var index = element["__" + eventName].indexOf(events[j]);
element["__" + eventName].splice(index, 1);
}
}
}
},
TriggerEvent: function (element, eventNames) {
if (element) {
eventNames = eventNames.split(" ");
for (var i = 0; i < eventNames.length; i++) {
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent(eventNames[i], false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("on" + eventNames[i]);
}
}
},
}
function ExtendableObject(options) {
// already defined previously
if (this.SetOptions)
return;
Object.defineProperty(this, "SetOptions", {
value: function (options) {
if (!options) {
return false;
}
for (var key in options) {
if (options[key] == null || options[key] == undefined) {
continue;
}
this[key] = options[key];
}
},
writable: false,
enumerable: false,
configurable: false
});
Object.defineProperty(this, "__SetMethod", {
value: function (methodName, fn) {
if (!methodName || typeof (fn) != "function") {
return false;
}
Object.defineProperty(this, methodName, {
value: fn,
writable: true,
enumerable: false,
configurable: true
});
},
writable: false,
enumerable: false,
configurable: false
});
Object.defineProperty(this, "__SetProperty", {
value: function (propertyName, setter, getter) {
if (!propertyName) {
return false;
}
var option = {
enumerable: true,
configurable: true
};
if (typeof (getter) == "function" || typeof (setter) == "function") {
if (typeof (setter) == "function")
option.set = setter
if (typeof (getter) == "function")
option.get = getter;
}
else {
option.value = setter;
option.writable = true;
}
Object.defineProperty(this, propertyName, option);
},
writable: false,
enumerable: false,
configurable: false
});
this.SetOptions(options);
}
ExtendableObject.prototype.ExtendObject = function (object, options) {
if (!options) {
return false;
}
for (var key in options) {
if (options[key] == null || options[key] == undefined) {
continue;
}
object[key] = options[key];
}
return true;
}
// query descriptor object
function PageDescriptor(options) {
this.PageIndex = 0;
this.PageSize = 0;
this.TotalItemCount = 0;
this.LastQueryDate = null;
ExtendableObject.call(this, options);
}
function FilterDescriptor(options) {
this.IsCaseSensitive = false;
this.Operator = "Contains";
this.PropertyName = "";
this.Value = "";
ExtendableObject.call(this, options);
}
function SelectDescriptor(options) {
this.Aggregate = "None";
this.Alias = "";
this.NavigationPropertyName = "";
this.PropertyName = "";
ExtendableObject.call(this, options);
}
function QueryDescriptor(options) {
this.SortDescriptors = [];
this.FilterDescriptors = [];
this.Includes = [];
this.Selects = [];
this.SuspendQueryChanged = false;
this.PageDescriptor = new PageDescriptor();
ExtendableObject.call(this, options);
}
// validation
function ValidationResult(options) {
this.IsSuccess = false;
this.Message = "";
this.MemberName = "";
ExtendableObject.call(this, options);
}
function FieldValidationResult(options) {
this.IsSuccess = true;
this.ErrorMessages = [];
ExtendableObject.call(this, options);
this.AddValidationResult = function (validationResult) {
if (!validationResult.IsSuccess) {
this.ErrorMessages.push(validationResult.Message);
}
this.IsSuccess = this.IsSuccess && validationResult.IsSuccess;
}
}
function ValidationResultInfo(options) {
ExtendableObject.call(this, options);
this.IsSuccess = true;
this.__SetMethod("AddValidationResult", function (memberName, validationResult) {
if (!this[memberName]) {
this[memberName] = new FieldValidationResult();
}
var fieldValidResult = this[memberName];
fieldValidResult.AddValidationResult(validationResult);
this.IsSuccess = this.IsSuccess && fieldValidResult.IsSuccess;
});
}
function ValidatorBase(options) {
this.ErrorMessage = "";
this.MemberName = "";
this.ApplyDecoration = function (el, entity, validationResult) { };
ExtendableObject.call(this, options);
this.GetErrorMessage = function (source) {
return this.ErrorMessage.replace(/\{0\}/ig, this.MemberName);
}
this.IsValid = function (source) {
return true;
};
this.Validate = function (source) {
var result = new ValidationResult({ MemberName: this.MemberName });
result.IsSuccess = this.IsValid(source);
result.Message = result.IsSuccess ? "" : this.GetErrorMessage(source);
return result;
};
}
function RequiredValidator(options) {
ValidatorBase.call(this, options);
this.ApplyDecoration = function (el, entity, validationResult) {
if (!el.Decoration) {
var label = el.querySelector(".control-label");
if (label) {
el.Decoration = document.createElement("span");
el.Decoration.className = "required-decoration";
label.appendChild(el.Decoration);
$(el.Decoration).attr("data-title", App.Resources.FieldRequired).attr("data-placement", "auto right").tooltip({ container: el.Decoration.ownerDocument.body });
}
}
if (!entity.IsNew && el.Decoration) {
if (entity.__originalValues.hasOwnProperty(this.MemberName) && !this.IsValid(entity)) {
el.Decoration.className = "required-decoration";
el.Decoration.alwaysVisible = true;
}
else if (!el.Decoration.alwaysVisible) {
el.Decoration.className = "hide";
}
}
};
this.IsValid = function (source) {
return !Object.isEmptyValue(source[this.MemberName]) && !!source[this.MemberName].toString().trim();
};
}
function MinValidator(options) {
this.Minimum = 0;
ValidatorBase.call(this, options);
this.GetErrorMessage = function (source) {
return this.ErrorMessage.replace(/\{0\}/ig, this.MemberName).replace(/\{1\}/ig, this.Minimum);
}
this.IsValid = function (source) {
return Object.isEmptyValue(source[this.MemberName]) || source[this.MemberName] >= this.Minimum;
};
}
function MaxValidator(options) {
this.Maximum = 0;
ValidatorBase.call(this, options);
this.GetErrorMessage = function (source) {
return this.ErrorMessage.replace(/\{0\}/ig, this.MemberName).replace(/\{1\}/ig, this.Maximum);
}
this.IsValid = function (source) {
return Object.isEmptyValue(source[this.MemberName]) || source[this.MemberName] <= this.Maximum;
};
}
function StringLengthValidator(options) {
this.MaximumLength = 100;
this.MinimumLength = 0;
ValidatorBase.call(this, options);
this.GetErrorMessage = function (source) {
return this.ErrorMessage.replace(/\{0\}/ig, this.MemberName).replace(/\{1\}/ig, this.MinimumLength).replace(/\{2\}/ig, this.MaximumLength);
}
this.IsValid = function (source) {
return source[this.MemberName].length >= this.MinimumLength && source[this.MemberName].length <= this.MaximumLength;
};
}
function RangeValidator(options) {
this.Maximum = 100;
this.Minimum = 0;
this.Type = "int";
ValidatorBase.call(this, options);
this.GetErrorMessage = function (source) {
return this.ErrorMessage.replace(/\{0\}/ig, this.MemberName).replace(/\{1\}/ig, this.Minimum).replace(/\{2\}/ig, this.Maximum);
}
this.IsValid = function (source) {
return Object.isEmptyValue(source[this.MemberName]) || (source[this.MemberName] >= this.Minimum && source[this.MemberName] <= this.Maximum);
};
}
function RegularExpressionValidator(options) {
this.Pattern = "(?:)";
ValidatorBase.call(this, options);
this.IsValid = function (source) {
var regExp = new RegExp(this.Pattern);
return regExp.test(source[this.MemberName] || "");
};
}
function EmailValidator(options) {
// Use this Regexp. coz .NET RegExp not fully compatible with JS RegExp
options.Pattern = "^((([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,})))?$";
RegularExpressionValidator.call(this, options);
}
function AlphaNumericValidator(options) {
if (!options.Pattern)
options.Pattern = "^[a-zA-Z0-9_]+$";
RegularExpressionValidator.call(this, options);
}
function PasswordValidator(options) {
this.PasswordValidations = [
{
Regex: "^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d])(?=.*[\\W]).*$",
ErrorMessage: "Require 8 or more characters.\r\nContains at least one lowercase letter.\r\nContains at least one uppercase letter.\r\nContains at least one digit.\r\nContains at least one special character."
},
{
Regex: "^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d]).*$",
ErrorMessage: "Require 8 or more characters.\r\nContains at least one lowercase letter.\r\nContains at least one uppercase letter.\r\nContains at least one digit."
},
{
Regex: "^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z]).*$",
ErrorMessage: "Require 8 or more characters.\r\nContains at least one lowercase letter.\r\nContains at least one uppercase letter."
},
{
Regex: "^.*(?=.{8,})(?=.*[a-z]).*$",
ErrorMessage: "Require 8 or more characters.\r\nContains at least one lowercase letter."
},
{
Regex: "^.*(?=.*[a-z]).*$",
ErrorMessage: "Contains at least one lowercase letter."
}
];
this.MinimumLevel = 3;
this.ApplyDecoration = function (el, entity, validationResult) { };
ValidatorBase.call(this, options);
this.IsValid = function (source) {
var pattern = this.PasswordValidations[this.PasswordValidations.length - this.MinimumLevel].Regex;
var regExp = new RegExp(pattern);
return source[this.MemberName] ? regExp.test(source[this.MemberName]) : false;
};
}
function VerifyPasswordValidator(options) {
this.PasswordProperty = [];
ValidatorBase.call(this, options);
this.IsValid = function (source) {
return source[this.MemberName] == source[this.PasswordProperty];
};
}
function ClientValidator(options) {
this.ClientValidate = "";
ValidatorBase.call(this, options);
this.ApplyDecoration = function (el, entity, validationResult) {
this.Window = el.ownerDocument.defaultView || el.ownerDocument.parentWindow;
};
this.IsValid = function (source) {
var result = true;
if (!this.Window || !this.Window.eval) // if Windows.eval is undefined, means this validator is no longer valid (typically from modal)
return result;
var fn = (this.Window || window).eval("( function(source){" + this.ClientValidate + "})");
result = fn.call(this, source);
return result;
};
}
function CustomValidator(options) {
ValidatorBase.call(this, options);
this.SetOptions(options);
this.Validate = function (source) {
var result = new ValidationResult({ MemberName: this.MemberName });
result.IsSuccess = this.IsValid(source);
result.Message = result.IsSuccess ? "" : this.GetErrorMessage(source);
return result;
};
}
function GetTabViewCount(view) {
if (Page.HideTabViewCount) {
return "";
}
return "(" + (view.Count ? view.Count : 0) + ")";
}
function DelegateCommand(options) {
this.CanExecuteCommand = function (model, param) {
return true;
}
this.Command = function (model, param) {
}
this.Parameter = null;
ExtendableObject.call(this, options);
var __bind = function (fn, me) { return function (event, model) { return fn.call(me, this, model, event); }; };
this.__Command = __bind(function (el, model, event) {
if (this.__CanExecuteCommand.call(el, event, model)) {
this.Command.call(this, model, el["__command-parameter"], el, event);
}
}, this);
this.__CanExecuteCommand = __bind(function (el, model, event) {
if (this.IsProcessing)
return false;
if (typeof (this.CanExecuteCommand) == "function")
return this.CanExecuteCommand.call(this, model, el["__command-parameter"], el, event) !== false;
else
return true;
}, this);
this.RaiseCanExecuteChange = function () {
App.BindingService.TriggerChange(this, "__CanExecuteCommand");
}
var isProcessing = false;
Object.defineProperty(this, "IsProcessing", {
set: function (value) {
if (isProcessing != value) {
isProcessing = value;
this.RaiseCanExecuteChange();
App.BindingService.TriggerChange(this, "IsProcessing");
}
},
get: function () {
return isProcessing;
},
enumerable: true,
configurable: true,
});
}
// binding
var AliasBindingAdapter = function () {
this.Attibute = "alias-*";
this.block = true;
this.Context = null;
this.priority = 3900;
this.bind = function (el) {
if (this.marker == null) {
var attr = [this.view.prefix, this.type].join('-').replace('--', '-');
this.marker = document.createComment(" rivets: " + this.type + " ");
this.nested = null;
el.removeAttribute(attr);
el.parentNode.insertBefore(this.marker, el);
el.parentNode.removeChild(el);
}
else if (this.nested) {
this.nested.bind();
}
};
this.unbind = function (el) {
if (this.nested)
this.nested.unbind();
};
this.routine = function (el, value) {
var modelName = this.args[0];
var data = {};
data[modelName] = value;
if (!this.nested) {
var _ref2 = this.view.models;
for (var key in _ref2) {
var model = _ref2[key];
if (data[key] == null) {
data[key] = model;
}
}
var template = el.cloneNode(true);
var options = this.view.options();
options.preloadData = true;
this.marker.parentNode.insertBefore(template, this.marker.nextSibling);
this.nested = new this.binder.Context["_"].View(template, data, options);
this.nested.bind();
}
else if (value != this.nested.models[modelName]) {
this.nested.update(data);
}
}
this.update = function (models) {
var data = {};
for (var key in models) {
model = models[key];
if (key !== this.args[0]) {
data[key] = model;
}
}
if (this.nested) {
this.nested.update(data);
}
}
}
var TemplateBindingAdapter = function () {
this.Attibute = "rv-*";
this.block = true;
this.Context = null;
this.priority = 13000;
this.bind = function (el) {
if (this.marker == null) {
this.marker = document.createComment(" rivets: " + this.type + " ");
this.nested = null;
this.attr = [this.view.prefix, this.type].join('-').replace('--', '-');
this.bindingTemplate = el.getAttribute(this.attr);
el.parentNode.insertBefore(this.marker, el);
el.parentNode.removeChild(el);
this.isClone = el.children.length > 0;
}
else if (this.nested) {
this.nested.bind();
}
};
this.unbind = function (el) {
if (this.nested)
this.nested.unbind();
this.nested = null;
if (this.isClone) {
if (this.template.parentNode)
this.template.parentNode.removeChild(this.template);
if (this.marker.parentNode)
this.marker.parentNode.insertBefore(el, this.marker.nextSibling);
}
else {
el.removeAttribute(this.type);
var attr = [this.view.prefix, this.type].join('-').replace('--', '-');
el.setAttribute(attr, this.bindingTemplate);
}
if (this.marker.parentNode)
this.marker.parentNode.removeChild(this.marker);
};
this.routine = function (el, bindingKey) {
var data = {};
if (!this.marker.parentNode)
return;
var oldBindingKey = el.getAttribute(this.type);
if (oldBindingKey != bindingKey || !this.nested) {
this.template = this.isClone ? el.cloneNode(true) : el;
if (this.nested) {
data = this.nested.models;
this.nested.unbind();
for (var __i = 0; __i < this.nested.els.length; __i++)
this.nested.els[__i].parentNode.removeChild(this.nested.els[__i]);
}
else {
var _ref2 = this.view.models;
for (var key in _ref2) {
var model = _ref2[key];
if (data[key] == null) {
data[key] = model;
}
}
}
//this.marker.parentNode.insertBefore(template, this.marker.nextSibling);
var bindingContext = this;
//setTimeout(function () {
this.template.removeAttribute(this.attr);
this.template.setAttribute(this.type, bindingKey);
this.marker.parentNode.insertBefore(this.template, this.marker.nextSibling);
var options = bindingContext.view.options();
options.preloadData = true;
bindingContext.nested = new bindingContext.binder.Context["_"].View(this.template, data, options);
bindingContext.nested.bind();
//});
}
};
this.update = function (models) {
var data = {};
for (key in models) {
model = models[key];
if (key !== this.args[0]) {
data[key] = model;
}
}
if (this.nested) {
this.nested.update(data);
}
}
}
var ImageBindingAdapter = function () {
this.Attibute = "src";
this.publishes = true;
this.Context = null;
this.priority = 5000;
this.bind = function (el) {
return true;
};
this.IsRunning = false;
this.loadlist = [];
this.DoLoad = function (el, value, placeholder) {
placeholder = placeholder ? placeholder : "/assets/images/placeholder/picture.png";
el.src = placeholder;
var img = new Image();
img.onload = function () {
this.el.src = this.src;
};
img.el = el;
img.src = value;
}
this.unbind = function (el) {
return true;
};
this.routine = function (el, value) {
if (el.tagName == "IMG" && el.hasAttribute("background-load"))
this.binder.DoLoad(el, value, el.getAttribute("data-placeholder"));
else
el.setAttribute("src", value);
return value;
}
}
var AddClassAdapter = function () {
this.Attibute = "add-class";
this.PrevValues = [];
this.publishes = true;
this.Context = null;
this.priority = 5000;
this.bind = function (el) {
return true;
};
this.unbind = function (el) {
return true;
};
this.routine = function (el, value) {
var classList = (typeof (value) == "string" ? value : "").split(/[ ]+/);
if (this.PrevValues && this.PrevValues.length > 0) {
this.PrevValues.each(function (o) { el.classList.remove(o); });
}
if (classList && classList.length > 0) {
classList.each(function (o) { el.classList.add(o); });
}
this.PrevValues = classList;
return value;
}
}
var NumberBindingAdapter = function () {
this.Attibute = "value-*";
this.publishes = true;
this.Context = null;
this.priority = 3000;
this.bind = function (el) {
if (this.args[0] !== "currency" && this.args[0] !== "number")
return false;
if (el.tagName !== 'INPUT' || el.type === 'radio' || el.type === 'checkbox')
return false;
var isCurrency = this.args[0] == "currency";
this.publish = App.BindFunction(function (event) {
var args, formatter, id, value, _i, oldValues, _ref1, _ref2, _ref3;
if (this.observer) {
if (event.type == "blur") {
if (this.el.__isFocus) this.el.__isFocus = false;
else
return;
}
value = this.getValue(this.el);
if (!Object.isEmptyValue(value)) {
value = App.UnformatNumber(value);
}
this.binder.routine.call(this, this.el, value);
return this.observer.setValue(value);
}
}, this);
this.focus = App.BindFunction(function () {
this.el.value = App.ToFixedNumber(this.el.__numberValue);
this.el.__isFocus = true;
if (el.value.match(/^0.$/) && el.__oldValue == "0") {
el.value = el.value.replace(/^0/, "");
}
}, this);
this.keydown = function (e) {
this.__oldValue = this.value;
var keyCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (e.ctrlKey == true) {
return true;
}
// Ensure that it is a number and stop the keypress
else if (keyCode >= 65 && keyCode <= 90 || (isCurrency && App.NumberFormat.Currency.DecimalDigit <= 0 && (keyCode == 190 || keyCode == 188))) {
e.preventDefault();
}
};
this.binder.Context["_"].Util.bindEvent(el, "input", this.publish);
this.binder.Context["_"].Util.bindEvent(el, "blur", this.publish);
EventManager.RegisterEvent(el, "keydown", this.keydown);
return this.binder.Context["_"].Util.bindEvent(el, "focus", this.focus);
};
this.unbind = function (el) {
if (this.args[0] !== "currency" && this.args[0] !== "number")
return;
if (el.tagName !== 'INPUT' || el.type === 'radio' || el.type === 'checkbox') {
return;
}
EventManager.RegisterEvent(el, "keydown", this.keydown);
//return this.binder.Context["_"].Util.unbindEvent(el, "input", this.binder.publish);
return this.binder.Context["_"].Util.unbindEvent(el, "blur", this.binder.publish);
return this.binder.Context["_"].Util.unbindEvent(el, "focus", this.binder.focus);
};
this.routine = function (el, value) {
if (this.args[0] !== "currency" && this.args[0] !== "number") {
return;
}
if (this.el.__isFocus) {
var stringVal = value != null && value != undefined ? value.toString() : "";
// check character length. because javascript 17 length number has issue.
if ((el.value != stringVal && stringVal.search(/[^0-9]/) < 0 && el.value.search(/[^0-9]/) < 0) && stringVal.length < 17) {
el.value = stringVal;
}
return;
}
this.el.__numberValue = value;
var rounding = this.el.getAttribute("data-rounding");
var precision = this.el.getAttribute("data-precision");
if (precision == null) {
precision = "6";
}
if (!isNaN(parseInt(value))) {
try {
if (this.args[0] == "number") {
this.el.__numberValue = App.Round(this.el.__numberValue, precision);
value = this.el.__numberValue;
}
} catch (e) {
}
this.el.value = App[this.args[0] == "currency" ? "FormatCurrency" : "FormatNumber"](value, rounding, precision);
}
else
this.el.value = "";
// raised change event
EventManager.TriggerEvent(el, "change");
}
}
var CommandBindingAdapter = function () {
this.Attibute = "command";
this.publishes = true;
this.Context = null;
this.priority = 10000;
this.bind = function (el) {
this.view.buildBinding('Binding', el, "on-click", this.keypath + ".__Command");
var binding = this.view.bindings[this.view.bindings.length - 1];
binding.bind();
this.nestedBindings = [];
this.nestedBindings.push(binding);
this.view.buildBinding('Binding', el, "can-execute-command", this.keypath + ".__CanExecuteCommand");
binding = this.view.bindings[this.view.bindings.length - 1];
binding.bind();
this.nestedBindings.push(binding);
this.view.buildBinding('Binding', el, "command-is-processing", this.keypath + ".IsProcessing");
binding = this.view.bindings[this.view.bindings.length - 1];
binding.bind();
this.nestedBindings.push(binding);
return true;
};
this.unbind = function (el) {
for (var i = 0; i < this.nestedBindings.length; i++) {
this.nestedBindings[i].unbind();
}
return true;
};
this.routine = function (el, value) {
el.__command = value;
if (el.__command && el.__command.RaiseCanExecuteChange)
el.__command.RaiseCanExecuteChange();
return value;
}
}
var CanExecuteCommandBindingAdapter = function () {
this.Attibute = "can-execute-command";
this.publishes = true;
this.Context = null;
this.priority = 10000;
this.routine = function (el, value) {
if (typeof (value) == "function") {
var result = value.call(el, null, this.view.models);
el.disabled = !result;
if (el.disabled) {
el.setAttribute("disabled", "");
el.classList.add("disabled");
}
else {
el.removeAttribute("disabled");
el.classList.remove("disabled");
}
return el.disabled;
}
}
}
// user rv-command-parameter="'stringparam'" for onetime binding.
var CommandParameterBindingAdapter = function () {
this.Attibute = "command-parameter";
this.publishes = true;
this.Context = null;
this.priority = 10000;
this.routine = function (el, value) {
if (el["__command-parameter"] != value) {
el["__command-parameter"] = value;
if (el.__command && el.__command.RaiseCanExecuteChange) {
el.__command.RaiseCanExecuteChange();
}
}
return value;
}
}
var CommandIsProcessingBindingAdapter = function () {
this.Attibute = "command-is-processing";
this.publishes = true;
this.Context = null;
this.priority = 10000;
this.ProccessingTemplate = '
';
this.routine = function (el, value) {
if (!el.hasOwnProperty("__innitialHTML")) {
Object.defineProperty(el, "__innitialHTML", {
value: "",
enumerable: false,
configurable: true,
writable: true
});
}
if (value) {
el.setAttribute("is-processing", true);
el.__innitialHTML = [];
for (var i = 0, length = el.childNodes.length; i < length; i++) {
el.__innitialHTML.push(el.childNodes[0]);
el.removeChild(el.childNodes[0]);
}
el.__initialbackgroundImage = el.style.backgroundImage;
el.style.backgroundImage = "none";
el.innerHTML = this.binder.ProccessingTemplate;
}
else {
el.removeAttribute("is-processing");
if (el.__innitialHTML) {
el.innerHTML = "";
for (var i = 0; i < el.__innitialHTML.length; i++) {
el.appendChild(el.__innitialHTML[i]);
}
el.__innitialHTML = null;
}
if (el.__initialbackgroundImage) {
el.style.backgroundImage = el.__initialbackgroundImage;
el.__initialbackgroundImage = null;
}
}
return value;
}
}
var ShowAnimationBindingAdapter = function () {
this.Attibute = "show-*";
this.publishes = true;
this.Context = null;
this.priority = -1;
this.bind = function (el) {
return true;
};
this.unbind = function (el) {
return true;
};
this.routine = function (el, value) {
if (!el.parentElement) {
var self = this;
setTimeout(function () {
self.binder.routine.call(self, el, value);
}, 100);
return false;
}
var animationType = this.args[0];
switch (animationType) {
case "slide":
if (value) {
var hasMinHeight = el.hasAttribute("data-minheight");
if (el.classList.contains("hide")) {
el.classList.remove("hide");
var ao = {};
var computedStyle = getComputedStyle(el, null);
el.style.minHeight = "0";
ao.height = el.scrollHeight;
if (el.tempStyle) {
ao.height += (!isNaN(parseInt(el.tempStyle.paddingTop)) ? parseInt(el.tempStyle.paddingTop) : 0) + (!isNaN(parseInt(el.tempStyle.paddingBottom)) ? parseInt(el.tempStyle.paddingBottom) : 0)
ao.paddingTop = el.tempStyle.paddingTop;
ao.paddingBottom = el.tempStyle.paddingBottom;
ao.marginTop = el.tempStyle.marginTop;
ao.marginBottom = el.tempStyle.marginBottom;
}
ao.height += parseInt(computedStyle.getPropertyValue("border-top-width")) + parseInt(computedStyle.getPropertyValue("border-bottom-width"));
ao.minHeight = ao.height += "px";
AnimationService.SetAnimationProperty(el, ao, function (el) {
el.style.overflow = "";
el.style.height = "";
if (!hasMinHeight)
el.style.minHeight = "";
});
}
}
else {
if (!el.classList.contains("hide") || !el.tempStyle) {
el.style.overflow = "hidden";
el.style.minHeight = "0";
el.style.height = el.scrollHeight + "px";
AnimationService.SetAnimationProperty(el, { height: "0", paddingTop: "0", paddingBottom: "0", marginTop: "0", marginBottom: "0" }, function (el) {
el.classList.add("hide");
if (!el.tempStyle) {
el.tempStyle = {
paddingTop: el.oriStyle.paddingTop,
paddingBottom: el.oriStyle.paddingBottom,
marginTop: el.oriStyle.marginTop,
marginBottom: el.oriStyle.marginBottom
}
}
});
}
}
break;
default:
value ? AnimationService.Show(el, "animate-" + animationType, function (el) {
el.classList.remove("animate-" + animationType);
el.classList.remove("animate");
}) : AnimationService.Hide(el, "animate-" + animationType);
break;
}
}
}
var TooltipBindingAdapter = function () {
this.Attibute = "tooltip";
this.publishes = true;
this.Context = null;
this.priority = 10000;
this.bind = function (el) {
var doc = el.ownerDocument;
var win = doc.defaultView || doc.parentWindow;
if (win && win.$)
win.$(el).tooltip({ trigger: 'hover' });
return true;
};
this.unbind = function (el) {
var doc = el.ownerDocument;
var win = doc.defaultView || doc.parentWindow;
if (win && win.$)
win.$(el).tooltip('destroy');
return true;
};
this.routine = function (el, value) {
var doc = el.ownerDocument;
var win = doc.defaultView || doc.parentWindow;
if (win && win.$)
win.$(el).tooltip('hide').attr('data-original-title', value);
}
}
var HideAnimationBindingAdapter = function () {
this.Attibute = "hide-*";
this.publishes = true;
this.Context = null;
this.priority = 10000;
this.bind = function (el) {
return true;
};
this.unbind = function (el) {
return true;
};
this.routine = function (el, value) {
return (new ShowAnimationBindingAdapter()).routine.call(this, el, !value);
}
}
var StyleBindingAdapter = function () {
this.Attibute = "style-*";
this.publishes = true;
this.Context = null;
this.priority = 10000;
this.bind = function (el) {
return true;
};
this.unbind = function (el) {
return true;
};
this.routine = function (el, value) {
var prop = this.args[0];
var cssList = el.style.cssText.split(";");
var exist = cssList.find(function (item) { return item.split(":")[0].trim() == prop; });
if (exist) cssList.remove(exist);
cssList.push(prop + ":" + value);
el.setAttribute("style", cssList.join(";"));
return value;
}
}
var WebInputBindingAdapter = function () {
this.Attibute = "webinput-*";
this.publishes = true;
this.priority = 10000;
this.Context = null;
this.GetControl = function (el) {
if (!el.Control) {
var id = el.id;
var doc = el.ownerDocument;
var win = doc.defaultView || doc.parentWindow;
el.Control = win.ISGetObject(id);
}
return el.Control;
}
this.GetProperty = function (prop) {
switch (prop) {
default:
prop = prop[0].toUpperCase() + prop.substring(1);
break;
}
return prop;
}
this.SetValue = function (model, keyPath, value) {
var keys = keyPath.split(".");
keys.shift();
var last = keys.pop();
if (model) {
model[last] = value;
}
};
this.bind = function (el) {
var control = this.binder.GetControl(el);
var prop = this.binder.GetProperty(this.args[0]);
var bindingContext = this;
if (control.hasOwnProperty(prop)) {
var bValue = control[prop];
Object.defineProperty(control, prop, {
get: function () { return bValue; },
set: function (newValue) {
if (newValue != bValue) {
bValue = newValue;
if (prop == "Value") {
var temValue = bValue;
var dateData = (temValue == "" && this.Nullable) ? null : this.GetDateTimeValueData();
if (dateData)
temValue = dateData;
bindingContext.binder.SetValue(bindingContext.model, bindingContext.keypath, temValue);
}
else {
bindingContext.binder.SetValue(bindingContext.model, bindingContext.keypath, bValue);
}
}
},
enumerable: true,
configurable: true
});
}
return true;
};
this.unbind = function (el) {
var control = this.binder.GetControl(el);
var prop = this.binder.GetProperty(this.args[0]);
if (control.hasOwnProperty(prop)) {
Object.defineProperty(control, prop, {
value: control[prop],
writable: true,
enumerable: true,
configurable: true
});
}
return true;
};
this.routine = function (el, value) {
var control = this.binder.GetControl(el);
var prop = this.binder.GetProperty(this.args[0]);
if (value == undefined) value = null;
switch (prop) {
case "Value":
if (typeof (value) == "number") {
control.SetValueData(value.toString());
}
else if (Date.IsDate(value)) {
control.SetValueData(value.toString(control.DisplayFormat.Format));
}
else {
if (value == null && control.Nullable) {
switch (control.DateDataSource) {
case "DisplayFormat":
control.DisplayFormat.ClientData.DateData = null;
break;
case "EditFormat":
control.EditFormat.ClientData.DateData = null;
break;
case "DynamicEditFormat":
control.DynamicEditFormat.ClientData.DateData = null;
break;
case "DateTimeEditor":
control.DateTimeEditor.ClientData.DateData = null;
break;
}
control.DateTimeValue = null;
control.SetValueData(value);
control.SetValue("");
}
else
control.SetValue(value);
}
break;
case "Disabled":
value ? control.Disable() : control.Enable();
control.FrameObj.classList[value ? 'add' : 'remove']("disabled");
break;
}
EventManager.TriggerEvent(control.HtmlObj, "change");
return value;
}
}
var WebComboBindingAdapter = function () {
this.Attibute = "webcombo-*";
this.publishes = true;
this.Context = null;
this.priority = 10000;
this.GetWindow = function (el) {
var doc = el.ownerDocument;
var win = doc.defaultView || doc.parentWindow;
return win;
}
this.GetControl = function (el) {
if (!el.Control) {
var id = el.id.replace(/_text$/ig, "");
var win = this.GetWindow(el);
el.Control = win.ISGetObject(id);
}
return el.Control;
}
this.GetProperty = function (prop) {
switch (prop) {
case 'datasource':
prop = "DataSource";
break;
default:
prop = prop[0].toUpperCase() + prop.substring(1);
break;
}
return prop;
}
this.SetValue = function (model, keyPath, value) {
var keys = keyPath.split(".");
var last = keys.pop();
for (var key of keys) {
model = model[key];
if (!model) {
return;
}
}
if (model) {
model[last] = value;
}
};
this.bind = function (el) {
var prop = this.binder.GetProperty(this.args[0]);
var control = this.binder.GetControl(el);
if (!control)
return false;
if (control.MultipleSelectionSettings && control.MultipleSelectionSettings.Enabled) {
prop = "Values";
}
var bValue = control[prop];
var bindingContext = this;
var setCollectionChange = function (arrayValue) {
if (Array.isArray(arrayValue) && !arrayValue.OnCollectionChange) {
arrayValue.OnCollectionChange = function (oldValue, value, result, array) {
if (!oldValue.itemEquals(array)) {
var bindVal = value;
if (Array.isArray(bindVal)) {
bindVal = ([]).concat(bindVal).select(function (a) { return a.Value });
}
bindingContext.SkipRoutine = true;
bindingContext.binder.SetValue(bindingContext.view.models, bindingContext.keypath, bindVal);
bindingContext.SkipRoutine = false;
}
}
}
}
Object.defineProperty(control, prop, {
get: function () { return bValue; },
set: function (newValue) {
if (!Object.isEquals(newValue, bValue)) {
bValue = newValue;
var bindVal = bValue;
if (prop == "Value") {
try {
if (this.BindingOperationMode == "ClientBinding") {
var val = this.DataSourceInternal.Rows[this.SelectedIndex].ObjectContext[this.DataValueField];
if (val && val.toString() == bindVal)
bindVal = val;
}
}
catch (e) {
}
}
setCollectionChange(newValue);
if (prop == "Values") {
if (bindingContext.__isSetValues)
return;
if (Array.isArray(bindVal) && bindVal.length > 0) {
bindVal = ([]).concat(bindVal).select(function (a) { return a.Value });
}
bindingContext.SkipRoutine = true;
bindingContext.binder.SetValue(bindingContext.view.models, bindingContext.keypath, bindVal);
bindingContext.SkipRoutine = false;
return;
}
else {
bindingContext.binder.SetValue(bindingContext.view.models, bindingContext.keypath, bindVal);
}
}
else if (prop == "DataSource") {
if (!bindingContext.binder.__runned) {
bindingContext.binder.__runned = true;
bindingContext.binder.routine.call(bindingContext, bindingContext.el, newValue);
}
else {
bindingContext.binder.__runned = false;
}
}
},
enumerable: true,
configurable: true
});
if (prop == "DataSource") {
if (control.BindingOperationMode != "ClientBinding") {
control.BindingOperationMode = "ClientBinding";
control.InitializeClientBinding();
}
if (control.Columns.length <= 0) {
var win = this.binder.GetWindow(el);
var displayColumn = new win.WebComboColumn();
displayColumn.Name = displayColumn.BaseFieldName = control.DataTextField
control.Columns.Add(displayColumn);
var valueColumn = new win.WebComboColumn();
valueColumn.Name = valueColumn.BaseFieldName = control.DataValueField;
valueColumn.Hidden = true;
control.Columns.Add(valueColumn);
}
control.ClientBindingSettings.DataSourceType = "ClientDataSource";
}
return true;
};
this.unbind = function (el) {
var control = this.binder.GetControl(el);
var prop = this.binder.GetProperty(this.args[0]);
if (!control)
return false;
if (control.MultipleSelectionSettings && control.MultipleSelectionSettings.Enabled) {
prop = "Values";
}
if (control.hasOwnProperty(prop)) {
Object.defineProperty(control, prop, {
value: control[prop],
writable: true,
enumerable: true,
configurable: true
});
}
return true;
};
this.routine = function (el, value) {
if (this.SkipRoutine)
return;
var prop = this.binder.GetProperty(this.args[0]);
var control = this.binder.GetControl(el);
if (!control) {
return;
}
if (control.MultipleSelectionSettings && control.MultipleSelectionSettings.Enabled) {
prop = "Values";
}
if (control[prop] == value) {
return;
}
if (control.BindingOperationMode == "ClientBinding") {
switch (prop) {
case "Values":
if (Array.isArray(value)) {
// always load from DB.
if (control.ClientBindingSettings.DataSourceType == 'WcfService') {
if (value.length > 0) {
App.HttpService.Request("POST", control.ClientBindingSettings.ServiceUrl + "/" + control.ClientBindingSettings.ServiceMethods.SelectMethod, {
selectArguments: { CurrentValues: value }
}).done(function (result) {
if (result.Results.length > 0) {
this.__isSetValues = true;
control.Values = result.Results.select(function (o) {
const v = {
Text: o.Text,
Value: o.Value
};
return v;
});
control.RefreshTextByValueItems();
this.__isSetValues = false;
EventManager.TriggerEvent(control.TextObj, "change");
}
});
}
else {
this.__isSetValues = true;
control.Values = [];
this.__isSetValues = false;
}
}
else {
this.__isSetValues = true;
control.SetMultipleValuesFromString(value.join(control.MultipleSelectionSettings.SeparatorChar));
this.__isSetValues = false;
}
}
break;
case "Value":
var pass = control.SetSelectedRowByValue(value);
if (!pass) {
if (control.Value != value) {
control.SetValue(value);
}
if (control.DataSource) {
var exist = control.DataSource.find(function (item) { return item[control.DataValueField] == value; });
if (exist) {
control.SetText(exist[control.DataTextField]);
}
else {
control.SetText("");
}
}
}
break;
case "Text":
if (typeof (value) == "undefined")
return;
var pass = false;
if (value !== null && value !== "") {
var rows = control.GetRows();
if (rows) {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var text = row.GetTextData();
if (text == value) {
pass = control.SetSelectedRowByValue(row.Value);
}
}
}
}
if (!pass) {
control.SetText(value);
if (control.DataSource) {
var exist = control.DataSource.find(function (item) { return item[control.DataTextField] == value; });
if (exist) {
if (exist[control.DataValueField] != control.Value)
control.SetValue(exist[control.DataValueField]);
}
}
}
break;
case "DataSource":
if (!value) {
control.GetRows();
value = [];
}
control.SetDataSourceWithValue(value, control.Value);
break;
case "Disabled":
value ? control.Disable() : control.Enable();
control.FrameObj.classList[value ? 'add' : 'remove']("disabled");
break;
}
}
else {
if (control.GetRowsCount && control.GetRowsCount() <= 0 && control.IsDataBound) {
var win = this.binder.GetWindow(el);
var context = this;
var cevent = control.LayoutSettings.ClientSideEvents;
var evname = "_combo" + control.Id + "_fn";
if (cevent.OnAfterResponseProcess.split(";").indexOf(evname) < 0)
cevent.OnAfterResponseProcess = (cevent.OnAfterResponseProcess ? ";" : "") + evname;
win[evname] = function (id, action) {
var combo = win.ISGetObject(id);
context.binder.routine.call(context, combo.TextObj, value);
var events = combo.LayoutSettings.ClientSideEvents.OnAfterResponseProcess.split(';');
events.remove(evname);
combo.LayoutSettings.ClientSideEvents.OnAfterResponseProcess = events.join(';');
win[evname] = undefined;
}
control.SetValue(value);
control.IsDirty = true;
control.LoadValue();
// control.ShowDropDown(); -- Should be unnecessary
}
else {
switch (prop) {
case "Values":
control.SetMultipleValuesFromString(value.join(control.MultipleSelectionSettings.SeparatorChar));
break;
case "Value":
var exist = control.SetSelectedRowByValue(value);
if (!exist) {
control.SetValue(value);
control.SetText("");
control.HtmlObj.value = "";
control.SelectedIndex = control.LastSelectedIndex = -1;
}
break;
case "Text":
if (typeof (value) == "undefined")
return;
var e = control.GetRows();
if (!e) {
control.SetText(value);
return false;
}
for (var b = 0; b < e.length; b++) {
var d = e[b];
if (d.GetTextData() == value) {
d.Select();
}
}
break;
case "Disabled":
value ? control.Disable() : control.Enable();
control.FrameObj.classList[value ? 'add' : 'remove']("disabled");
break;
}
}
}
EventManager.TriggerEvent(control.TextObj, "change");
return value;
}
}
var WebTextEditorBindingAdapter = function () {
this.Attibute = "webtexteditor-*";
this.publishes = true;
this.Context = null;
this.priority = 10000;
this.EmptyValue = null;
this.GetWindow = function (el) {
var doc = el.ownerDocument;
var win = doc.defaultView || doc.parentWindow;
return win;
}
this.GetControl = function (el) {
if (!el.Control) {
var id = el.id.replace(/_f$/ig, "");
var win = this.GetWindow(el);
el.Control = win.ISGetObject(id);
}
return el.Control;
}
this.bind = function (el) {
var sectionName = this.args[0];
var editor, content, textArea;
var control = this.binder.GetControl(el);
if (sectionName == "root") {
editor = control.RootTextEditor;
content = control.GetSelectedSectionElement();
textArea = control.GetSelectedTextArea();
}
else {
editor = control.GetSectionObjectByName(sectionName);
content = control.GetSectionElementByName(sectionName);
textArea = control.GetTextAreaBySectionName(sectionName);
}
this.getValue = function (el) {
var sectionName = this.args[0];
if (sectionName == "root") {
sectionName = undefined;
}
var control = this.binder.GetControl(el);
var value = control.ActiveView == "DesignView" ? content.contentDocument.body.innerHTML : textArea.value;
if ((control.ParagraphMode == "UseParagraph" && value == "") || value == "")
value = this.binder.EmptyValue;
return value;
}
var self = this;
content.blur();
textArea.blur();
if (textArea)
App.BindingService.Context["_"].Util.bindEvent(textArea, "blur", this.publish);
if (content && content.contentWindow)
App.BindingService.Context["_"].Util.bindEvent(content.contentWindow, "blur", this.publish);
else {
var undoRedoOperation = control.UndoRedoOperation.GetNamedItem(control.ID + "_" + (sectionName == "root" ? "Root" : sectionName));
var undoPos = undoRedoOperation.UndoPosition;
Object.defineProperty(undoRedoOperation, "UndoPosition", {
get: function () { return undoPos; },
set: function (newValue) {
if (newValue != undoPos) {
undoPos = newValue;
self.publish.apply(self, []);
}
},
enumerable: true,
configurable: true
});
}
return true;
};
this.unbind = function (el) {
var sectionName = this.args[0];
var editor, content, textArea;
try {
var control = this.binder.GetControl(el);
if (sectionName == "root") {
editor = control.RootTextEditor;
content = control.GetSelectedSectionElement();
textArea = control.GetSelectedTextArea();
}
else {
editor = control.GetSectionObjectByName(sectionName);
content = control.GetSectionElementByName(sectionName);
textArea = control.GetTextAreaBySectionName(sectionName);
}
this.binder.Context["_"].Util.unbindEvent(textArea, "blur", this.publish);
var undoRedoOperation = control.UndoRedoOperation.GetNamedItem(control.ID + "_" + (sectionName == "root" ? "Root" : sectionName));
var undoPos = undoRedoOperation.UndoPosition;
Object.defineProperty(undoRedoOperation, "UndoPosition", {
value: undoPos,
enumerable: true,
configurable: true,
writable: true
});
}
catch (e) { }
return true;
};
this.routine = function (el, value) {
if (this.IsFirst) {
this.IsFirst = false;
if (typeof (value) == "string")
this.binder.EmptyValue = "";
else
this.binder.EmptyValue = null;
}
var sectionName = this.args[0];
var editor, content, textArea;
var control = this.binder.GetControl(el);
if (typeof (value) == "undefined") {
value = "";
}
if (sectionName == "root") {
editor = control.RootTextEditor;
content = control.GetSelectedSectionElement();
textArea = control.GetSelectedTextArea();
}
else {
editor = control.GetSectionObjectByName(sectionName);
content = control.GetSectionElementByName(sectionName);
textArea = control.GetTextAreaBySectionName(sectionName);
}
if (this.getValue(el) != value) {
control.SetValue(value, sectionName == "root" ? undefined : sectionName);
if (textArea)
textArea.value = value;
}
return value;
}
}
var ValidationBindingAdapter = function () {
this.Attibute = "validate";
this.publishes = true;
this.Context = null;
this.Entity = null;
this.MemberName = null;
var timeout = null;
this.priority = 10000;
this.GetEntity = function (bindingContext) {
var pathes = bindingContext.keypath.split(".");
return bindingContext.observer.objectPath[pathes.length - 2];
};
this.GetMemberName = function (bindingContext) {
var pathes = bindingContext.keypath.split(".");
return pathes.pop();
};
this.bind = function (el) {
el.helpBlock = el.ownerDocument.createElement("span");
el.helpBlock.className = "help-block";
el.appendChild(el.helpBlock);
var pathes = this.keypath.split(".");
return true
};
this.unbind = function (el) {
return true;
};
this.routine = function (el, value) {
var entity = this.binder.GetEntity(this);
var prop = this.binder.GetMemberName(this);
el.classList.remove("has-error");
el.classList.remove("has-success");
el.helpBlock.innerHTML = "";
if (value) {
if (value.IsSuccess) {
if (entity.IsNew || (entity.IsPropertyChanged && entity.IsPropertyChanged(prop)))
el.classList.add("has-success");
}
else {
el.classList.add("has-error");
el.helpBlock.innerHTML = value.ErrorMessages[0];
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function () {
var firstErrorEl = el.ownerDocument.querySelector(".has-error input, .has-error textarea, .has-error select");
if (firstErrorEl === el.ownerDocument.activeElement && (firstErrorEl.type || firstErrorEl.href))
return false;
if (firstErrorEl == null)
return false;
var window = firstErrorEl.ownerDocument.defaultView || firstErrorEl.ownerDocument.parentWindow;
var elem = window.$(firstErrorEl);
var pageTop = $(window).scrollTop();
var pageBottom = pageTop + $(window).height() - 100;
var elementTop = elem.offset().top;
var elementBottom = elementTop + elem.height();
if ((pageTop > elementTop) || (pageBottom < elementBottom)) {
$(firstErrorEl.ownerDocument.body).animate({
scrollTop: elementTop - 100
}, 500, 'swing', function () {
firstErrorEl.focus();
if (firstErrorEl.select)
firstErrorEl.select();
});
}
else {
firstErrorEl.focus();
if (firstErrorEl.select)
firstErrorEl.select();
}
}, 100);
}
}
if (entity && entity.GetPropertyValidators) {
var validators = entity.GetPropertyValidators(prop);
for (var i = 0; i < validators.length; i++) {
var validator = validators[i];
validator.ApplyDecoration(el, entity, value);
}
return true;
}
}
}
var CheckboxBindingAdapter = function () {
this.Attibute = "checked-list";
this.publishes = true;
this.Context = null;
this.priority = 10000;
this.bind = function (el) {
this.publish = App.BindFunction(function () {
var args, formatter, id, value, _i, oldValues, _ref1, _ref2, _ref3;
if (this.observer) {
value = this.getValue(this.el);
var adapter = this.observer.adapter(this.observer.key);
oldValues = adapter.get(this.observer.target, this.observer.key.path);
oldValues[value ? "add" : "remove"](this.el["__command-parameter"]);
return this.observer.setValue(oldValues);
}
}, this);
var adapter = this.observer.adapter(this.observer.key);
if (!this.observer.target || !this.observer.key.path) {
this.observer.setValue([]);
}
else {
var oldValues = adapter.get(this.observer.target, this.observer.key.path);
}
//if (!Array.isArray(oldValues))
// this.observer.setValue([]);
return EventManager.RegisterEvent(el, "click", this.publish);
};
this.unbind = function (el) {
return EventManager.RegisterEvent(el, "click", this.publish);
};
this.routine = function (el, value) {
if (el.tagName === 'INPUT' && el.type === 'checkbox') {
if (Array.isArray(value) && value.indexOf(el["__command-parameter"]) >= 0) {
el.checked = true;
return el.setAttribute('checked', 'checked');
}
else {
el.checked = false;
return el.removeAttribute('checked');
}
}
return false;
}
}
var InitializeBindingAdapter = function () {
this.Attibute = "initialize";
this.publishes = true;
this.Context = null;
this.priority = 15000;
this.bind = function (el) {
return true;
};
this.unbind = function (el) {
return true;
};
this.routine = function (el, value) {
value.call(this.el, this.view.models);
}
}
function BindingService(options) {
this.Bindings = [];
this.Context = null;
this.BindingViews = [];
this.Bind = function (rootElement, model) {
var bindingView = this.Context.bind(rootElement, model);
this.BindingViews.push(bindingView);
return bindingView;
}
this.Unbind = function (bindingView) {
var index = this.BindingViews.indexOf(bindingView);
this.BindingViews.splice(index, 1);
bindingView.unbind();
}
this.UnbindAll = function () {
for (var i = 0; i < this.BindingViews.length; i++) {
this.BindingViews[i].unbind();
}
}
this.OnInitialize = function () {
}
ExtendableObject.call(this, options);
this.RegisterBindings = function () {
if (this.Context) {
for (var i = 0; i < this.Bindings.length; i++) {
var item = this.Bindings[i];
item.Context = this.Context;
this.Context.binders[item.Attibute] = item;
}
}
}
this.OnInitialize();
var templateEl = document.createElement("div");
this.GetText = function (textTemplate, model) {
templateEl.innerHTML = textTemplate;
var view = App.BindingService.Bind(templateEl, model);
var result = templateEl.innerHTML;
var elem = document.createElement('textarea');
elem.innerHTML = result;
result = elem.value;
App.BindingService.Unbind(view);
return result;
}
}
function HttpClientService(options) {
this.OnError = function () { };
this.OnSuccess = function () { };
this.ParseData = function (data) { return data; };
this.ParseUrl = function (controller, action, data, filter) { console.error("please specify ParseUrl method"); }
ExtendableObject.call(this, options);
this.Request = function (method, url, data, filter, isPayload, dataParser, headers) {
var cleanData = this.ParseData(data, filter);
if (dataParser)
cleanData = dataParser(cleanData);
var promise = $.ajax({
method: method,
url: url,
data: isPayload ? JSON.stringify(cleanData) : cleanData,
contentType: isPayload ? "application/json" : "application/x-www-form-urlencoded",
headers: headers
});
promise.done(function () {
if (data && data.Is)
this.Entity = data;
});
if (typeof (this.OnError) == "function") {
promise.fail(this.OnError);
}
if (typeof (this.OnSuccess) == "function") {
promise.done(this.OnSuccess);
}
return promise;
};
this.Post = function (controller, action, data, filter, isPayload, dataParser, headers) {
return this.Request("POST", this.ParseUrl(controller, action, data, filter), data, filter, isPayload, dataParser, headers);
};
this.Get = function (controller, action, data, filter, isPayload, dataParser) {
return this.Request("GET", this.ParseUrl(controller, action, data, filter), data, filter, isPayload, dataParser);
};
this.Put = function (controller, action, data, filter, isPayload, dataParser) {
return this.Request("PUT", this.ParseUrl(controller, action, data, filter), data, filter, isPayload, dataParser);
};
this.HttpDelete = function (controller, action, data, filter, isPayload, dataParser) {
return this.Request("DELETE", this.ParseUrl(controller, action, data, filter), data, filter, isPayload, dataParser);
};
this.PostSubmit = function (controller, action, data, filter, context, formOption) {
var url = this.ParseUrl(controller, action, data, filter);
this.Submit("post", url, data, filter, context, formOption);
};
this.GetSubmit = function (controller, action, data, filter, context, formOption) {
var url = this.ParseUrl(controller, action, data, filter);
this.Submit("get", url, data, filter, context, formOption);
};
this.Submit = function (method, url, data, filter, context, formOption) {
var cleanData = this.ParseData(data, filter);
if (!context)
context = window;
var form = context.document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", url);
if (formOption) {
for (var prop in formOption) {
form.setAttribute(prop, formOption[prop]);
}
}
var addHiddenInput = function (value, key) {
if (Array.isArray(value)) {
value.each(function (val, index) {
addHiddenInput(val, key + "[" + index + "]");
});
}
else if (value != null && typeof (value) == "object" && !Date.IsDate(value)) {
for (var prop in value) {
var val = value[prop];
addHiddenInput(val, key + "[" + prop + "]");
}
}
else {
if (Date.IsDate(value))
value = value.toJSON();
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", value);
form.appendChild(hiddenField);
}
}
for (var prop in cleanData) {
addHiddenInput(cleanData[prop], prop);
}
context.document.body.appendChild(form);
form.submit();
context.document.body.removeChild(form);
}
}
var AnimationService = {
GetCurrentStyle: function (element) {
return element.currentStyle ? element.currentStyle : window.getComputedStyle(element);
},
SetAnimation: function (element, type, animationClassBase, animationClass, endClass, callback) {
this.ClearAnimation(element);
if (animationClassBase && !element.classList.contains(animationClassBase)) {
element.classList.add(animationClassBase);
}
if (type == "add") {
element.classList.remove(endClass);
element.offsetHeight;
if (animationClass && !element.classList.contains(animationClass))
element.classList.add(animationClass);
}
else {
if (animationClass && !element.classList.contains(animationClass)) {
if (endClass && !element.classList.contains(endClass))
element.classList.add(endClass);
}
else {
EventManager.RegisterEvent(element, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function (e) {
EventManager.RemoveEvents(e.target, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", arguments.callee);
if (endClass && !element.classList.contains(endClass))
element.classList.add(endClass);
});
element.offsetHeight;
element.classList.remove(animationClass);
}
}
if (typeof (callback) == "function") {
var isRun = false;
EventManager.RegisterEvent(element, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function (e) {
EventManager.RemoveEvents(e.target, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", arguments.callee);
if (!isRun) {
isRun = true;
callback(element);
}
});
setTimeout(function () {
if (!isRun) {
isRun = true;
callback(element);
}
}, 400);
}
},
Hide: function (elements, animationClass, callBack, isHide) {
if (!elements)
return;
isHide = typeof (isHide) != "undefined" ? isHide : true;
animationClass = typeof (animationClass) == "string" && animationClass ? animationClass : "animate-toggle";
this.SetAnimation(elements, "remove", animationClass, "animate", (isHide ? "hide" : ""), callBack);
},
ClearAnimation: function (element) {
if (element.callbackTimeout) clearTimeout(element.callbackTimeout);
EventManager.RemoveEvents(element, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd");
},
Show: function (elements, animationClass, callBack, isHide) {
if (!elements)
return;
animationClass = typeof (animationClass) == "string" && animationClass ? animationClass : "animate-toggle";
this.SetAnimation(elements, "add", animationClass, "animate", "hide", callBack);
},
GetCurrentStyle: function (element) {
return element.currentStyle ? element.currentStyle : window.getComputedStyle(element);
},
RevertAnimation: function (element, callBack) {
if (!element.oriStyle)
return;
this.ClearAnimation(element);
if (!element.classList.contains("animate-property")) {
element.classList.add("animate-property");
element.offsetHeight;
}
// safari need setTimeout for animation
setTimeout(function () {
for (var prop in element.oriStyle) {
element.style[prop] = element.oriStyle[prop];
}
EventManager.RegisterEvent(element, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function (e) {
EventManager.RemoveEvents(e.target, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", arguments.callee);
if (typeof (callBack) == "function") {
callBack(element);
}
});
});
},
SetAnimationProperty: function (element, props, callBack) {
this.ClearAnimation(element);
var currentStyle = this.GetCurrentStyle(element);
var first = false;
var hasHideClass = false;
if (currentStyle.display == "none" && !element.oriStyle) {
first = true;
if (element.classList.contains("hide")) {
element.classList.remove("hide");
hasHideClass = true;
}
else {
element.__olddisplay = element.style.display;
element.style.display = "block";
}
element.style.MsTransition = element.style.OTransition = element.style.WebkitTransition = element.style.MozTransition = element.style.transition = "none";
}
if (!element.oriStyle)
element.oriStyle = {};
element.offsetHeight;
for (var prop in props) {
element.oriStyle[prop] = currentStyle[prop];
}
if (!element.classList.contains("animate-property"))
element.classList.add("animate-property");
for (var prop in props) {
element.style[prop] = props[prop];
}
if (typeof (callBack) == "function") {
EventManager.RegisterEvent(element, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function (e) {
AnimationService.ClearAnimation(element);
callBack(element);
callBack = null;
});
// ensure callBack is always called after certain period
// coz in initial view, callBack is not called causing some finalization properties aren't executed
element.callbackTimeout = setTimeout(function () {
if (callBack && typeof (callBack) == "function")
EventManager.TriggerEvent(element, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd");
}, 500);
}
if (first) {
if (hasHideClass)
element.classList.add("hide");
else {
element.style.display = element.__olddisplay;
element.__olddisplay = undefined;
}
element.style.MsTransition = element.style.OTransition = element.style.WebkitTransition = element.style.MozTransition = element.style.transition = "";
EventManager.TriggerEvent(element, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd");
}
},
Animate: function (el, animateClass, baseClass, isAdd) {
var deferred = App.Deferred([
["resolve", "done", jQuery.Callbacks("memory stopOnFalse")]
], true);
var promise = deferred.promise();
if (!animateClass) {
return promise;
}
isAdd = typeof (isAdd) == "boolean" ? isAdd : !el.classList.contains(animateClass);
this.ClearAnimation(el);
if (baseClass && !el.classList.contains(baseClass))
el.classList.add(baseClass);
el.offsetHeight;
if (isAdd) {
if (el.classList.contains(animateClass)) {
el.classList.remove(animateClass);
el.offsetHeight;
}
setTimeout(function () {
el.classList.add(animateClass)
});
}
else {
if (!el.classList.contains(animateClass)) {
el.classList.add(animateClass);
el.offsetHeight;
}
setTimeout(function () {
el.classList.remove(animateClass)
});
}
el.transitionEndEventRaised = false;
EventManager.RegisterEvent(el, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function (e) {
if (!el.transitionEndEventRaised) {
el.transitionEndEventRaised = true;
EventManager.RemoveEvents(el, "transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", arguments.callee);
deferred.resolveWith(el, arguments);
}
});
// in safari, transitionEnd is not called if the browser is not active
setTimeout(function () {
if (!el.transitionEndEventRaised) {
console.log("transitionEnd called from timeout");
EventManager.TriggerEvent(el, "transitionEnd webkitTransitionEnd oTransitionEnd MSTransitionEnd");
}
}, 500);
return promise;
}
}
//dropdown
function Dropdown(element) {
this.Element = element;
this.Target = null;
this.IsShowed = false;
this.IsAutoClose = true;
this.Initialize = function () {
this.Element.Obj = this;
if (!this.Target) {
var target = element.getAttribute("data-target");
this.Target = element.ownerDocument.querySelector(target);
}
this.IsAutoClose = element.getAttribute("data-auto-close") ? element.getAttribute("data-auto-close").toLowerCase() == "true" : this.IsAutoClose;
this.RegisterBehaviour();
this.Hide();
}
this.Show = function () {
AnimationService.Show(this.Target, "dropdown-animation");
this.Element.classList.add("active");
this.IsShowed = true;
}
this.Hide = function () {
var self = this;
AnimationService.Hide(self.Target, "dropdown-animation");
self.IsShowed = false;
self.Element.classList.remove("active");
}
this.Toggle = function () {
if (this.IsShowed) {
this.Hide();
}
else {
this.Show();
}
}
this.RegisterBehaviour = function () {
var isDescendant = function (parents, child) {
var node = child;
while (node != null) {
if (parents.indexOf(node) >= 0) {
return true;
}
node = node.parentNode;
}
return false;
}
var docBody = this.Element.ownerDocument.body;
if (docBody) {
var doc = this.Element.ownerDocument;
var win = doc.defaultView || doc.parentWindow;
var self = this;
var evenHandler = function (event) {
if (event.type == "blur" && event.target != win)
return;
var isDisableClose = false;
if (event.target && event.target.className) {
isDisableClose = typeof event.target.className === "string" && event.target.className.indexOf("disable-close") >= 0;
}
if (isDescendant([self.Element], event.target)) {
if (event.type == "blur")
return;
self.Toggle();
}
else {
var isClose = self.IsAutoClose;
if (!isClose) {
var Els = [];
var othrS = element.getAttribute("data-keepshow-selector");
if (othrS) {
var els = element.ownerDocument.querySelectorAll(othrS);
for (var i = 0; i < els.length; i++) {
Els.push(els[i]);
}
}
Els.push(self.Target);
var isClose = !isDescendant(Els, event.target)
}
if (isClose && !isDisableClose) {
self.Hide();
}
}
};
EventManager.RegisterEvent(docBody, "click", evenHandler);
EventManager.RegisterEvent(win, "blur", evenHandler);
}
}
this.Initialize();
}
function SelectionControl(element) {
if (typeof (element) == "string")
element = document.getElementById(element);
this.CheckBoxElement = element;
this.FrameStyle = "switch material";
this.Initialize = function () {
if (this.FrameStyle)
this.CheckBoxElement.className += " " + this.FrameStyle;
this.LabelElement = document.createElement("label");
this.CheckBoxElement.parentElement.insertBefore(this.LabelElement, this.CheckBoxElement.nextSibling);
if (this.CheckBoxElement.id)
this.LabelElement.setAttribute("for", this.CheckBoxElement.id);
else
var self = this;
this.LabelElement.addEventListener("click", function () {
self.CheckBoxElement.click();
});
}
}
function Switch(element) {
SelectionControl.call(this, element);
this.FrameStyle = "switch material";
this.Initialize();
}
function Radio(element) {
SelectionControl.call(this, element);
this.FrameStyle = "material-radio";
this.Initialize();
}
function Checkbox(element) {
SelectionControl.call(this, element);
this.FrameStyle = "material-checkbox";
this.Initialize();
}
function InfoBar(options) {
this.IsShown = false;
this.Buttons = [];
this.Text = "";
this.MaxVisibleAction = 2;
this.MaxMobileVisibleAction = 0;
ExtendableObject.call(this, options);
}
function FilterVisibleAction(buttons, maxVisible) {
return buttons.slice(0, Math.min(maxVisible, buttons.length));
}
function ButtonBase(options) {
this.Caption = "";
this.Icon = "";
this.Name = "";
this.Type = ""; // normal, primary, destructive;
this.Class = "";
this.Command = null;
ExtendableObject.call(this, options);
this.__SetProperty("TypeStyle", null, function () {
var value = "";
switch (this.Type.toLowerCase()) {
case "danger":
case "destructive":
value = "danger";
break;
case "primary":
value = "primary";
break;
default:
value = "default";
break;
}
return value;
});
}
function ActionButton(options) {
ButtonBase.call(this, options);
}
function SegmentedButtonItem(options) {
this.Title = "";
this.FrameStyle = "btn outline-button";
this.Data = null;
ExtendableObject.call(this, options);
this.Element = null;
this.IsActive = false;
this.Initialize = function (container, parentControl) {
this.Element = document.createElement("button");
this.Element.type = "button";
this.Element.Object = this;
if (container)
this.AppendTo(container);
if (parentControl)
this.SetParentControl(parentControl);
this.Refresh();
return this.Element;
}
this.Refresh = function () {
this.Element.className += " " + this.FrameStyle;
this.Element.innerHTML = this.Title;
}
this.AppendTo = function (container) {
if (!this.Element) {
this.Initialize();
}
container = typeof (container) == "string" ? document.getElementById(container) : container;
container.appendChild(this.Element);
}
this.Select = function () {
if (this.Parent) {
this.Parent.SetSelectedItem(this);
}
}
this.SetParentControl = function (parent) {
this.Parent = parent;
}
}
function SegmentedButton(id, isAutoInitialize) {
this.Id = id;
this.Element = null;
this.Items = [];
this.FrameStyle = "btn-group-sm";
this.ActiveItemStyle = "active";
this.OnSelectedItemChange = "";
this.Element = null;
this.SelectedItem = null;
this.Initialize = function () {
this.Element = document.getElementById(this.Id);
this.Element.Object = this;
this.Element.className += " " + this.FrameStyle;
this.Element.style.display = "inline-block";
this.Refresh();
}
this.Refresh = function (isAnimated) {
isAnimated = typeof (isAnimated) == "undefined" ? true : isAnimated;
if (isAnimated)
this.Hide();
var self = this;
setTimeout(function () {
while (self.Element.lastChild) {
self.Element.removeChild(self.Element.lastChild);
}
for (var i = 0; i < self.Items.length; i++) {
var item = self.Items[i];
item.Initialize(self.Element, self);
if (self.SelectedItem == null) {
self.SetSelectedItem(self.SelectedItem);
}
}
self.SelectedItem.Element.classList.add(self.ActiveItemStyle);
self.RegisterBehavior();
if (isAnimated)
self.Show();
}, isAnimated ? 300 : 0);
}
this.SetSelectedItem = function (item, isForce) {
if (!item || (this.SelectedItem == item && !isForce))
return;
if (this.OnSelectedItemChange && this.OnSelectedItemChange(item, this.SelectedItem) === false) {
return;
}
if (this.SelectedItem)
this.SelectedItem.Element.classList.remove(this.ActiveItemStyle);
item.Element.classList.add(this.ActiveItemStyle);
var oldItem = this.SelectedItem;
this.SelectedItem = item;
}
this.RegisterBehavior = function () {
for (var i = 0; i < this.Items.length; i++) {
var item = this.Items[i];
this.RegisterItemBehaviour(item);
}
}
this.RegisterItemBehaviour = function (item) {
item.Element.addEventListener("click", function () {
item.Select();
});
}
this.AddItem = function (newItem) {
this.Items.push(newItem)
if (this.Element) {
newItem.Initialize(this.Element, this);
this.RegisterItemBehaviour(newItem);
}
}
this.RemoveItem = function (item) {
var index = this.Items.indexOf(item);
var item = this.Items.splice(index, 1);
this.Element.remove(item.Element);
}
this.SetItems = function (items, onSelectedChange) {
if (typeof (onSelectedChange) != "undefined")
this.OnSelectedItemChange = onSelectedChange;
this.Items = items;
this.SelectedItem = this.Items[0];
this.Refresh();
}
this.Hide = function () {
AnimationService.Hide(this.Element);
}
this.Show = function () {
AnimationService.Show(this.Element);
}
if (isAutoInitialize)
this.Initialize();
}
// Services
// notification service
function NotificationButton(options) {
ButtonBase.call(this, options);
}
function NotificationOptions(options) {
this.Buttons = [];
this.Text = "";
this.Title = "";
this.Type = "default"; // warning, danger, success, info, default
this.Duration = 10000;
this.AutoClose = true;
ExtendableObject.call(this, options);
this.__SetProperty("TypeStyle", null, function () {
var value = "";
switch (this.Type.toLowerCase()) {
case "error":
case "danger":
value = "error";
break;
case "warning":
value = "warning";
break;
case "success":
value = "success";
break;
case "info":
default:
value = "info";
break;
}
return value;
});
}
function NotificationService(options) {
this.FrameStyle = "notification-container";
ExtendableObject.call(this, options);
this.Initialize = function () {
this.Element = document.createElement("div");
this.Element.className = this.FrameStyle;
document.body.appendChild(this.Element);
}
this.Notify = function (notificationOption, callBack) {
if (typeof (notificationOption) == "string") {
notificationOption = new NotificationOptions({ Title: notificationOption });
}
if (notificationOption.Buttons.length == 0 && !callBack) {
notificationOption.Buttons.push(new NotificationButton({ Name: "Close", Caption: App.Resources.Close }));
}
var self = this;
var deferred = App.Deferred([
["resolve", "done", jQuery.Callbacks("memory stopOnFalse")]
], true);
var promise = deferred.promise();
if (typeof (callBack) == "function") {
promise.done(callBack);
}
var notifEl = document.createElement("div");
notifEl.className = "notification hide " + notificationOption.TypeStyle;
notifEl.setAttribute("tabindex", "-1");
notifEl.setAttribute("role", "notification");
notifEl.setAttribute("aria-labelledby", "notification");
notifEl.innerHTML = '' +
'' +
'
' +
'' +
'';
notifEl.querySelector(".notification-title").innerText = notificationOption.Title;
notifEl.querySelector(".notification-description").innerText = notificationOption.Text;
var buttonContainer = notifEl.getElementsByClassName("notification-action")[0];
for (var i = 0; i < notificationOption.Buttons.length; i++) {
var button = notificationOption.Buttons[i];
var el = document.createElement("button");
el.className = "btn small block " + button.TypeStyle;
buttonContainer.appendChild(el);
el.innerHTML = button.Caption;
el.onclick = App.BindFunction(function () {
deferred.resolveWith(self, [this.Name]);
}, button);
}
this.Element.appendChild(notifEl);
EventManager.RegisterEvent(notifEl, "mouseenter", function (el) {
clearTimeout(this.__timeout);
});
EventManager.RegisterEvent(notifEl, "mouseleave", function (el) {
var notifEl = this;
if (notificationOption.Duration >= 0)
this.__timeout = setTimeout(function () {
self.HideNotification(notifEl);
}, notificationOption.Duration);
});
AnimationService.Show(notifEl, "animate-zoomleft");
if (notificationOption.AutoClose) {
if (notificationOption.Duration >= 0)
notifEl.__timeout = setTimeout(function () {
self.HideNotification(notifEl);
}, notificationOption.Duration);
}
promise.HideNotification = App.BindFunction(function () {
this.HideNotification(notifEl);
}, this);
promise.done(function () {
this.HideNotification(notifEl);
});
return promise;
};
this.HideNotification = function (el) {
var notificationService = this;
clearTimeout(el.__timeout);
AnimationService.Hide(el, "animated-zoomleft", function (e) {
if (e.parentElement)
e.parentElement.removeChild(e);
else
e.style.display = "none";
});
}
this.GetIcon = function (type) {
var icon = "";
switch (type.toLowerCase()) {
case "warning":
icon = "alert webui-warning-icon";
break;
case "success":
icon = "ios-checkmark-outline webui-green-icon";
break;
case "error":
case "danger":
icon = "ios-close-outline webui-red-icon";
break;
case "info":
default:
icon = "ios-information-outline";
break;
}
return icon;
}
this.Initialize();
}
function DialogButton(options) {
ButtonBase.call(this, options);
this.Command = App.PresenterService.Dialog.GetButtonCommand();
}
function DialogOptions(options) {
this.Buttons = [];
this.Title = "";
this.Content = "";
this.ContentId = null;
this.ShowHeader = true;
this.ShowFooter = true;
this.ContentMode = "inline"; // "inline", "iframe";
this.ContentUrl = "";
this.Width = "";
this.Height = "auto";
this.Scrollable = true;
this.Model = null;
this.IsStaticBackdrop = false;
this.LeftFooterTemplate = "";
this.Left = 0;
this.Top = 0;
this.Align = "";
this.NoMargin = "";
this.ExpandBodyHeight = false;
this.NoFadeAnimation = false;
this.Page = null;
ExtendableObject.call(this, options);
}
DialogOptions.GetModalOptions = function (modalId) {
var result = new DialogOptions();
var modal = document.getElementById(modalId);
var title = "", content = "", buttons = [];
var tempEl = modal.getElementsByClassName("modal-title");
if (tempEl && tempEl.length > 0)
result.Title = tempEl[0].innerHTML;
tempEl = modal.getElementsByClassName("modal-body");
if (tempEl)
result.Content = tempEl[0].innerHTML;
tempEl = modal.getElementsByClassName("modal-footer");
if (tempEl.length > 0) {
leftTemplateEl = tempEl[0].getElementsByClassName("modal-footer-left");
var buttons = [];
if (leftTemplateEl.length > 0) {
result.LeftFooterTemplate = leftTemplateEl[0].innerHTML;
var butEl = tempEl[0].getElementsByClassName("modal-footer-buttons");
if (butEl.length > 0) {
buttons = butEl[0].getElementsByTagName("button");
}
}
else {
buttons = tempEl[0].getElementsByTagName("button");
}
for (var i = 0; i < buttons.length; i++) {
var buttonEl = buttons[i];
var name = buttonEl.getAttribute("name") ? buttonEl.getAttribute("name") : i;
var type = buttonEl.getAttribute("button-type") ? buttonEl.getAttribute("button-type") : "default";
result.Buttons.push(new DialogButton({ Name: name, Caption: buttonEl.innerHTML, Type: type }));
}
}
return result;
}
function DialogPresenter(options) {
this.FrameStyle = "modal fade dialog-box";
this.ButtonStyle = "btn";
this.BackdropStyle = "modal-backdrop fade dialog-backdrop";
this.PrimaryButtonStyle = "primary";
this.DefaultButtonStyle = "default";
this.DestructiveButtonStyle = "danger";
this.OnDialogShowed = function (options) { };
this.Height = "";
this.Width = "";
this.zIndex = 960;
this.OnBeforeShow = function (options) { return true; };
this.OnClosed = function (options) {
if (options.rvFrameView) {
App.BindingService.Unbind(options.rvFrameView);
options.rvFrameView = null;
}
if (options.rvView) {
App.BindingService.Unbind(options.rvView);
delete options.rvView;
}
};
this.DialogOptions = null;
this.Stacks = [];
ExtendableObject.call(this, options);
Object.defineProperty(this, "__defaultHandler", {
enumerable: false,
writable: true,
value: {}
})
this.DefaultHandler = function (name, fn) {
if (typeof (fn) == "function") {
var savedFn = (function (fn, me) { return function () { return fn.apply(me, arguments); }; })(fn, this);
this.__defaultHandler[name] = savedFn;
}
else if (typeof (fn) == "undefined") {
return this.__defaultHandler[name];
}
}
this.GetButtonCommand = function () {
var self = this;
return new DelegateCommand({
Command: function (model, param) {
model.DialogOption.Defer.resolveWith(this, [model.button.Name, param, model, self]);
},
CanExecuteCommand: function (model, param) {
for (var i = 0; i < model.DialogOption.Buttons.length; i++) {
var button = model.DialogOption.Buttons[i];
if (button.IsProcessing) {
return false;
}
}
return true;
},
DefaultHandler: function () { return self.DefaultHandler.apply(self, arguments); }
});
};
this.Show = function (dialogOption, callBack, onDialogShowed) {
this.DialogOptions = dialogOption;
var dialogDeferred = App.Deferred([
["resolve", "done", jQuery.Callbacks("memory stopOnFalse")],
["reject", "fail", jQuery.Callbacks("memory stopOnFalse")],
["show", "onshowed", jQuery.Callbacks("once memory stopOnFalse")],
["close", "onclosed", jQuery.Callbacks("once memory stopOnFalse")],
], true);
var promise = dialogDeferred.promise();
dialogOption.Defer = dialogDeferred;
if (typeof (this.OnDialogShowed) == "function") {
promise.onshowed(this.OnDialogShowed);
}
if (typeof (this.OnClosed) == "function") {
promise.onclosed(this.OnClosed);
}
if (typeof (onDialogShowed) == "function") {
promise.onshowed(onDialogShowed);
}
this.CreateDialog(dialogOption);
this.CreateBackdrop(dialogOption);
if (this.OnBeforeShow && this.OnBeforeShow(dialogOption) == false)
return;
// custom show
this.zIndex++;
document.body.classList.add("modal-open");
if (!dialogOption.Backdrop.classList.contains("in")) {
document.body.appendChild(dialogOption.Backdrop);
}
document.body.appendChild(dialogOption.Element);
dialogOption.Element.style.display = "block";
dialogOption.Backdrop.style.display = "block";
if (!dialogOption.Backdrop.classList.contains("in") && !dialogOption.NoFadeAnimation) {
AnimationService.Animate(dialogOption.Backdrop, "in");
}
AnimationService.Animate(dialogOption.Element, "in");
var self = this;
promise.Close = function () {
self.Close(dialogOption);
};
EventManager.RegisterEvent(dialogOption.Element, "click", function (event) {
if (event.target == this && !dialogOption.IsStaticBackdrop) {
dialogDeferred.resolveWith(self, ["CloseDialog", dialogOption.Model, null, self]);
self.Close(dialogOption);
}
});
dialogOption.rvView = App.BindingService.Bind(dialogOption.Element, { DialogOption: dialogOption, Model: dialogOption.Model });
if (dialogOption.ContentMode == "iframe") {
dialogOption.IFrame.onload = function () {
try {
var pageObj = this.contentWindow.Page;
if (pageObj) {
dialogOption.HelpLink = pageObj.HelpLink;
pageObj.OnNavigated(dialogOption);
this.onunload = function () {
pageObj.OnUnload(dialogOption);
}
}
else {
var template = this.contentDocument.getElementById("maincontent");
dialogOption.rvFrameView = App.BindingService.Bind(template ? template : this.contentDocument.body, { Model: dialogOption.Model });
}
promise.done(function (name, data, model, dialog) {
if (name == "CloseDialog" && !(pageObj && pageObj["Execute" + name]))
name = "CancelCommand";
if (pageObj && pageObj["Execute" + name]) {
return pageObj["Execute" + name].call(this, data, model, dialog);
}
else {
var defaultHandler = self.DefaultHandler(name);
if (typeof (defaultHandler) == "function") {
return defaultHandler(this, data);
}
}
});
self.EnsureDialogSize(dialogOption);
dialogDeferred.showWith(self, [dialogOption]);
var contentBody = this.contentDocument.body;
setTimeout(function () {
contentBody.removeAttribute("style");
contentBody.removeAttribute("no-animation");
contentBody.setAttribute("isloaded", "true");
}, 10);
}
catch (e) {
console.error(e);
}
}
// if exact size is already specified, apply it directly to avoid flicker
if (dialogOption.Width != "" && dialogOption.Width != "auto" && dialogOption.Height != "" && dialogOption.Height != "auto")
this.EnsureDialogSize(dialogOption);
}
else {
if (typeof (callBack) == "string") {
callBack = this.DefaultHandler(callBack);
}
if (typeof (callBack) == "function") {
promise.done(callBack);
}
this.EnsureDialogSize(dialogOption);
dialogDeferred.showWith(this, [dialogOption]);
}
if (dialogOption.Top == "auto") {
var top = ((dialogOption.Element.offsetHeight - dialogOption.ContainerElement.offsetHeight) / 2) - 30;
dialogOption.Top = (top > 0 ? top : 10);
}
dialogOption.DialogEl.style.top = (dialogOption.Top + "").replace("px", "") + "px";
dialogOption.DialogEl.style.left = (dialogOption.Left + "").replace("px", "") + "px";
dialogOption.IsShown = true;
this.Stacks.push(dialogOption);
return promise;
}
this.EnsureDialogSize = function (dialogOption) {
dialogOption.ContainerElement.style.maxWidth = "";
if (!isNaN(parseInt(dialogOption.Width))) {
dialogOption.ContainerElement.style.width = "calc(100% - 20px)";
if (dialogOption.Width.indexOf('%') < 0 && dialogOption.Width.indexOf('px') < 0)
dialogOption.Width += "px";
dialogOption.ContainerElement.style.maxWidth = dialogOption.Width;
}
dialogOption.ContainerElement.style.height = "";
if (dialogOption.Height == "auto") {
if (dialogOption.IFrame && dialogOption.IFrame.contentDocument)
dialogOption.BodyElement.style.height = dialogOption.IFrame.contentDocument.body.scrollHeight + "px";
}
else if (!isNaN(parseInt(dialogOption.Height))) {
if (dialogOption.Height.indexOf('%') < 0 && dialogOption.Height.indexOf('px') < 0)
dialogOption.Height += "px";
if (dialogOption.Height.indexOf('px') > 0 && !dialogOption.AllowOverHeight) {
// make sure the height doesn't exceed the screen height
var headerFooterHeight = (!dialogOption || (dialogOption.ShowHeader && dialogOption.ShowFooter)) ? 152 : 20;
var maxHeight = document.body.offsetHeight - 40 - headerFooterHeight; // allow some room for padding and dropshadow, minus title and footer area
if (parseInt(dialogOption.Height) > maxHeight)
dialogOption.Height = maxHeight + "px";
}
dialogOption.BodyElement.style.height = dialogOption.Height;
}
}
this.Close = function (dialogOption, disabledUnload) {
if (!dialogOption)
dialogOption = this.Stacks[this.Stacks.length - 1];
if (!dialogOption || !dialogOption.IsShown)
return;
this.Stacks.remove(dialogOption);
dialogOption.IsShown = false;
var iframe = dialogOption.BodyElement.getElementsByTagName("iframe")[0];
if (iframe && !disabledUnload) {
if (typeof (iframe.onunload) != "undefined")
iframe.onunload();
// clear iframe to avoid memory leaks
dialogOption.BodyElement.removeChild(iframe);
iframe.DialogOptions.IFrame = null;
iframe.DialogOptions = null;
};
var dialog = this;
this.zIndex--;
var hasOtherDialog = document.body.querySelectorAll(".dialog-box").length > 1;
if (!hasOtherDialog) {
if (dialogOption.NoFadeAnimation) {
dialogOption.Backdrop.parentElement.removeChild(dialogOption.Backdrop);
if (!document.body.querySelector(".modal-backdrop.fade.in")) {
document.body.classList.remove("modal-open");
}
}
else {
AnimationService.Animate(dialogOption.Backdrop, "in").done(function () {
dialogOption.Backdrop.parentElement.removeChild(dialogOption.Backdrop);
if (!document.body.querySelector(".modal-backdrop.fade.in")) {
document.body.classList.remove("modal-open");
}
});
}
}
else {
if (this.Stacks.length > 0) {
var otherDialogOption = this.Stacks[this.Stacks.length - 1];
if (otherDialogOption && otherDialogOption !== dialogOption) {
if (otherDialogOption.NoFadeAnimation) {
AnimationService.Animate(dialogOption.Backdrop, "in");
otherDialogOption.Element.before(dialogOption.Backdrop);
}
}
}
}
var dialogDeferred = dialogOption.Defer;
AnimationService.Animate(dialogOption.Element, "in").done(function () {
if (hasOtherDialog) {
dialogOption.Backdrop.style.zIndex = dialog.zIndex - 1;
}
console.log("remove dialog element");
if (dialogOption.Element.parentElement)
dialogOption.Element.parentElement.removeChild(dialogOption.Element);
dialogDeferred.closeWith(dialog, [dialogOption, dialogOption.Model]);
});
}
this.Initialize = function () { }
this.CreateDialog = function (dialogOption) {
var dialog = document.createElement("div");
dialog.className = this.FrameStyle;
dialog.setAttribute("tabindex", "-1");
dialog.setAttribute("data-backdrop", "static");
dialog.setAttribute("role", "dialog");
dialog.setAttribute("aria-labelledby", "dialogPresenter");
dialog.setAttribute("role", "dialog");
dialog.setAttribute("role", "dialog");
dialog.innerHTML = '';
dialog.style.zIndex = this.zIndex;
if (dialogOption.Scrollable) {
dialog.classList.add("modal-scrollable-content");
}
else {
dialogOption.Height = "auto";
dialog.classList.remove("modal-scrollable-content");
}
dialogOption.Element = dialog;
dialogOption.HeaderElement = dialog.getElementsByClassName("modal-header")[0];
dialogOption.TitleElement = dialog.getElementsByClassName("modal-title")[0];
dialogOption.BodyElement = dialog.getElementsByClassName("modal-body")[0];
dialogOption.FooterElement = dialog.getElementsByClassName("modal-footer")[0];
dialogOption.FooterLeftElement = dialog.getElementsByClassName("modal-footer-left")[0];
dialogOption.ContainerElement = dialog.getElementsByClassName("modal-dialog")[0];
dialogOption.DialogEl = dialog.getElementsByClassName("modal-content")[0];
dialogOption.Element.IsCloseEvent = false;
if (dialogOption.ExpandBodyHeight) {
let headerHeight = dialogOption.ShowHeader ? 65 : 0;
let footerHeight = dialogOption.ShowFooter ? 65 : 0;
dialogOption.BodyElement.style.height = `calc(100vh - ${headerHeight + footerHeight}px)`;
}
if (dialogOption.Align) {
dialog.classList.add(dialogOption.Align);
}
if (dialogOption.NoMargin) {
let noMargin = dialogOption.NoMargin.split(",");
noMargin.each((item) => {
dialogOption.ContainerElement.classList.add("no-margin-" + item);
});
}
if (dialogOption.Width == "")
dialogOption.Width = "500px";
dialogOption.HeaderElement.style.display = dialogOption.ShowHeader ? "" : "none";
if (dialogOption.ShowHeader) {
dialogOption.HeaderElement.style.display = "";
dialogOption.TitleElement.innerHTML = dialogOption.Title;
}
else {
dialogOption.HeaderElement.style.display = "none";
}
if (dialogOption.IsStaticBackdrop) {
dialogOption.Element.setAttribute("data-backdrop", "static");
}
else {
dialogOption.Element.removeAttribute("data-backdrop");
}
dialogOption.BodyElement.setAttribute("content-mode", dialogOption.ContentMode);
if (dialogOption.ContentMode == "iframe" && dialogOption.ContentUrl) {
if (!dialogOption.IFrame)
dialogOption.IFrame = document.createElement("iframe");
dialogOption.IFrame.DialogOptions = dialogOption;
dialogOption.IFrame.src = dialogOption.ContentUrl;
dialogOption.BodyElement.innerHTML = "";
dialogOption.BodyElement.appendChild(dialogOption.IFrame);
dialogOption.BodyElement.style.overflow = "hidden";
}
else {
if (dialogOption.Content) {
dialogOption.BodyElement.innerHTML = dialogOption.Content;
}
else if (dialogOption.ContentId) {
var contentEl = document.getElementById(dialogOption.ContentId);
if (contentEl)
dialogOption.BodyElement.innerHTML = contentEl.innerHTML;
}
dialogOption.BodyElement.style.overflow = "";
}
if (dialogOption.ContainerClass) {
dialogOption.ContainerElement.classList.add(dialogOption.ContainerClass);
}
dialogOption.FooterElement.style.display = dialogOption.ShowFooter ? "" : "none";
dialogOption.FooterLeftElement.innerHTML = dialogOption.LeftFooterTemplate;
return dialog;
}
this.CreateBackdrop = function (dialogOption) {
var backdrop = document.querySelector(".dialog-backdrop");
if (!backdrop) {
backdrop = document.createElement("div");
backdrop.className = this.BackdropStyle;
}
backdrop.style.zIndex = this.zIndex;
dialogOption.Backdrop = backdrop;
return backdrop;
}
}
function ConfirmOption(options) {
this.OKText = App.Resources.Proceed;
this.OKButtonType = "primary"; //primary default destructive
this.OKCommand = null;
this.CancelText = App.Resources.Cancel;
this.CancelButtonType = "default";
this.AutoClose = true;
this.ShowFooter = true;
this.ShowCancel = true;
this.ShowIcon = true;
this.Model = {};
this.TemplateId = "";
this.Template = "";
this.Text = "";
this.Type = "success"; //default, info, success, warning, and danger.
this.Width = "400px";
this.Height = "auto";
this.Left = 0;
this.Top = 100;
this.IsStaticBackdrop = false;
this.Scrollable = false;
ExtendableObject.call(this, options);
this.__SetProperty("ResolvedTemplate", null, function () {
if (this.Template)
return this.Template;
else if (this.TemplateId) {
var templateEl = document.getElementById(this.TemplateId);
if (templateEl)
return templateEl.innerHTML;
}
return "" + this.Text + "
";
});
this.__SetProperty("Icon", null, function () {
var icon = "";
switch (this.Type.toLowerCase()) {
case "info":
icon = "ios-information-outline";
break;
case "success":
icon = "ios-checkmark-outline webui-green-icon";
break;
case "danger":
case "error":
case "desctructive":
icon = "ios-close-outline webui-red-icon";
break;
case "warning":
default:
icon = "alert-circle-outline webui-warning-icon";
break;
}
return icon;
});
}
function AlertOption(options) {
if (typeof (options) == "undefined")
options = {};
if (typeof (options) == "string") {
options = {
Text: options
}
}
if (options) {
options.Type = options.Type ? options.Type : "warning";
options.ShowCancel = typeof (options.ShowCancel) == "boolean" ? options.ShowCancel : false;
options.OKText = typeof (options.OKText) == "string" ? options.OKText : App.Resources.OK;
}
ConfirmOption.call(this, options);
}
function PromptOption(options) {
if (typeof (options) == "undefined")
options = {};
if (typeof (options) == "string") {
options = {
TemplateId: options
}
}
if (options) {
options.Text = options.Text ? options.Text : "";
options.ShowIcon = typeof (options.ShowIcon) == "boolean" ? options.ShowIcon : false;
options.IsStaticBackdrop = typeof (options.IsStaticBackdrop) == "boolean" ? options.IsStaticBackdrop : true;
}
ConfirmOption.call(this, options);
}
function ConfirmPresenter(options) {
this.FrameStyle = "modal fade confirm-box";
this.BackdropStyle = "modal-backdrop fade confirm-backdrop";
this.ButtonStyle = "btn";
this.PrimaryButtonStyle = "primary";
this.DefaultButtonStyle = "default";
this.DestructiveButtonStyle = "danger";
ExtendableObject.call(this, options);
this.zIndex = 1060;
this.GetButtonStyle = function (type) {
var style = this.DefaultButtonStyle;
switch (type.toLowerCase()) {
case "primary":
style = this.PrimaryButtonStyle;
break;
case "destructive":
style = this.DestructiveButtonStyle;
break;
}
return this.ButtonStyle + " " + style;
}
this.CreateBackdrop = function (confirmOption) {
var backdrop = document.querySelector(".confirm-backdrop");
if (!backdrop) {
backdrop = document.createElement("div");
backdrop.className = this.BackdropStyle;
}
backdrop.style.zIndex = this.zIndex;
return backdrop;
}
this.CreateConfirm = function (confirmOption) {
var confirm = document.createElement("div");
confirm.className = this.FrameStyle;
confirm.setAttribute("tabindex", "-1");
confirm.setAttribute("role", "dialog");
confirm.setAttribute("aria-labelledby", "dialogPresenter");
confirm.setAttribute("role", "dialog");
confirm.setAttribute("role", "dialog");
confirm.style.zIndex = this.zIndex;
confirm.innerHTML = '' +
'
' +
'
' +
'
' +
'
' + confirmOption.ResolvedTemplate + '
' +
'' +
'
';
if (confirmOption.Scrollable) {
confirm.classList.add("modal-scrollable-content");
}
else {
confirmOption.Height = "auto";
confirm.classList.remove("modal-scrollable-content");
}
return confirm;
}
this.Show = function (confirmOption) {
var deferred = App.Deferred([
["resolve", "done", jQuery.Callbacks("memory stopOnFalse")],
["reject", "fail", jQuery.Callbacks("memory stopOnFalse")]
], true);
var promise = deferred.promise();
promise.Close = function () {
deferred.rejectWith(confirmOption.CancelCommand, [confirmOption.Model, confirmOption]);
};
var confirmPresenter = this;
if (typeof (confirmOption) == "string") {
confirmOption = new ConfirmOption({ Text: confirmOption });
}
confirmOption = confirmOption ? confirmOption : new ConfirmOption();
var backdrop = this.CreateBackdrop(confirmOption);
confirmOption.Backdrop = backdrop;
if (!confirmOption.Backdrop.parentElement) {
document.body.appendChild(confirmOption.Backdrop);
}
var confirm = this.CreateConfirm(confirmOption);
confirmOption.Element = confirm;
var dialogEl = confirmOption.Element.getElementsByClassName("modal-content")[0];
if (confirmOption.Top != "auto") {
dialogEl.style.top = confirmOption.Top + "px";
}
dialogEl.style.left = confirmOption.Left + "px";
this.ShowConfirm(confirmOption);
confirmOption.CancelCommand = new DelegateCommand({
Command: function (model, param) {
deferred.rejectWith(confirmOption.CancelCommand, [confirmOption.Model, confirmOption]);
}
});
confirmOption.OKCommand = new DelegateCommand({
Command: function (model, param) {
if (!confirmOption.__eventregistered) {
promise.done(function () {
if (confirmOption.AutoClose)
confirmPresenter.CloseConfirm(confirmOption);
return false;
});
}
confirmOption.__eventregistered = true;
deferred.resolveWith(confirmOption.OKCommand, [confirmOption.Model, confirmOption]);
}
});
EventManager.RegisterEvent(confirm, "click", function (event) {
if (event.target == this && !confirmOption.IsStaticBackdrop) {
promise.Close();
}
});
this.SetSize(confirmOption);
promise.fail(function () {
confirmPresenter.CloseConfirm(confirmOption);
})
promise.confirm = confirmOption;
return promise;
}
this.ShowConfirm = function (confirmOption) {
this.zIndex++;
document.body.classList.add("modal-open");
if (!confirmOption.Backdrop.parentElement) {
document.body.appendChild(confirmOption.Backdrop);
}
document.body.appendChild(confirmOption.Element);
var dialogEl = confirmOption.Element.getElementsByClassName("modal-content")[0];
confirmOption.__binding = App.BindingService.Bind(confirmOption.Element, { Model: confirmOption.Model, Option: confirmOption });
ISMaterialTheme.RegisterAllBehaviour(confirmOption.Element);
confirmOption.Element.style.display = "block";
if (confirmOption.Top == "auto") {
var top = (dialogEl.ownerDocument.body.offsetHeight - dialogEl.offsetHeight) / 2;
dialogEl.style.top = (top > 0 ? top : 10) + "px";
}
if (!confirmOption.Backdrop.classList.contains("in")) {
AnimationService.Animate(confirmOption.Backdrop, "in");
}
AnimationService.Animate(confirmOption.Element, "in");
}
this.CloseConfirm = function (confirmOption) {
var confirmPresenter = this;
this.zIndex--;
if (confirmOption.__binding) {
App.BindingService.Unbind(confirmOption.__binding);
confirmOption.__binding = null;
}
var hasOtherConfirm = document.body.querySelectorAll(".confirm-box").length > 1;
if (!hasOtherConfirm) {
console.log("animating-in backdrop");
AnimationService.Animate(confirmOption.Backdrop, "in").done(function () {
console.log("remove backdrop");
confirmOption.Backdrop.parentElement.removeChild(confirmOption.Backdrop);
if (!document.body.querySelector(".modal-backdrop.fade.in")) {
document.body.classList.remove("modal-open");
}
});
}
AnimationService.Animate(confirmOption.Element, "in").done(function () {
if (hasOtherConfirm) {
confirmOption.Backdrop.style.zIndex = confirmPresenter.zIndex - 1;
}
console.log("remove confirm element");
if (confirmOption.Element.parentElement)
confirmOption.Element.parentElement.removeChild(confirmOption.Element);
});
}
this.SetSize = function (confirmOption) {
var container = confirmOption.Element.querySelector(".modal-dialog");
container.style.maxWidth = "";
if (!isNaN(parseInt(confirmOption.Width))) {
container.style.width = "100%";
if (confirmOption.Width.indexOf('%') < 0 && confirmOption.Width.indexOf('px') < 0)
confirmOption.Width += "px";
container.style.maxWidth = confirmOption.Width;
}
container.style.height = "";
if (confirmOption.Height != "auto" && !isNaN(parseInt(confirmOption.Height))) {
if (confirmOption.Height.indexOf('%') < 0 && confirmOption.Height.indexOf('px') < 0)
confirmOption.Height += "px";
var body = confirmOption.Element.querySelector(".modal-body");
body.style.height = confirmOption.Height;
}
}
this.GetIcon = function (type) {
var icon = "";
switch (type.toLowerCase()) {
case "info":
icon = "ios-information-outline";
break;
case "success":
icon = "ios-checkmark-outline webui-green-icon";
break;
case "danger":
case "error":
case "desctructive":
icon = "ios-close-outline webui-red-icon";
break;
case "warning":
default:
icon = "alert-circle-outline webui-warning-icon";
break;
}
return icon;
}
}
function ActivityPresenter(options) {
this.FrameStyle = "activity-presenter";
this.LoaderStyle = "ls-loader";
ExtendableObject.call(this, options);
this.Show = function (offsetEl) {
offsetEl = typeof (offsetEl) != "undefined" ? offsetEl : document.body;
var elLeft = 0, elTop = 0;
if (typeof offsetEl.getBoundingClientRect !== undefined) {
elLeft = offsetEl.getBoundingClientRect().left;
elTop = offsetEl.getBoundingClientRect().top;
}
elLeft += (window.pageXOffset || document.documentElement.scrollLeft) - (document.documentElement.clientLeft || 0);
elTop += (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0);
this.Element.style.left = elLeft + "px";
this.Element.style.top = elTop + "px";
this.Element.style.width = offsetEl.offsetWidth + "px";
this.Element.style.height = offsetEl.offsetHeight + "px";
AnimationService.Show(this.Element, "animate-opacity");
}
this.Hide = function () {
AnimationService.Hide(this.Element, "animate-opacity");
}
this.Initialize = function () {
this.Element = document.createElement("div");
var child = document.createElement("div");
this.Element.className = this.FrameStyle;
child.className = this.LoaderStyle;
this.Element.appendChild(child);
document.body.appendChild(this.Element);
this.Hide();
}
this.Initialize();
}
function ProgressPresenter(options) {
this.ProgressStyle = "loader-progress";
this.CompleteStyle = "complete";
this.OnComplete = function (el) { };
ExtendableObject.call(this, options);
this.Easing = function (p) {
if (p == 0) {
p = .01;
}
return (1 - p) * .3;
}
this.Show = function (progressName) {
var el;
if (progressName && progressName.nodeType === 1)
el = progressName;
else
el = document.querySelector('[data-progress="' + progressName + '"]');
if (!el) {
return false;
}
if (el.progressTimeout) {
clearTimeout(el.progressTimeout);
this.Complete(progressName);
}
el.style.backgroundSize = "0 2px";
el.offsetWidth;
if (!el.classList.contains(this.ProgressStyle)) {
el.classList.add(this.ProgressStyle);
}
this.SetProgress(progressName, 0);
};
this.SetProgress = function (progressName, progressValue) {
var el;
if (progressName && progressName.nodeType === 1)
el = progressName;
else
el = document.querySelector('[data-progress="' + progressName + '"]');
if (!el) {
return false;
}
if (el.progressTimeout) {
clearTimeout(el.progressTimeout);
}
if (el.classList.contains(this.CompleteStyle)) {
el.classList.remove(this.CompleteStyle);
}
progressValue = typeof (progressValue) == "number" && progressValue >= 0 ? progressValue : 0;
el.style.backgroundSize = progressValue + "% 2px";
var self = this;
if (progressValue >= 100) {
el.progressTimeout = setTimeout(function () {
self.Complete(progressName);
}, 500);
}
else {
el.progressTimeout = setTimeout(function () {
var left = (100 - progressValue);
progressValue = progressValue + (left * self.Easing(progressValue / 100));
self.SetProgress(progressName, progressValue);
}, 500);
}
}
this.Hide = function (progressName) {
var el;
if (progressName && progressName.nodeType === 1)
el = progressName;
else
el = document.querySelector('[data-progress="' + progressName + '"]');
if (!el) {
return false;
}
this.SetProgress(progressName, 100);
};
this.Complete = function (progressName) {
var el;
if (progressName && progressName.nodeType === 1)
el = progressName;
else
el = document.querySelector('[data-progress="' + progressName + '"]');
if (!el) {
return false;
}
el.classList.add(this.CompleteStyle);
el.style.backgroundSize = "";
el.offsetWidth;
if (this.OnComplete) {
this.OnComplete(progressName);
}
};
this.ShowLoader = function (progressName, title) {
var el;
if (typeof (progressName) == "string") {
el = document.querySelector('[data-progress="' + progressName + '"]');
if (!el) {
el = document.querySelector(progressName);
}
}
else if (progressName && progressName.nodeType === 1)
el = progressName;
if (!el || el.__LoaderShowed) {
return false;
}
for (var i = 0; i < el.children.length; i++) {
if (typeof el.children[i].oriOpacity == "undefined") {
el.children[i].oriOpacity = el.children[i].style.opacity;
}
el.children[i].style.opacity = 0;
}
var position = AnimationService.GetCurrentStyle(el).position;
if (position == "static") {
el.__oldposition = el.style.position;
el.style.position = "relative";
}
var loader = document.createElement("div");
loader.setAttribute("loader", "loader");
loader.className = "spin-progress hide";
loader.innerHTML = "" + (title ? " " + title : "") + "
";
el.appendChild(loader);
el.__LoaderShowed = true;
AnimationService.Show(loader, "animate-opacity");
var self = this;
return {
Close: function () {
self.HideLoader(el);
}
};
};
this.HideLoader = function (progressName) {
var el;
if (typeof (progressName) == "string") {
el = document.querySelector('[data-progress="' + progressName + '"]');
if (!el) {
el = document.querySelector(progressName);
}
}
else if (progressName && progressName.nodeType === 1)
el = progressName;
if (el.__LoaderShowed)
el.__LoaderShowed = false;
var loader = el.querySelector("[loader='loader']");
if (!el || !loader) {
return false;
}
AnimationService.Hide(loader, "animate-opacity", function () {
el.style.position = el.__oldposition;
el.removeChild(loader);
delete el.__oldposition;
for (var i = 0; i < el.children.length; i++) {
if (typeof (el.children[i].oriOpacity) !== "undefined") {
el.children[i].style.opacity = el.children[i].oriOpacity;
}
}
});
};
this.ShowProgressBox = function (title) {
var progress = new ConfirmOption({
IsStaticBackdrop: true,
Template: "",
ShowCancel: false,
ShowFooter: false,
ShowIcon: false,
Width: "40%",
Top: "auto"
});
var promise = App.PresenterService.Confirm.Show(progress);
var presenter = this;
promise.SetProgress = function (progressValue) {
var el = this.confirm.Element.getElementsByClassName("progress-bar")[0];
var self = this;
if (el.progressTimeout) {
clearTimeout(el.progressTimeout);
}
progressValue = typeof (progressValue) == "number" && progressValue >= 0 ? progressValue : 0;
if (progressValue >= 100) {
el.progressTimeout = setTimeout(function () {
self.SetComplete();
}, 500);
}
else {
el.progressTimeout = setTimeout(function () {
var left = (100 - progressValue);
el.style.width = progressValue + "%";
progressValue = progressValue + (left * presenter.Easing(progressValue / 100));
if (progressValue < 98)
self.SetProgress(progressValue);
}, 500);
}
}
promise.SetComplete = function () {
var el = this.confirm.Element.getElementsByClassName("progress-bar")[0];
el.style.width = "100%";
var self = this;
if (el.progressTimeout) {
clearTimeout(el.progressTimeout);
}
setTimeout(function () {
self.Close();
}, 300);
}
promise.SetProgress(0);
return promise;
}
}
function PresenterService(options) {
this.OnInitialize = function () { };
this.Dialog = new DialogPresenter();
this.Activity = new ActivityPresenter();
this.Progress = new ProgressPresenter();
this.Confirm = new ConfirmPresenter();
ExtendableObject.call(this, options);
this.OnInitialize();
}
function Breadcrumb(id) {
this.FrameStyle = "breadcrumb";
this.IconStyle = "breadcrumb-icon";
this.Id = id;
this.Initialize = function () {
this.Element = document.getElementById(this.Id);
this.Element.Object = this;
this.Element.className += " " + this.FrameStyle;
}
this.Update = function (items) {
while (this.Element.lastChild) {
this.Element.removeChild(this.Element.lastChild);
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (!item.Url)
continue;
var el = document.createElement("li");
var content = item.Title;
if (item.Icon && i == 0) {
content = '' + content;
}
if (i == (items.length - 1)) {
el.className = "active";
el.innerHTML = content;
}
else {
var a = document.createElement("a");
a.innerHTML = content;
el.appendChild(a);
a.NavigationItem = new NavigationItem(item.Url);
a.onclick = function () {
App.GetService("NavigationService").Navigate(this.NavigationItem);
return false;
}
}
this.Element.appendChild(el);
}
}
this.Initialize();
}
function BreadcrumbItem(option) {
this.Title = "";
this.Url = "";
this.Icon = "";
ExtendableObject.call(this, option);
}
function NavigationItem(options) {
if (typeof (options) == "string") {
options = {
Url: options
}
}
this.Url = "";
this.Parameter = "";
this.Type = "";
this.Title = "";
this.Icon = "";
this.PageTitle = "";
this.ContentUrl = "";
ExtendableObject.call(this, options);
this.__SetMethod("OnInitialize", function () {
if (this.Url.indexOf("?") >= 0) {
var path = this.Url.split("?");
this.Url = path[0];
var search = path[1];
if (search) {
this.Parameter = {};
var pairs = search.split("&");
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i];
if (pair === "") continue;
pair = pair.split("=");
this.Parameter[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
}
}
if (this.Url.indexOf("http") == 0) {
this.Url = this.Url.replace(/^http(s)?:\/\/[^\/]+/i, "");
}
else if (this.Url.indexOf("/") > 0) {
this.Url = window.location.pathname.replace(/\/$/, "") + "/" + this.Url;
}
});
this.__SetMethod("GetQueryString", function () {
var querystring = "";
var hasParamContentUrl = this.ContentUrl.indexOf("?") >= 0;
if (this.Parameter) {
for (var prop in this.Parameter) {
var value = this.Parameter[prop] == null || typeof (this.Parameter[prop]) == "undefined" ? "" : this.Parameter[prop];
querystring += (querystring || hasParamContentUrl ? "&" : "?") + encodeURIComponent(prop) + "=" + encodeURIComponent(value);
}
}
return querystring;
});
this.__SetProperty("CompleteUrl", null, function () {
var result = this.Url;
var querystring = "";
for (var prop in this.Parameter) {
var value = this.Parameter[prop] == null || typeof (this.Parameter[prop]) == "undefined" ? "" : this.Parameter[prop];
var regex = new RegExp("{" + prop + "}", "ig");
if (result.match(regex)) {
result = result.replace(regex, value);
}
else {
value = encodeURIComponent(value);
querystring += (querystring ? "&" : "") + encodeURIComponent(prop) + "=" + encodeURIComponent(value);
}
}
return result + (result.indexOf("?") < 0 ? querystring ? "?" : "" : "&") + querystring;
});
this.__SetProperty("RequestAddress", null, function () {
return this.ContentUrl + this.GetQueryString();
});
this.OnInitialize();
}
function NavigationService(options) {
this.NavigationTarget = null;
this.SiteMap = null;
this.BeforeNavigate = function (navigationItem) { return true; };
this.AfterNavigate = function (navigationItem) { };
this.OnLoaded = function (navigationItem, element) { };
this.OnInitialize = function () { };
ExtendableObject.call(this, options);
this.GetContentWindow = function () {
return this.NavigationTarget ? this.NavigationTarget.contentWindow : window;
}
this.Reload = function (wind) {
if (wind === true) {
return this.Navigate(this.CurrentNavigationItem);
}
if (wind == null) {
wind = window;
}
wind.location.reload();
}
this.GetContentDoc = function () {
return this.NavigationTarget ? this.NavigationTarget.contentDocument : document;
}
this.Navigate = function (navigationItem, navigationTarget) {
if (typeof (navigationItem) == "string") {
navigationItem = new NavigationItem(navigationItem);
}
if (!navigationItem.Title)
this.SetNavigationInfo(navigationItem);
navigationTarget = typeof (navigationTarget) != "undefined" ? navigationTarget : this.NavigationTarget;
if (navigationTarget) {
if (navigationTarget.getAttribute("src") == navigationItem.RequestAddress) {
return false;
}
}
else {
if (navigationItem.CompleteUrl == window.location.pathname)
return false;
}
navigationItem.__isHandled = false;
try {
if (this.BeforeNavigate && !this.BeforeNavigate(navigationItem, navigationTarget)) {
return false;
}
}
catch (e) {
}
this.PrevNavigationItem = this.CurrentNavigationItem;
this.CurrentNavigationItem = navigationItem;
if (navigationTarget) {
window.App.CurrentPage = null;
navigationTarget.contentWindow.location.replace(navigationItem.RequestAddress);
if (App.RootWindow.location.pathname + App.RootWindow.location.search == navigationItem.CompleteUrl)
history.replaceState(navigationItem.Parameter, navigationItem.PageTitle, navigationItem.CompleteUrl);
else
history.pushState(navigationItem.Parameter, navigationItem.PageTitle, navigationItem.CompleteUrl);
//navigationTarget.src = navigationItem.RequestAddress;
}
else {
window.location.href = navigationItem.CompleteUrl;
}
if (this.AfterNavigate) {
this.AfterNavigate(navigationItem, navigationTarget);
}
}
this.SetCurrentNavigationItem = function () {
var navigationItem = new NavigationItem(window.location.pathname + window.location.search);
navigationTarget = this.NavigationTarget;
if (navigationTarget)
this.Navigate(navigationItem, navigationTarget);
}
this.CreateNavigationItemFromNode = function (node) {
var url = node.getAttribute("url");
if (!url) url = "";
var navigationItem = new NavigationItem(url);
this.SetNavigationInfo(navigationItem, node);
return navigationItem;
}
this.SetNavigationInfo = function (navigationItem, node) {
if (!this.SiteMap)
return false;
node = node ? node : this.GetSiteMapNode(navigationItem);
if (!node) {
navigationItem.ContentUrl = "/404.html";
return false;
}
navigationItem.Url = node.getAttribute("url");
navigationItem.Title = node.getAttribute("title");
if (navigationItem.Title == "WorkShifts")
navigationItem.Title = "";
if (node.getAttribute("isfullrefresh")) {
var value = node.getAttribute("isfullrefresh")
if (value == "true") {
navigationItem.NavigationTarget = false;
}
}
var prop = navigationItem.Title.replace(/\s+/ig, "");
if (App.Resources.hasOwnProperty(prop)) {
navigationItem.Title = App.Resources[prop];
}
navigationItem.Icon = node.getAttribute("icon");
navigationItem.PageTitle = node.getAttribute("pagetitle");
if (!navigationItem.PageTitle) {
try {
navigationItem.PageTitle = node.querySelector("pageTitle").innerHTML;
}
catch (e) {
navigationItem.PageTitle = navigationItem.Title;
}
}
prop = navigationItem.PageTitle.replace(/\s+/ig, "");
if (App.Resources.hasOwnProperty(prop)) {
navigationItem.PageTitle = App.Resources[prop];
}
navigationItem.ContentUrl = node.getAttribute("content-url");
if (!navigationItem.ContentUrl && navigationItem.Url)
navigationItem.ContentUrl = "/WebForm" + navigationItem.Url.split("?")[0].trim() + ".aspx";
}
this.GetSiteMapNode = function (navigationItem, nodes) {
var result = null;
if (!nodes) {
if (this.SiteMap)
nodes = this.SiteMap.children;
else
return result;
}
nodes = typeof (nodes) == "undefined" ? this.SiteMap.children : nodes;
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var url = node.getAttribute("Url")
if (url) {
if (!navigationItem.Parameter) {
navigationItem.Parameter = {};
}
var regex = new RegExp("^" + url.replace(/\{[^\{\}]+\}/ig, "([^\/]+)") + "$", "i");
var values = null;
if ((values = navigationItem.Url.match(regex))) {
var names = url.match(/\{[^\{\}]+\}/ig);
for (var i = 1; i < values.length; i++) {
var value = values[i];
var name = names[i - 1].substring(1, names[i - 1].length - 1);
if (!navigationItem.Parameter.hasOwnProperty(name) && value.indexOf("{") < 0)
navigationItem.Parameter[name] = value;
}
return node;
}
}
result = this.GetSiteMapNode(navigationItem, node.children);
if (result)
return result;
}
return null;
}
//for breadcrumb
this.GetNavigationPath = function (navigationItem) {
var items = [];
items.unshift(navigationItem);
var xmlNode = this.GetSiteMapNode(navigationItem);
if (xmlNode) {
xmlNode = xmlNode.parentElement;
while (xmlNode && xmlNode.tagName != "XML") {
var item = this.CreateNavigationItemFromNode(xmlNode);
xmlNode = xmlNode.parentElement;
if (!item.Url)
continue;
items.unshift(item);
}
}
return items;
}
//
var navigationTarget = this.NavigationTarget;
Object.defineProperty(this, "NavigationTarget", {
set: function (value) {
if (!value)
return false;
navigationTarget = value;
var self = this;
navigationTarget.onload = function () {
if (self.OnLoaded) {
self.OnLoaded(self.CurrentNavigationItem, this.contentWindow);
}
}
navigationTarget.onbeforeunload = function () {
App.PresenterService.Dialog.Close();
if ((App.CurrentPage && App.CurrentPage.HasUnsavedChanges()) || (App.DialogPage && App.DialogPage.HasUnsavedChanges()))
return App.Resources.DirtyFormConfirm;
}
},
get: function () {
return navigationTarget;
},
configurable: true,
enumerable: true
});
window.onbeforeunload = function () {
App.PresenterService.Dialog.Close();
if ((App.CurrentPage && App.CurrentPage.HasUnsavedChanges()) || (App.DialogPage && App.DialogPage.HasUnsavedChanges()))
return App.Resources.DirtyFormConfirm;
}
window.onpopstate = function (state) {
App.PresenterService.Dialog.Close();
App.NavigationService.Navigate(window.location.pathname + window.location.search);
}
this.OnInitialize();
}
var CookieManager = {
Set: function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
},
Get: function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
Delete: function (name) {
this.Set(name, "", -1);
}
}
// Page
function PageBase(options) {
this.OnItemChange = function () { };
this.OnUnload = function () { };
this.OnNavigated = function () { };
this.OnInitialize = function () { };
this.OnPageReady = function () { };
this.OnModelPropertyChanged = function (entity, prop, oldValue, newValue) {
}
this.HasUnsavedChanges = function () {
return App.DataContext.HasDirtyEntity;
};
ExtendableObject.call(this, options);
this.InitializeQueryableWebCombo = function (id) {
var combo = ISGetObject(id);
combo.ClientBindingSettings.IncludeJsonState = true;
}
}
function DefaultPage(options, isAutoInitialize) {
this.IsOutletAware = true;
this.Options = {};
this.ActionButtonBar = {};
this.OnAction = function (button, model, param) {
if (typeof (this["Execute" + button.Name]) == "function") {
this["Execute" + button.Name].call(button.Command, model, param);
}
};
PageBase.call(this, options);
this.OnInitialize = function () {
var services = App.GetAllService();
this.SetOptions(services);
this.UpdateActionButtonBar();
};
this.ShowRightMenu = function () {
Page.IsShowRightSideMenu = true;
};
this.HideRightMenu = function () {
Page.IsShowRightSideMenu = false;
};
this.OnUnload = function () {
App.BindingService.Unbind(this.BindingView);
};
this.UpdateActionButtonBar = function () {
var self = this;
if (this.AppBarPrimaryAction) {
var item = this.AppBarPrimaryAction;
item.Command = new DelegateCommand({
Command: function (model, param) {
var button = null;
try {
button = model.AppBar.PrimaryButton;
}
catch (e) {
button = model.Page.AppBarPrimaryAction;
}
self.OnAction(button, self, param);
}
});
item.Type = "primary";
this.AppBarPrimaryAction = new ActionButton(item);
App.AppBar.PrimaryButton = this.AppBarPrimaryAction;
}
else {
App.AppBar.PrimaryButton = null;
}
if (!isNaN(this.AppBarMaxVisibleAction)) {
App.AppBar.MaxShowedAction = this.AppBarMaxVisibleAction;
}
App.AppBar.SecondaryButtons = [];
if (this.AppBarSecondaryActions) {
var items = this.AppBarSecondaryActions;
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (!item.Children) {
item.Command = new DelegateCommand({
Command: function (model, param) {
self.OnAction(model.abutton, self, param);
}
});
}
else {
var currentGroup = null;
var sortedChildren = item.Children.sort(function (p1, p2) { return p1.Group > p2.Group ? p1.Group == p2.Group ? 0 : 1 : -1; });
item.Children = [];
for (var j = 0; j < sortedChildren.length; j++) {
var childItem = sortedChildren[j];
if (currentGroup != childItem.Group) {
var groupItem = {
Caption: childItem.Group,
Group: childItem.Group,
IsGroup: true,
Type: "Default"
};
var group = new ActionButton(groupItem);
item.Children.push(group);
currentGroup = childItem.Group;
}
var childInfoButton = new ActionButton(childItem);
childInfoButton.Command = new DelegateCommand({
Command: function (model, param) {
self.OnAction(model.childbutton, model, param);
}
});
if (childInfoButton.Type.toLowerCase() == "primary") {
childInfoButton.Type = "default";
}
item.Children.push(childInfoButton);
}
}
App.AppBar.SecondaryButtons.push(item);
}
}
App.AppBar.HelpLink = self.HelpLink;
}
this.OnNavigated = function () {
if (this.TemplateSelector) {
var template = document.querySelector(this.TemplateSelector);
if (template)
this.BindingView = App.BindingService.Bind(template, { Page: Page, Model: Page.Item, AppModel: App.Model });
}
};
if (isAutoInitialize !== false) {
this.OnInitialize();
}
}
function FormPage(options) {
this.Item = {};
this.FormType = "New"; // New, Edit
this.EntityType = "";
this.IsDirty = false;
DefaultPage.call(this, options, false);
this.OnItemChange = function (text, value) {
if (text) {
var curNav = App.NavigationService.CurrentNavigationItem;
App.AppBar.Breadcrumbs[App.AppBar.Breadcrumbs.length - 1].Title = text;
var jumplistWidth = window.parent.document.querySelector(".breadcrumb > li.active").offsetWidth;
App.AppBar.JumpModel.SetJumpListWidth((text.length * 14.4) + 35 + "px");
if (curNav.Parameter && curNav.Parameter.id != value) {
curNav.Parameter.id = value;
setTimeout(function () {
App.NavigationService.Navigate(curNav);
});
}
}
}
this.ExecuteSave = function (model, param) {
return App.DefaultHandler("SaveCommand")(this, Page.Item);
}
this.ExecuteDuplicate = function (model, param) {
return App.DefaultHandler("DuplicateCommand")(this, Page.Item);
}
this.ExecuteCancel = function () {
return App.DefaultHandler("CancelCommand")(this, Page.Item);
}
this.SetJumpList = function () {
if (!window.ISGetObject) return;
var combo = window.ISGetObject("JumpListCombo");
if (!combo) return;
combo.Value = Page.Item.GetKeyValues();
if (!combo.Text) {
App.HttpService.Request("POST", Page.JumpListServiceUrl + "/" + Page.JumpListSelectMethod, {
CurrentValue: combo.Value
}).done(function (result) {
var text = result.Results[0].Text;
combo.SetText(text);
Page.OnItemChange(text, Page.Item.GetKeyValues());
})
}
return;
}
this.OnJumplistSelecting = function (combo, selectArguments) { }
this.OnNavigated = function () {
if (Page.FormPageType)
document.documentElement.setAttribute("form-type", Page.FormPageType);
for (var prop in this.FormBag) {
this.DataContext.ParseEntities(this.FormBag[prop], this.DataContext.GetTypeName(prop));
this.DataContext.SetUnchanged(this.FormBag[prop]);
};
this.DataContext.ParseEntity(this.Item, this.EntityType);
if (this.FormType === "New")
this.DataContext.SetAdd(this.Item);
if (this.TemplateSelector) {
var template = document.querySelector(this.TemplateSelector);
if (template)
this.BindingView = App.BindingService.Bind(template, { Page: Page, Model: Page.Item, AppModel: App.Model });
}
if (this.FormType === "Edit" && this.HasJumpList) {
this.SetJumpList();
}
};
this.OnInitialize();
}
function ModalPage(options) {
PageBase.call(this, options, false);
this.HasUnsavedChanges = function () {
return App.DataContext.HasDirtyEntity && this.FormType == "Edit";
};
this.IsDirty = false;
this.FormType = "New"; // New, Edit
this.OnUnload = function (dialogOptions) {
App.DialogPage = this.ParentDialog;
if (dialogOptions.rvFrameView) {
App.BindingService.Unbind(dialogOptions.rvFrameView);
dialogOptions.rvFrameView = null;
}
};
this.OnInitialize = function () {
var services = App.GetAllService();
this.SetOptions(services);
};
this.OnNavigated = function (dialogOptions) {
var model = null;
if (dialogOptions != null) {
this.DialogOption = dialogOptions;
model = dialogOptions.Model;
if (model && model.Is && model.Is(this.EntityType)) {
for (var prop in this.Item) {
if (!dialogOptions.Model.hasOwnProperty(prop))
dialogOptions.Model[prop] = this.Item[prop];
}
this.Item = dialogOptions.Model;
}
else {
this.Item = App.DataContext.ParseEntity(this.Item, this.EntityType);
dialogOptions.Model = this.Item;
dialogOptions.rvView.models.Model = dialogOptions.Model;
}
this.FormType = "Edit";
}
if (this.FormPageType)
document.documentElement.setAttribute("form-type", Page.FormPageType);
for (var prop in this.FormBag) {
this.DataContext.ParseEntities(this.FormBag[prop], this.DataContext.GetTypeName(prop));
this.DataContext.SetUnchanged(this.FormBag[prop]);
};
// set DialogPage earlier, allow formatter to work properly
this.ParentDialog = App.DialogPage;
App.DialogPage = this;
if (dialogOptions.Model && !dialogOptions.rvFrameView) {
var template = document.getElementById("maincontent");
dialogOptions.rvFrameView = App.BindingService.Bind(template ? template : document.body, { Page: this, Model: this.Item });
}
this.OnPageReady(model);
};
this.OnInitialize();
}
function ListPage(options) {
this.SearchColumns = [];
this.DefaultViewIndex = 0;
this.EditUrl = App.NavigationService.CurrentNavigationItem.Url + "/{id}";
DefaultPage.call(this, options, false);
this.Edit = function (id) {
var breadcrumbTitles = Array.prototype.slice.call(arguments, 1, arguments.length - 2);
var navigationItem = new NavigationItem({ Url: this.EditUrl, Parameter: { id: id } });
navigationItem.BreadcrumbTitles = breadcrumbTitles;
this.NavigationService.Navigate(navigationItem);
event.preventDefault();
}
this.LastSearchText = "";
this.SearchText = "";
this.FilterView = null;
this.SelectedView = null;
this.TabView = null;
this.Infobar = null;
this.Grid = null;
// filter
this.NewFilter = new EntityBase({
__entityType: "Filter",
PropertyName: "",
Operator: "",
Value: "",
OnPropertyChanged: function (propertyName, oldValue, newValue) {
App.BindingService.TriggerChange(this, propertyName);
Page.AddFilterCommand.RaiseCanExecuteChange();
if (propertyName == "Value" && Page.Filters) {
var filterPropertyName = this.PropertyName;
var filter = Page.Filters.find(function (f) { return f.PropertyName == filterPropertyName });
if (filter && filter.InputType == "Number") {
this.Value = App.Round(newValue, Page.InventoryPrecision)
}
}
}
});
this.RemoveFilter = function (event, model) {
if (!Array.isArray(Page.UserFilters))
Page.UserFilters = [];
Page.UserFilters.remove(model.userfilter);
if (Page.SelectedView == Page.FilterView && !Page.FilterView.IsNew) {
Page.FilterView.IsNew = true;
}
if (Page.SelectedView == Page.FilterView && Page.FilterView.IsNew && Page.UserFilters.length <= 0) {
Page.TabViews.remove(Page.FilterView);
if (Page.CloseViewBehaviour == "SelectLastSelectedView" && Page.LastSelectedView) {
Page.ChangeView(Page.LastSelectedView);
}
else {
var index = Page.DefaultViewIndex;
if (index >= Page.TabViews.length) {
index = 0;
}
Page.ChangeView(Page.TabViews[index]);
}
}
else {
Page.RefreshVisualization();
}
}
this.AddFilterCommand = new DelegateCommand({
Command: function (model, param) {
var displayValue = "";
if (Page.SelectedFilter.SelectionSource) {
var valueItem = Page.SelectedFilter.SelectionSource.find(function (item) { return item.Value.toString() == Page.NewFilter.Value; })
if (valueItem) {
displayValue = valueItem.Text;
}
}
if (Page.SelectedFilter.InputType == "DateTime") {
var newDate = new Date(Page.NewFilter.DateValue);
newDate.setHours(0, 0, 0, 0);
displayValue = newDate.toString();
}
displayValue = displayValue.replace(" ", "");
var item = {
PropertyName: Page.NewFilter.PropertyName,
Operator: Page.NewFilter.Operator,
Value: Page.SelectedFilter.InputType == "DateTime" ? Page.NewFilter.DateValue : Page.NewFilter.Value,
DisplayValue: displayValue
};
if (!Array.isArray(Page.UserFilters))
Page.UserFilters = [];
if (Page.UserFilters.add(item)) {
Page.ExecuteFilter("", Page.UserFilters, Page.SearchText, true);
Page.NewFilter.PropertyName = null;
document.body.click();
}
},
CanExecuteCommand: function (model, param) {
return !Object.isEmptyValue(Page.NewFilter.PropertyName) && !Object.isEmptyValue(Page.NewFilter.Operator) && !Object.isEmptyValue(Page.SelectedFilter.InputType == "DateTime" ? Page.NewFilter.DateValue : Page.NewFilter.Value);
}
})
this.ExecuteSaveFilter = function (event, model) {
var option = DialogOptions.GetModalOptions("save-filter-modal");
var filterModel = {
SearchText: Page.SearchText,
Filters: Page.UserFilters
};
option.Model = App.DataContext.DbSet("UserSavedFilter").New({
EntityType: Page.EntityType,
Filter: JSON.stringify(filterModel)
}, false);
App.PresenterService.Dialog.Show(option).done(function (commandName, data, model, dialog) {
var command = this;
if (commandName == "SaveCommand") {
var promise = dialog.DefaultHandler("SaveCommand")(command, data);
promise.done(function (result, status, object) {
if (result.IsSuccess) {
Page.SavedFilters.unshift({
Title: data.Name,
Name: data.UserSavedFilterId,
Filter: filterModel
});
Page.FilterView.Title = data.Name;
Page.FilterView.IsNew = false;
dialog.Close();
}
});
}
else
dialog.DefaultHandler("CancelCommand")(command, data);
});
};
this.ApplySavedFilter = function (event, model) {
Page.ExecuteFilter(model.filter.Title, model.filter.Filter.Filters, model.filter.Filter.SearchText, false);
};
this.ExecuteFilter = function (title, filters, search, isNew) {
Page.FilterView.IsNew = isNew;
Page.FilterView.Title = title;
Page.FilterView.Count = 0;
if (filters && filters.length > 0) {
filters.each(function (f) {
if (typeof f.Value.getMonth === 'function' && !f.DisplayValue) {
f.Value.setHours(0, 0, 0, 0);
f.DisplayValue = f.Value.toString();
}
});
}
Page.FilterView.Filter = {
SearchText: search,
Filters: filters
};
if (search) {
Page.SearchText = "";
}
Page.ChangeView(Page.FilterView);
}
this.OnSelectedFilterChange = function (event, model) {
if (!Page.Filters) {
return;
}
Page.SelectedFilter = Page.Filters.find(function (item) { return item.PropertyName == Page.NewFilter.PropertyName; });
if (Page.SelectedFilter) {
var filter = Page.SelectedFilter;
Page.NewFilter.Operator = filter.FilterOperators[0].Value;
Page.NewFilter.Value = "";
if (Page.SelectedFilter.InputType == "Selection") {
var filterCombo = ISGetObject("filterOptions");
filterCombo.TextObj.setAttribute("readonly", "readonly");
if (filter.SelectionSource)
Page.NewFilter.Value = filter.SelectionSource[0].Value.toString();
}
else if (Page.SelectedFilter.InputType == "LoadOnDemandSelection") {
var filterCombo = ISGetObject("filterOptions");
filterCombo.TextObj.removeAttribute("readonly");
if (!filter.__isSelectLoaded) {
App.HttpService.Get(filter.EntityType, "GetJumpList").done(function (result) {
if (result.IsSuccess && result.Data && Page.SelectedFilter == filter) {
filter.SelectionSource = result.Data;
Page.NewFilter.Value = "";
if (filter.SelectionSource && filter.SelectionSource.length > 0)
Page.NewFilter.Value = filter.SelectionSource[0].Value;
}
filter.__isSelectLoaded = true;
});
}
else {
if (filter.SelectionSource)
Page.NewFilter.Value = filter.SelectionSource[0].Value;
}
}
else if (Page.SelectedFilter.InputType == "DateTime") {
Page.NewFilter.DateValue = new Date();
}
}
}
this.DeleteFilterCommand = new DelegateCommand({
Command: function (model) {
var emt = this;
var confirmDelete = new ConfirmOption({
Text: (App.Resources.DeleteConfirm).formatString("Filter", model.filter.Title),
OKButtonType: 'destructive',
OKText: 'Delete'
});
App.PresenterService.Confirm.Show(confirmDelete).done(function () {
emt.IsProcessing = true;
Page.HttpService.HttpDelete("UserSavedFilter", "Delete", { primaryKeys: [model.filter.Name] }).done(function (result) {
if (result.IsSuccess) {
Page.SavedFilters.remove(model.filter);
Page.TabViews.remove(Page.FilterView);
Page.ChangeView(Page.LastSelectedView);
}
}).always(function () {
emt.IsProcessing = false;
});
}).fail(function () {
emt.IsProcessing = false;
});
}
});
// search
this.TriggerSearch = function (e) {
if (e.keyCode == 13) {
Page.ExecuteSearch();
}
}
this.ExecuteSearch = function (searchString) {
if (typeof (searchString) == "string") {
Page.SearchText = searchString;
}
if (Page.SearchText == Page.LastSearchText) {
return;
}
if (Page.SearchText) {
Page.AddRecentSearch(Page.SearchText);
}
Page.RefreshVisualization();
var searchEl = document.getElementById("search-textbox");
searchEl.blur();
};
this.ExecuteClearSearch = function (event, model) {
Page.ExecuteSearch("");
}
this.SearchOnBlur = function () {
Page.ExecuteSearch();
Page.HideSearchMenu();
}
this.SearchOnFocus = function () {
Page.ShowSearchMenu.call(this);
}
// view
this.ExecuteSelectView = function (event, model) {
if (Page.SelectedView != model.view)
Page.ChangeView(model.view);
}
this.ChangeView = function (view) {
if (view != Page.SelectedView) {
Page.LastSelectedView = Page.SelectedView;
if (view == Page.FilterView) {
Page.TabViews.add(Page.FilterView);
}
//if (Page.LastSelectedView.Filter && Page.LastSelectedView.Filter.SearchText == Page.SearchText) {
// Page.SearchText = "";
//}
Page.SelectedView = view;
}
else if (Page.SelectedView != Page.FilterView) {
return;
}
var selectedView = Page.TabViews.findIndex(function (q) { return q.Name == view.Name });
if (selectedView >= 0) {
Page.SelectedViewIndex = selectedView;
}
if (Page.SelectedView.Filter) {
Page.UserFilters = [];
if (Page.SelectedView.Filter.SearchText && !Page.SearchText) {
Page.SearchText = Page.SelectedView.Filter.SearchText;
}
Page.UserFilters = ([]).concat(Page.SelectedView.Filter.Filters);
}
else {
Page.UserFilters = null;
}
Page.IsShowFilter = Page.SelectedView == Page.FilterView && Page.UserFilters.length > 0;
if (Page.LastSelectedView)
Page.RefreshVisualization(true);
var selectedIndex = Page.TabViews.indexOf(Page.SelectedView);
var el = document.getElementById("segmented-button").children[selectedIndex];
if (el && el.scrollIntoView) {
el.scrollIntoView({ block: "end" });
}
}
this.RefreshVisualization = function (skip) {
// abort previous request if still in progress.
if (Page.Grid.IsInProgress) {
var old = Page.Grid.OnResponseError;
Page.Grid.OnResponseError = function () { };
Page.Grid.XmlHttp.Abort();
Page.Grid.OnResponseError = old;
Page.Grid.IsInProgress = false;
}
WG50Engine.ExecuteFlyPostback(Page.Grid.Name, "ColumnFilter", Page.Grid.RootTable.Id);
}
// ui aspect
this.ShowSearchMenu = function () {
if (Page.SearchMenuEl.style.opacity == 0) {
Page.SearchMenuEl.style.opacity = "";
Page.SearchMenuEl.classList.add("hide");
}
Page.SearchMenuEl.style.visibility = "";
var searchBoxPos = document.getElementById("search-textbox").getBoundingClientRect();
Page.SearchMenuEl.style.left = searchBoxPos.left + "px";
Page.SearchMenuEl.style.top = (searchBoxPos.bottom) + "px";
Page.SearchMenuEl.style.width = this.offsetWidth + "px";
Page.SearchMenuEl.style.height = "auto";
AnimationService.Show(Page.SearchMenuEl, "dropdown-animation");
}
this.HideSearchMenu = function () {
WebMenuEngine.CloseSubMenu(Page.SearchMenu.RootMenu, null, true);
AnimationService.Hide(Page.SearchMenuEl, "dropdown-animation");
}
this.OnNavigated = function (navigationItem) {
this.SearchContextMenu = ISGetObject("searchmenu");
// register usersavedfilter validation
App.DataContext.DbSet("UserSavedFilter").AddValidator(new RequiredValidator({
ErrorMessage: App.Resources.NameRequired,
MemberName: "Name"
}));
var self = this;
this.FilterView = {};
if (!this.SelectedViewIndex) {
this.SelectedViewIndex = 0;
}
this.Infobar = new InfoBar();
this.Infobar.Buttons = [];
if (this.ContextualActions) {
if (!isNaN(this.ContextualMaxVisibleAction)) {
this.Infobar.MaxVisibleAction = this.ContextualMaxVisibleAction;
this.Infobar.MaxMobileVisibleAction = this.ContextualMobileMaxVisibleAction;
}
for (var i = 0; i < this.ContextualActions.length; i++) {
var item = this.ContextualActions[i];
var infoButton = new ActionButton(item);
if (!item.Children) {
infoButton.Command = new DelegateCommand({
Command: function (model, param) {
self.OnAction(model.button, model, param);
}
});
}
else {
infoButton.Children = [];
var currentGroup = null;
var sortedChildren = item.Children.sort(function (p1, p2) { return p1.Group > p2.Group ? p1.Group == p2.Group ? 0 : 1 : -1; });
for (var j = 0; j < sortedChildren.length; j++) {
var childItem = sortedChildren[j];
if (currentGroup != childItem.Group) {
var groupItem = {
Caption: childItem.Group,
Group: childItem.Group,
IsGroup: true,
Type: "Default"
};
var group = new ActionButton(groupItem);
infoButton.Children.push(group);
currentGroup = childItem.Group;
}
var childInfoButton = new ActionButton(childItem);
childInfoButton.Command = new DelegateCommand({
Command: function (model, param) {
self.OnAction(model.childbutton, model, param);
}
});
if (childInfoButton.Type.toLowerCase() == "primary") {
childInfoButton.Type = "default";
}
infoButton.Children.push(childInfoButton);
}
}
if (infoButton.Type.toLowerCase() == "primary") {
infoButton.Type = "default";
}
this.Infobar.Buttons.push(infoButton);
}
}
var template = document.querySelector(".frame-content");
if (template)
this.BindingView = App.BindingService.Bind(template, { Page: Page });
var self = this;
if (this.TabViews && this.TabViews.length > this.SelectedViewIndex) {
this.ChangeView(this.TabViews[this.SelectedViewIndex]);
}
if (this.Grid) {
this.RefreshContextualAction();
this.Grid.ClientBindingSettings.IncludeJsonState = true;
if (this.InitialDataSource) {
this.Grid.RebindData(this.InitialDataSource.Results);
this.Grid.SetTotalRows(this.InitialDataSource.TotalRowCount);
}
}
this.GetViewCount();
};
this.GetViewCount = function () {
var selectArguments = {
SelectedViewIndex: Page.SelectedViewIndex,
SearchText: Page.SearchText,
UserFilters: Page.UserFilters
}
App.HttpService.Request("POST", this.Grid.ClientBindingSettings.ServiceUrl + "/GetViewCount", { selectArguments: selectArguments })
.done(function (result) {
if (result.Results) {
Page.TabViews = result.Results;
var selectedView = Page.TabViews.find(function (t) { return t.Name == Page.SelectedView.Name });
if (selectedView) {
Page.SelectedView = selectedView;
}
}
});
};
this.GetSelectedItems = function () {
var selectedRows = Page.Grid.RootTable.GetCheckedRows(true);
var items = selectedRows
.select(function (item) {
var rowObj = Page.Grid.RootTable.ToRowObject(item);
return rowObj.DataRow.ObjectContext;
});
return items;
};
this.GridUncheckAll = function () {
WGUIEngine.SetRowsCheck(Page.Grid.RootTable.GetElement(WG40.BODY, WG40.HTMLTABLE), 0, null, false);
WG50Engine.SetCheckedRowsData(Page.Grid)
}
// webgrid
this.RefreshContextualAction = function () {
var hTable = Page.Grid.RootTable.GetElement(WG40.COLHEADER, WG40.HTMLTABLE);
var allcheckbox = hTable.querySelector("input");
var loadedRowCount = Page.Grid.RootTable.GetRowsCount();
if (!allcheckbox)
return;
allcheckbox.checked = loadedRowCount > 0 && loadedRowCount <= Page.GetSelectedItems().length;
var grid = this.Grid;
var checkedRows = grid.RootTable.GetCheckedRows(true).length;
var searchEl = document.getElementById("search-box");
searchEl.style.transform = "";
if (checkedRows == 0) {
Page.Infobar.IsShowed = false;
}
else {
Page.Infobar.Text = checkedRows.toString() + " " + App.GetResourceString(this.EntityType + (checkedRows == 1 ? "" : App.Resources.Plural)) + " " + App.Resources.Selected;
Page.Infobar.IsShowed = true;
}
};
this.OnGridInitialize = function (controlId) {
this.Grid = ISGetObject(controlId);
this.Grid.RootTable.GetFilterRow().nextSibling.style.display = "none";
var clientEvent = this.Grid.LayoutSettings.ClientSideEvents;
clientEvent.OnColumnFilter = "Page.OnFilter;" + clientEvent.OnColumnFilter;
clientEvent.OnCheckBoxClick = "Page.OnGridCheckBoxClick;" + clientEvent.OnCheckBoxClick;
clientEvent.OnBeforeRequest = "Page.GridOnBeforeRequest";
clientEvent.OnResponse += "Page.OnGridAfterResponseProcess;" + clientEvent.OnResponse;
};
this.OnGridAfterInitialize = function () {
this.Grid.SetStatus2("", "loaded", this.Grid.TotalLoadedRows, this.Grid.TotalRows);
WG50Engine.ReflectNoDataStatus(this.Grid);
}
this.FormatGridCheckbox = function (controlId) {
var grid = ISGetObject(controlId);
var checkboxs = grid.FrameObj.querySelectorAll(".DefChkBox:not([initialized])");
for (var i = 0; i < checkboxs.length; i++) {
var checkbox = checkboxs[i];
var checkboxObj = new SelectionControl(checkbox);
checkboxObj.FrameStyle = "";
checkboxObj.Initialize();
checkbox.setAttribute("initialized", "");
}
};
// webgrid event
this.OnGridCheckBoxClick = function (controlId) {
if (Page._refreshContextTimeout) {
Page._refreshContextTimeout = clearTimeout(Page._refreshContextTimeout);
}
Page._refreshContextTimeout = setTimeout(function () {
Page.RefreshContextualAction();
Page._refreshContextTimeout = null;
}, 100);
};
this.GridOnBeforeRequest = function (id, action) {
switch (action) {
case "ColumnFilter":
// document.getElementsByClassName("grid-outerframe")[0].setAttribute("isrefreshing", "true");
break;
}
return true;
}
this.OnGridAfterResponseProcess = function (controlId, action) {
var grid = ISGetObject(controlId);
Page.FormatGridCheckbox(controlId);
if (!grid.RootTable.GetCheckedRows())
Page.RefreshContextualAction();
setTimeout(function () {
if ((Page.SelectedView.Filter && Page.SearchText == Page.SelectedView.Filter.SearchText) || !Page.SearchText) {
Page.SelectedView.Count = Page.Grid.TotalRows;
}
Page.RefreshContextualAction();
}, 100);
//document.getElementsByClassName("grid-outerframe")[0].removeAttribute("isrefreshing");
};
this.OnFilter = function (controlId, gridTable, title) {
var filters = [];
filters = filters.concat(Page.Grid.RootTable.FilteredColumns);
for (var i = 0; i < filters.length; i++) {
var filter = filters[i];
filter.XmlNode = null;
}
Page.ExecuteFilter(filters, null, true);
return false;
};
// menu event
this.OnSearchMenuClick = function (controlId, menuItem) {
Page.ExecuteSearch(menuItem.Text);
}
this.OnMenuInitialize = function (controlId) {
this.SearchMenu = ISGetObject(controlId);
var searchInput = document.getElementById("search-textbox");
this.SearchMenu.SetOffsetElement(searchInput);
this.SearchMenu.Show();
}
this.OnShowMenu = function (controlId, menu) {
if (!Page.SearchMenuEl) {
Page.SearchMenuEl = menu.Popup._e;
Page.SearchMenuEl.style.opacity = 0;
Page.SearchMenuEl.style.width = "100px";
menu.Popup.OnClosed = function () {
return false;
}
setTimeout(function () {
Page.SearchMenuEl.classList.add("hide");
if (Page.Grid && Page.Grid.TotalRows > 0 && document.getElementById("content_Grid_WebGrid1_ND")) {
document.getElementById("content_Grid_WebGrid1_ND").classList.add("hide");
}
}, 100);
}
}
this.SortWebGrid = function (colName, sortBy) {
if (!colName || !sortBy) return;
switch (sortBy) {
case "Ascending":
case "Descending":
break;
default:
return;
}
var elClicked = ((event) ? event.srcElement : wg_Global.EventContext);
if (elClicked) {
$(elClicked).closest("#sorting-dropdown").children("li").removeClass("active");
$(elClicked).parent("li").addClass("active");
}
var gh = $('tr[type="ColHeader"]');
if (gh.length < 1) return;
var g = gh[0];
var k = ISGetObject(WG50Engine.GetGridNameByRow(g.parentElement));
if (!k) return;
var x = k.Tables[WG50Engine.GetTableNameByRow(g.parentElement)];
if (!x) return;
var w = x.SortedColumns.GetNamedItem(colName);
if (!w) {
x.SortedColumns.Clear();
w = new WebGridGroup();
w.ColumnMember = colName;
w.SortOrder = sortBy;
x.SortedColumns.Add(w);
}
w.SortOrder = sortBy;
w._UIState = "Changed";
WGUIEngine.ProcessGroupedColumns(x);
WG50Engine.ExecuteFlyPostback(k.Name, "ChangeGroup", g);
return
}
this.AddRecentSearch = function (searchText) {
//clean text from html
searchText = searchText.replace(/<([^ ]+)[^>]*>(.*?)<\/\1>/ig, "$2");
var index = this.RecentSearches.indexOf(searchText);
if (index >= 0) {
this.RecentSearches.splice(index, 1);
this.SearchContextMenu.Items.RemoveAt(index + 2);
}
this.RecentSearches.unshift(searchText);
var item = new WebMenuItem(searchText, searchText);
item.Position = 2;
item.Enabled = true;
//fix
item.OnInsert = function (pos) {
if (!this.OwnerMenu)
this.OwnerMenu = this.Parent;
this.Collection = this.OwnerMenu.Items;
if (this.OwnerMenu.Element != null)
WebMenuEngine.InsertMenuItem(this, pos);
this.Collection.ReindexPosition();
};
this.SearchContextMenu.Items.InsertAt(item, item.Position);
x = parseInt(item.OwnerMenu.Popup._e.style.left);
y = parseInt(item.OwnerMenu.Popup._e.style.top);
item.OwnerMenu.Popup.show(x, y, 0, 0);
for (var i = 10; i < this.RecentSearches.length; i++) {
this.SearchContextMenu.Items.RemoveAt(this.RecentSearches.length + 1);
this.RecentSearches.pop();
}
var noRecentMenu = this.SearchContextMenu.Items.GetNamedItem("noRecent");
if (noRecentMenu)
noRecentMenu.Delete();
CookieManager.Set(this.RecentSearchCookieName, this.RecentSearches.join(this.RecentSearchDelim));
}
this.ClearGridBindings = function () {
if (Page.Grid != null) {
if (Page.Grid.Bindings) {
for (var i = 0; i < Page.Grid.Bindings; i++)
App.BindingService.Unbind(Page.Grid.Bindings[i]);
}
Page.Grid.Bindings = null;
}
};
this.OnGridRender = function (id, table, partialRows) {
if (!Page.Grid.Bindings)
Page.Grid.Bindings = [];
var rows = partialRows;
if (!rows)
rows = this.Grid.RootTable.Rows;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (!row.IsModelBound) {
var binding = App.BindingService.Bind(row.GetElement(), { Model: row.DataRow.ObjectContext, Page: Page, Index: i });
Page.Grid.Bindings.push(binding);
row.IsModelBound = true;
}
}
this.FormatGridCheckbox(id);
};
this.OnGridSelecting = function (grid, selectArguments) {
// clear bindings
this.ClearGridBindings();
if (Page.SearchText) {
selectArguments.SearchText = Page.SearchText;
}
if (Page.UserFilters) {
selectArguments.UserFilters = Page.UserFilters;
}
if (Page.SelectedViewIndex > 0) {
selectArguments.SelectedViewIndex = Page.SelectedViewIndex;
}
Page.LastSelectedArguments = selectArguments;
Page.LastSearchText = Page.SearchText;
};
this.OnUnload = function () {
// clear bindings
this.ClearGridBindings();
App.BindingService.Unbind(this.BindingView);
}
this.OnInitialize();
}
function ReportPage(options) {
DefaultPage.call(this, options, false);
this.SalesChannels = ["marketplace", "food_delivery"];
this.OnInitialize = function () {
var services = App.GetAllService();
this.SetOptions(services);
};
this.FilterView = null;
this.SelectedView = null;
this.KeepSystemFilter = true;
this.NewFilter = new EntityBase({
__entityType: "Filter",
PropertyName: "",
Operator: "",
Value: "",
OnPropertyChanged: function (propertyName, oldValue, newValue) {
App.BindingService.TriggerChange(this, propertyName);
Page.AddFilterCommand.RaiseCanExecuteChange();
if (propertyName == "Value" && Page.Filters) {
var filterPropertyName = this.PropertyName;
var filter = Page.Filters.find(function (f) { return f.PropertyName == filterPropertyName });
if (filter && filter.InputType == "Number") {
this.Value = App.Round(newValue, Page.InventoryPrecision)
}
}
}
});
var _selectedViewIndex = options.SelectedViewIndex;
Object.defineProperty(this, "SelectedViewIndex", {
set: function (value) {
_selectedViewIndex = value;
if (_selectedViewIndex == 1 && this.Chart) {
if (this.Chart.ChartInteractiveUI.ResponseTimeoutID == 1) {
this.Chart.ChartInteractiveUI.ResponseTimeoutID = 0;
this.Chart.ChartInteractiveUI.RefreshChart();
}
}
App.BindingService.TriggerChange(this, "SelectedViewIndex");
},
get: function () {
return _selectedViewIndex;
},
configurable: true,
enumerable: true
});
this.OnItemChange = function (text, value) {
if (text) {
var curNav = App.NavigationService.CurrentNavigationItem;
App.AppBar.Breadcrumbs = [new BreadcrumbItem({ Title: curNav.Title, Icon: curNav.Icon }), new BreadcrumbItem({ Title: text })];
// var jumplistWidth = window.parent.document.querySelector(".breadcrumb > li.active").offsetWidth;
App.AppBar.JumpModel.SetJumpListWidth((text.length * 14.4) + 35 + "px");
if (this.SelectedReportType != value) {
if (!curNav.Parameter)
curNav.Parameter = {};
curNav.Parameter.ReportType = value;
App.NavigationService.Navigate(curNav);
}
}
}
this.OnNavigated = function (navigationItem) {
this.FilterView = {};
// register usersavedfilter validation
App.DataContext.DbSet("UserSavedFilter").AddValidator(new RequiredValidator({
ErrorMessage: App.Resources.NameRequired,
MemberName: "Name"
}));
App.AppBar.JumpModel.Items = this.ReportTypes;
App.AppBar.JumpModel.SelectedItem = this.SelectedReportType;
var selectedChannel = this.ChannelList.find(function (item) { return item.Value == Page.SystemFilter.Channel; });
if (selectedChannel) {
Page.SystemFilter.Channel = -1;
Page.SetChannel(null, { channel: selectedChannel }, true);
}
if (this.SalesChannels.indexOf(Page.SystemFilter.Channel) >= 0) {
switch (Page.SystemFilter.Channel) {
case "marketplace":
Page.SystemFilter.ChannelText = App.Resources.Marketplace;
break;
case "food_delivery":
Page.SystemFilter.ChannelText = App.Resources.FoodDelivery;
break;
}
if (Page.SystemFilter.ChannelId) {
Page.SelectedChannelIdText = Page.SystemFilter.ChannelId;
Page.SystemFilter.ChannelText = Page.SelectedChannelIdText;
}
}
var template = document.querySelector(".frame-content");
if (template)
this.BindingView = App.BindingService.Bind(template, { Page: Page, Model: Page.Item, AppModel: App.Model });
Page.SetPredefinedDateRange(null, { daterange: { Value: Page.SystemFilter.PredefinedDateRange } });
switch (this.SystemFilter.PredefinedDateRange) {
case "Custom":
this.CustomDateRange = this.SystemFilter.PredefinedDateRange;
this.SystemFilter.DateRangeText = this.SystemFilter.CustomStartDate.toString("MMM dd, yyyy") + " - " + this.SystemFilter.CustomEndDate.toString("MMM dd, yyyy");
break;
case "SelectedDate":
this.CustomDateRange = this.SystemFilter.PredefinedDateRange;
this.SystemFilter.DateRangeText = this.SystemFilter.CustomStartDate.toString("MMM dd, yyyy");
break;
default:
this.SystemFilter.DateRangeText = this.PredefinedDateRangeList.find(function (item) { return item.Value == Page.SystemFilter.PredefinedDateRange; }).Text;
break;
}
Page.SetSummaryReportTitle();
// set jumplist height so all item visible.
var combo = ISGetObject("jumplist");
combo.FrameObj.parentElement.style.width = (Page.ReportTypes.find(function (o) { return o.Value === Page.SelectedReportType; }).Text.length * 14.4) + 35 + "px";
combo.LayoutSettings.ResultBoxHeight = (Page.ReportTypes.length * 32) + 12;
if (Page.SavedFilters) {
var filterModel = Page.SavedFilters.find(function (filterModel) { return filterModel.IsDefault });
if (filterModel) {
var defaultView = {
filter: filterModel
};
Page.ApplySavedFilter(null, defaultView, true);
}
}
};
this.RefreshSummaryData = function () {
var data = { ListAction: "RefreshSummaryData" };
if (Page.UserDimensions) data["UserDimensions"] = JSON.stringify(Page.UserDimensions);
if (Page.UserFilters) data["UserFilters"] = JSON.stringify(Page.UserFilters);
if (Page.UserMetrics) data["UserMetrics"] = JSON.stringify(Page.UserMetrics);
if (Page.SystemFilter) data["SystemFilter"] = JSON.stringify(Page.SystemFilter);
Page.SetBusy(true);
var promise = this.HttpService.Request("POST", window.location.href, data);
promise.done(function (result) {
if (result.IsSuccess) {
Page.SummaryData = result.Data;
Page.SetSummaryReportTitle();
Page.SetBusy(false);
}
})
}
this.SetSummaryReportTitle = function () {
if (Page.IsSummary) {
var dateRange = "";
if (Page.SystemFilter.PredefinedDateRange == "Custom")
dateRange = "from " + Page.SystemFilter.CustomStartDate.toString("MMM dd, yyyy") + " to " + Page.SystemFilter.CustomEndDate.toString("MMM dd, yyyy");
else
dateRange = Page.PredefinedDateRangeList.find(function (item) { return item.Value == Page.SystemFilter.PredefinedDateRange }).Text;
Page.SummaryData.ReportTitle = App.Model.StoreName + " - " + Page.ReportTypes.find(function (item) { return item.Value == Page.SelectedReportType }).Text + " Report " + dateRange;
}
}
this.OnSelectedFilterChange = function (event, model) {
if (!Page.Filters) {
return;
}
Page.SelectedFilter = Page.Filters.find(function (item) { return item.PropertyName == Page.NewFilter.PropertyName; });
if (Page.SelectedFilter) {
var filter = Page.SelectedFilter;
Page.NewFilter.Operator = filter.FilterOperators[0].Value;
Page.NewFilter.Value = "";
if (Page.SelectedFilter.InputType == "Selection") {
var filterCombo = ISGetObject("filterOptions");
filterCombo.TextObj.setAttribute("readonly", "readonly");
if (filter.SelectionSource)
Page.NewFilter.Value = filter.SelectionSource[0].Value;
}
else if (Page.SelectedFilter.InputType == "LoadOnDemandSelection") {
var filterCombo = ISGetObject("filterOptions");
filterCombo.TextObj.removeAttribute("readonly");
if (!filter.__isSelectLoaded) {
App.HttpService.Get(filter.EntityType, "GetJumpList").done(function (result) {
if (result.IsSuccess && result.Data && Page.SelectedFilter == filter) {
filter.SelectionSource = result.Data;
Page.NewFilter.Value = filter.SelectionSource[0].Value;
}
filter.__isSelectLoaded = true;
});
}
else {
if (filter.SelectionSource)
Page.NewFilter.Value = filter.SelectionSource[0].Value;
}
}
else if (Page.SelectedFilter.InputType == "DateTime") {
Page.NewFilter.DateValue = new Date();
}
}
}
this.AddMetric = function (event, model) {
var item = model.metric;
if (!Array.isArray(Page.UserMetrics))
Page.UserMetrics = [];
if (typeof (Page.UserMetrics) != "string")
item = item.PropertyName;
if (Page.UserMetrics.indexOf(item) >= 0)
Page.UserMetrics.remove(item);
else {
Page.UserMetrics.add(item)
}
Page.FilterView.Title = "";
Page.FilterView.IsNew = true;
Page.ExecuteFilter("", Page.UserFilters, Page.SearchText, true);
}
this.AddDimension = function (event, model) {
var item = model.dimension;
if (!Array.isArray(Page.UserDimensions))
Page.UserDimensions = [];
if (typeof (Page.UserDimensions) != "string")
item = item.PropertyName;
if (Page.UserDimensions.indexOf(item) >= 0)
Page.UserDimensions.remove(item);
else {
Page.UserDimensions.add(item)
}
Page.FilterView.Title = "";
Page.FilterView.IsNew = true;
Page.ExecuteFilter("", Page.UserFilters, Page.SearchText, true);
}
this.RemoveFilter = function (event, model) {
Page.FilterView.Title = "";
Page.FilterView.IsNew = true;
if (Array.isArray(Page.UserFilters) && Page.UserFilters.remove(model.userfilter))
Page.RefreshVisualization();
}
this.ExecuteSaveFilter = function (event, model) {
if (!Page.FilterView.IsNew && !model.filter) {
return;
}
var option = DialogOptions.GetModalOptions("save-filter-modal");
var filterModel = {}
if (model.filter) {
filterModel = model.filter.Filter;
option.Model = App.DataContext.ParseEntity({
UserSavedFilterId: model.filter.Name,
EntityType: Page.SelectedReportType,
Name: model.filter.Title,
IsDefault: model.filter.IsDefault,
IsGlobal: model.filter.IsGlobal,
Filter: ""
}, "UserSavedFilter");
option.Model.Filter = JSON.stringify(filterModel);
option.Model.IsDefault = model.filter.IsDefault;
option.Model.AcceptChanges();
}
else {
filterModel = {
SearchText: Page.SearchText,
Filters: Page.UserFilters,
Dimensions: Page.UserDimensions,
Metrics: Page.UserMetrics,
SystemFilter: Page.SystemFilter
};
option.Model = App.DataContext.DbSet("UserSavedFilter").New({
EntityType: Page.SelectedReportType,
Filter: JSON.stringify(filterModel),
IsGlobal: false,
IsDefault: false
}, false);
}
option.Height = "300px";
option.Model.SelectedReportTitle = App.AppBar.Breadcrumbs[App.AppBar.Breadcrumbs.length - 1].Title;
option.Model.IsAdmin = Page.IsAdmin;
var oldName = option.Model.Name;
App.PresenterService.Dialog.Show(option).done(function (commandName, data, model, dialog) {
var command = this;
if (commandName == "SaveCommand") {
var promise = dialog.DefaultHandler("SaveCommand")(command, data);
promise.done(function (result, status, object) {
if (result.IsSuccess) {
var filter = null;
if (Page.FilterView.IsNew) {
filter = {
Title: data.Name,
Name: data.UserSavedFilterId,
IsDefault: !!(data.IsDefault),
IsGlobal: !!(data.IsGlobal),
Filter: filterModel
};
Page.SavedFilters.push(filter);
}
else {
filter = Page.SavedFilters.find(function (filterModel) { return filterModel.Name == data.UserSavedFilterId });
filter.Title = data.Name;
filter.IsDefault = !!(data.IsDefault);
filter.IsGlobal = !!(data.IsGlobal);
}
if (filter.IsDefault) {
var otherDefault = Page.SavedFilters.find(function (filterModel) { return filterModel.IsDefault && filterModel.IsGlobal == filter.IsGlobal && filterModel.Name != filter.Name });
if (otherDefault) {
otherDefault.IsDefault = false;
}
}
if (Page.FilterView.IsNew || (oldName == Page.FilterView.Title)) {
Page.FilterView.Title = data.Name;
Page.FilterView.IsNew = false;
}
dialog.Close();
}
});
}
else
dialog.DefaultHandler("CancelCommand")(command, data);
});
};
this.DeleteFilterCommand = new DelegateCommand({
Command: function (model) {
var emt = this;
var confirmDelete = new ConfirmOption({
Text: (App.Resources.DeleteConfirm).formatString("Filter", model.filter.Title),
OKButtonType: 'destructive',
OKText: 'Delete'
});
App.PresenterService.Confirm.Show(confirmDelete).done(function () {
emt.IsProcessing = true;
Page.HttpService.HttpDelete("UserSavedFilter", "Delete", { primaryKeys: [model.filter.Name] }).done(function (result) {
if (result.IsSuccess) {
if (Page.FilterView.Title == model.filter.Title) {
Page.FilterView.Title = null;
Page.FilterView.IsNew = true;
}
Page.SavedFilters.remove(model.filter);
}
}).always(function () {
emt.IsProcessing = false;
});
}).fail(function () {
emt.IsProcessing = false;
});
}
});
this.ApplySavedFilter = function (event, model, skip) {
if (event) {
if (event.target.className.indexOf("webui-edit") > 0 || event.target.className.indexOf("webui-ios-trash-outline") > 0) {
return;
}
}
if (!skip) {
var clone = JSON.parse(JSON.stringify(model.filter));
Page.UserDimensions = clone.Filter.Dimensions || [];
Page.UserMetrics = clone.Filter.Metrics || [];
if (clone.Filter.SystemFilter) {
Page.SystemFilter = Object.assign(Page.SystemFilter, clone.Filter.SystemFilter);
}
Page.SetPredefinedDateRange(null, { daterange: { Value: Page.SystemFilter.PredefinedDateRange } }, skip);
}
switch (Page.SystemFilter.PredefinedDateRange) {
case "Custom":
Page.CustomDateRange = Page.SystemFilter.PredefinedDateRange;
Page.SystemFilter.DateRangeText = Page.SystemFilter.CustomStartDate.toString("MMM dd, yyyy") + " - " + Page.SystemFilter.CustomEndDate.toString("MMM dd, yyyy");
break;
case "SelectedDate":
Page.CustomDateRange = Page.SystemFilter.PredefinedDateRange;
Page.SystemFilter.DateRangeText = Page.SystemFilter.CustomStartDate.toString("MMM dd, yyyy");
break;
default:
Page.SystemFilter.DateRangeText = Page.PredefinedDateRangeList.find(function (item) { return item.Value == Page.SystemFilter.PredefinedDateRange; }).Text;
break;
}
if (!Page.SystemFilter.Channel) Page.SystemFilter.Channel = null;
if (!Page.SystemFilter.Outlet) Page.SystemFilter.Outlet = "";
var selectedChannel = Page.ChannelList.find(function (item) { return item.Value == Page.SystemFilter.Channel; });
if (selectedChannel) Page.SystemFilter.ChannelText = selectedChannel.Text;
Page.ChangeOutlet(null, skip);
Page.ChangeChannelId(null, skip);
Page.ExecuteFilter(model.filter.Title, model.filter.Filter.Filters, model.filter.Filter.SearchText, false, skip);
};
this.ExecuteFilter = function (title, filters, search, isNew, skip) {
Page.FilterView.IsNew = isNew;
Page.FilterView.Title = title;
Page.FilterView.Count = 0;
Page.FilterView.Filter = {
SearchText: search,
Filters: filters,
Dimensions: Page.UserDimensions,
Metrics: Page.UserMetrics,
SystemFilter: Page.SystemFilter
};
if (search) {
Page.SearchText = "";
}
Page.ChangeView(Page.FilterView, skip);
}
this.ChangeView = function (view, skip) {
if (view != Page.SelectedView) {
Page.LastSelectedView = Page.SelectedView;
Page.SelectedView = view;
}
else if (Page.SelectedView != Page.FilterView) {
return;
}
if (Page.SelectedView.Filter) {
Page.UserFilters = [];
if (Page.SelectedView.Filter.SearchText && !Page.SearchText) {
Page.SearchText = Page.SelectedView.Filter.SearchText;
}
Page.UserFilters = ([]).concat(Page.SelectedView.Filter.Filters);
}
else {
Page.UserFilters = null;
}
Page.IsShowFilter = Page.SelectedView == Page.FilterView && Page.UserFilters.length > 0;
if (!skip)
Page.RefreshVisualization();
}
this.AddFilterCommand = new DelegateCommand({
Command: function (model, param) {
var displayValue = "";
if (Page.SelectedFilter.SelectionSource) {
var valueItem = Page.SelectedFilter.SelectionSource.find(function (item) { return item.Value.toString() == Page.NewFilter.Value; })
if (valueItem) {
displayValue = valueItem.Text;
}
}
this.IsProcessing = true;
var item = {
PropertyName: Page.NewFilter.PropertyName,
Operator: Page.NewFilter.Operator,
Value: Page.SelectedFilter.InputType == "DateTime" ? Page.NewFilter.DateValue : Page.NewFilter.Value,
DisplayValue: displayValue
};
if (!Array.isArray(Page.UserFilters))
Page.UserFilters = [];
if (Page.UserFilters.add(item)) {
Page.ExecuteFilter("", Page.UserFilters, Page.SearchText, true);
model.Page.NewFilter.PropertyName = null;
document.body.click();
}
},
CanExecuteCommand: function (model, param) {
return !Object.isEmptyValue(Page.NewFilter.PropertyName) && !Object.isEmptyValue(Page.NewFilter.Operator) && !Object.isEmptyValue(Page.SelectedFilter.InputType == "DateTime" ? Page.NewFilter.DateValue : Page.NewFilter.Value);
}
})
this.RemoveUserColumn = function (item, event) {
Page.FilterView.Title = "";
Page.FilterView.IsNew = true;
event.stopPropagation();
if ((Array.isArray(Page.UserDimensions) && Page.UserDimensions.remove(item)) || (Array.isArray(Page.UserMetrics) && Page.UserMetrics.remove(item)))
Page.RefreshVisualization();
return false;
}
this.SetCustomDateRange = function (event, model) {
Page.SystemFilter.PredefinedDateRange = Page.CustomDateRange;
Page.SystemFilter.DateRangeText = Page.SystemFilter.CustomStartDate.toString("MMM dd, yyyy") + (Page.CustomDateRange === "Custom" ? " - " + Page.SystemFilter.CustomEndDate.toString("MMM dd, yyyy") : "");
Page.RefreshVisualization();
document.body.click();
$("#DateFilter").collapse('hide');
}
this.StylePredefinedDateRange = function (model) {
if (model.daterange.Value == "Custom") {
var separator = document.createElement("li");
separator.setAttribute("role", "separator");
separator.className = "divider";
var el = this;
setTimeout(function () {
el.parentElement.insertBefore(separator, el);
}, 100);
}
}
this.SetPredefinedDateRange = function (event, model, skip) {
Page.FilterView.Title = "";
Page.FilterView.IsNew = true;
var now = new Date();
if (model.daterange.Value == "Custom") {
Page.ShowCustomDateRange = true;
Page.CustomDateRange = model.daterange.Value;
}
else if (model.daterange.Value == "SelectedDate") {
Page.ShowCustomDateRange = true;
Page.CustomDateRange = model.daterange.Value;
Page.SystemFilter.CustomEndDate = now;
}
else {
Page.ShowCustomDateRange = false;
Page.SystemFilter.CustomEndDate = now;
switch (model.daterange.Value) {
case "Today":
Page.SystemFilter.CustomStartDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
break;
case "Yesterday":
Page.SystemFilter.CustomStartDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 0, 0, 0, 0);
break;
case "ThisWeek":
Page.SystemFilter.CustomStartDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1, 0, 0, 0, 0);
break;
case "ThisMonth":
Page.SystemFilter.CustomStartDate = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0, 0);
break;
case "ThisYear":
Page.SystemFilter.CustomStartDate = new Date(now.getFullYear(), 0, 1, 0, 0, 0, 0);
break;
case "Last7Days":
Page.SystemFilter.CustomStartDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 6, 0, 0, 0, 0);
break;
case "Last30Days":
Page.SystemFilter.CustomStartDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 29, 0, 0, 0, 0);
break;
case "Last90Days":
Page.SystemFilter.CustomStartDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 89, 0, 0, 0, 0);
break;
case "LastMonth":
Page.SystemFilter.CustomStartDate = new Date(now.getFullYear(), now.getMonth() - 1, 1, 0, 0, 0, 0);
Page.SystemFilter.CustomEndDate = new Date(now.getFullYear(), now.getMonth(), 0, 0, 0, 0, 0);
break;
}
if (Page.SystemFilter.PredefinedDateRange != model.daterange.Value) {
Page.SystemFilter.PredefinedDateRange = model.daterange.Value;
Page.SystemFilter.DateRangeText = Page.PredefinedDateRangeList.find(function (item) { return item.Value == Page.SystemFilter.PredefinedDateRange; }).Text;
Page.ExecuteFilter("", Page.UserFilters, Page.SearchText, true, skip);
}
document.body.click();
$("#DateFilter").collapse('hide');
}
}
this.SetChannel = function (event, model, skip) {
Page.FilterView.Title = "";
Page.FilterView.IsNew = true;
if (Page.SystemFilter.Channel != model.channel.Value) {
if (Page.LastSelectedChannel != Page.SystemFilter.Channel) {
Page.SystemFilter.ChannelId = null;
}
Page.SystemFilter.Channel = model.channel.Value;
Page.SystemFilter.ChannelText = model.channel.Text;
if (Page.ChannelWithOutlets.indexOf(Page.SystemFilter.Channel) <= -1) {
Page.SystemFilter.Outlet = "";
}
else {
if (!Page.SystemFilter.Outlet) {
var defaultOutlet = Page.Outlets.find(function (item) { return item.Value == ""; });
if (!defaultOutlet) {
defaultOutlet = Page.Outlets[0];
}
if (defaultOutlet) {
Page.SelectedOutletText = defaultOutlet.Text;
Page.__temp = defaultOutlet.Text;
Page.SystemFilter.Outlet = defaultOutlet.Value;
//if (defaultOutlet.Value) {
// Page.SystemFilter.ChannelText += " - " + defaultOutlet.Text;
//}
}
}
else {
var outlet = Page.Outlets.find(function (it) { return it.Value == Page.SystemFilter.Outlet });
if (outlet) {
Page.SystemFilter.ChannelText += " - " + outlet.Text;
}
else {
Page.SystemFilter.ChannelText += " - INVALID OUTLET";
}
}
}
Page.ExecuteFilter("", Page.UserFilters, Page.SearchText, true, skip);
$("#ChannelFilter").collapse('hide');
}
}
this.ChangeOutlet = function (controlId, skip) {
if (Page.ChannelWithOutlets.indexOf(Page.SystemFilter.Channel) >= 0) {
if (typeof (skip) != "boolean")
skip = false;
if (typeof (Page.__temp) !== "undefined" && Page.__temp != Page.SelectedOutletText)
Page.ExecuteFilter("", Page.UserFilters, Page.SearchText, true, skip);
var cn = Page.ChannelList.find(function (item) { return item.Value == (Page.SystemFilter.Channel || null); });
Page.SystemFilter.ChannelText = cn ? cn.Text : "";
if (Page.SystemFilter.Outlet) {
var on = Page.Outlets.find(function (it) { return it.Value == Page.SystemFilter.Outlet });
if (on) {
Page.SystemFilter.ChannelText += " - " + on.Text;
}
}
Page.__temp = Page.SelectedOutletText;
$("#ChannelFilter").collapse('hide');
}
else {
Page.SystemFilter.Outlet = "";
}
}
this.OnChannelIdComboSelecting = function (webcombo, selectArguments) {
selectArguments.SearchText = webcombo.TextObj.value;
selectArguments.Channel = Page.SystemFilter.Channel;
}
this.ChangeChannelId = function (controlId, skip) {
if (Page.SystemFilter.Channel == "marketplace" || Page.SystemFilter.Channel == "food_delivery") {
if (typeof (skip) != "boolean")
skip = false;
if (typeof (Page.__temp) !== "undefined" && Page.__temp != Page.SelectedChannelIdText)
Page.ExecuteFilter("", Page.UserFilters, Page.SearchText, true, skip);
if (Page.SystemFilter.ChannelId)
Page.SystemFilter.ChannelText = Page.SelectedChannelIdText;
else {
Page.SystemFilter.ChannelText = Page.ChannelList.find(function (item) { return item.Value == Page.SystemFilter.Channel; }).Text;
}
Page.__temp = Page.SelectedOutletText;
$("#ChannelFilter").collapse('hide');
}
}
this.RefreshVisualization = function () {
if (Page.KeepSystemFilter)
CookieManager.Set("__reportSystemFilter_" + App.Model.StoreShortName, JSON.stringify(Page.SystemFilter));
if (this.IsSummary) {
this.RefreshSummaryData();
}
else {
//ALWAYS RESET SORT WHEN REFRESH
this.Grid.RootTable.SortedColumns.Clear();
this.Grid.RootTable.SortedColumns.UpdateChanges();
if (this.Grid.IsInProgress) {
this.Grid.XmlHttp.Abort();
this.Grid.IsInProgress = false;
}
this.Grid.RefreshAll();
}
}
this.SetBusy = function (isBusy) {
var a = document.getElementsByClassName("loading-center");
for (var i = 0; i < a.length; i++) {
a[i].style.display = isBusy ? "" : "none";
}
a = document.getElementsByClassName("grid-outerframe");
for (var i = 0; i < a.length; i++) {
a[i].setAttribute("isrefreshing", isBusy ? "true" : "false");
}
};
this.OnUnload = function () { };
// grid event
this.OnGridInitialize = function (controlId) {
this.Grid = ISGetObject(controlId);
var clientEvent = this.Grid.LayoutSettings.ClientSideEvents;
clientEvent.OnAfterResponseProcess = "Page.GridOnAfterResponseProcess;" + clientEvent.OnAfterResponseProcess;
clientEvent.OnBeforeRequest = "Page.GridOnBeforeRequest;" + clientEvent.OnBeforeRequest;
clientEvent.OnUnhandledError = "Page.GridOnUnhandledError;" + clientEvent.OnUnhandledError;
this.SetGridUserColumnAction();
};
this.SetGridUserColumnAction = function () {
var usercolumns = (this.UserDimensions || []).concat(this.UserMetrics || []);
var header = this.Grid.RootTable.GetElement(WG40.COLHEADER, WG40.HTMLTABLE);
for (var i = 0; i < header.rows[0].cells.length; i++) {
var cell = header.rows[0].cells[i];
var colname = cell.getAttribute("colname");
if (usercolumns.indexOf(colname) >= 0) {
var textNode = cell.firstChild;
textNode.style.overflow = "hidden";
var hiddenSpan = document.createElement("span");
hiddenSpan.className = "hide";
cell.insertBefore(hiddenSpan, textNode);
var rootContainer = document.createElement("div");
var container = document.createElement("div");
container.className = "table-layout";
container.style.tableLayout = "fixed";
rootContainer.appendChild(container);
var actionContainer = document.createElement("div");
actionContainer.style.textAlign = "right";
actionContainer.style.width = "22px";
var removeAction = document.createElement("a");
actionContainer.appendChild(removeAction);
removeAction.className = "btn icon-button xsmall pull-right user-column-remover";
removeAction.innerHTML = '';
removeAction.onmousedown = App.BindFunction(Page.RemoveUserColumn, Page, [colname]);
ISMaterialTheme.AddRipplesEffect(removeAction);
container.appendChild(textNode);
container.appendChild(actionContainer);
cell.appendChild(rootContainer);
}
}
};
this.GridOnBeforeRequest = function (id, action) {
if (Page.UserDimensions) Page.Grid.AddInput("UserDimensions", JSON.stringify(Page.UserDimensions));
if (Page.UserMetrics) Page.Grid.AddInput("UserMetrics", JSON.stringify(Page.UserMetrics));
if (Page.UserFilters) Page.Grid.AddInput("UserFilters", JSON.stringify(Page.UserFilters));
if (Page.SystemFilter) Page.Grid.AddInput("SystemFilter", JSON.stringify(Page.SystemFilter));
switch (action) {
case "Refresh":
case "RefreshAll":
this.SetBusy(true);
break;
case "Export":
var exportButton = Page.AppBarSecondaryActions.find(function (item) { return item.Name == "Export" });
exportButton.Command.IsProcessing = true;
break;
case "Print":
var exportButton = Page.AppBarSecondaryActions.find(function (item) { return item.Name == "Print" });
exportButton.Command.IsProcessing = true;
break;
}
return true;
}
this.GridOnAfterResponseProcess = function (id, action) {
switch (action) {
case "Refresh":
var header = this.Grid.RootTable.GetElement(WG40.COLHEADER, WG40.HTMLTABLE);
var cell = header.rows[0].cells[0];
WGUIEngine.ResizeColumn(Page.Grid.RootTable, cell, cell.style.width, 0);
this.SetBusy(false);
break;
case "RefreshAll":
setTimeout(function () {
wgDoResize(true, true);
Page.SetBusy(false);
}, 600);
this.SetGridUserColumnAction();
Page.AddFilterCommand.IsProcessing = false;
break;
case "Print":
var exportButton = Page.AppBarSecondaryActions.find(function (item) { return item.Name == "Print" });
exportButton.Command.IsProcessing = false;
break;
case "ColumnSort":
WGUIEngine.FitColumns(Page.Grid.RootTable);
break;
}
return true;
}
this.OnGridActionDispatched = function (controlId, action) {
if (action == "Export") {
var g = ISGetObject(controlId);
var xmlrp = g.XmlResp;
var status = ISXml.GetNodeText(xmlrp, "//status");
if (status == "Ok") {
var dest = ISXml.GetNodeText(xmlrp, "//outputFile");
var reportConfirm = App.PresenterService.Confirm.Show(new ConfirmOption({
Template: "Your report is generated successfully.
View report.
",
ShowCancel: false, OKText: "Close",
Type: "info"
}));
}
App.ReportConfirm = reportConfirm;
g.SetStatus1("", "ready", "CommonText/Ready");
g.SetIdle();
g.LastRequestObj = null;
g.TempLRO = null;
g.IsUnhandledError = false;
g.IsStatusLocked = false;
g.IsInProgress = false;
// default after response
var exportButton = Page.AppBarSecondaryActions.find(function (item) { return item.Name == "Export" });
exportButton.Command.IsProcessing = false;
return false;
}
return true;
}
this.GridOnUnhandledError = function (id, action) {
switch (action) {
case "RefreshAll":
Page.AddFilterCommand.IsProcessing = false;
break;
case "Export":
var exportButton = Page.AppBarSecondaryActions.find(function (item) { return item.Name == "Export" });
exportButton.Command.IsProcessing = false;
break;
case "Print":
var exportButton = Page.AppBarSecondaryActions.find(function (item) { return item.Name == "Print" });
exportButton.Command.IsProcessing = false;
break;
}
}
// chart event
this.OnChartInitialize = function (controlId) {
this.Chart = ISGetObject(controlId);
this.Chart.ChartInteractiveUI.ResponseTimeoutID = 1;
};
// button action
this.ExecuteExport = function (model, param) {
var command = this;
WGMenuEngine.ShowExportMenu(Page.Grid);
};
this.ExecutePrint = function (model, param) {
var cmd = this;
cmd.IsProcessing = true;
var reportFilter = "";
var printHtml = "";
if (Page.IsSummary) {
printHtml = document.getElementById("summary-container").outerHTML;
}
else {
var reportFitlerEl = document.getElementById("filter-container");
for (var i = 0; i < reportFitlerEl.children.length; i++) {
reportFilter += reportFitlerEl.children[i].innerText.trim() + ", ";
}
reportFilter = reportFilter.substring(0, reportFilter.length - 2);
printHtml = Page.Grid.FrameObj.outerHTML;
}
var reportName = Page.ReportTypes.find(function (item) { return item.Value == Page.SelectedReportType }).Text;
reportName = (App.Resources.GenericReportText).formatString(reportName);
var reportTitle = App.Model.StoreName + " - " + reportName;
var dateRange = Page.SystemFilter.CustomStartDate.toString("MMM dd, yyyy") + " - " + Page.SystemFilter.CustomEndDate.toString("MMM dd, yyyy");
var printFrame = document.createElement("iframe");
document.body.append(printFrame);
printFrame.onload = function () {
cmd.IsProcessing = false;
printFrame.contentWindow.print();
setTimeout(function () {
printFrame.parentElement.removeChild(printFrame);
});
};
printFrame.src = "about:blank";
printFrame.contentDocument.write('' + reportTitle + '');
printFrame.contentDocument.write('');
printFrame.contentDocument.write('');
printFrame.contentDocument.write('');
//printFrame.contentDocument.write('');
printFrame.contentDocument.write('');
printFrame.contentDocument.write("" + reportTitle + "
");
printFrame.contentDocument.write("");
printFrame.contentDocument.write("");
printFrame.contentDocument.write(printHtml);
printFrame.contentDocument.write('');
if (Page.IsSummary) {
var summaryTitle = printFrame.contentDocument.getElementById("summary-title");
if (summaryTitle)
summaryTitle.parentElement.removeChild(summaryTitle);
}
else {
var gridFrame = printFrame.contentDocument.getElementById(Page.Grid.Id + "_f");
var header = printFrame.contentDocument.getElementById("dvCH_" + Page.Grid.Id + "_");
var content = printFrame.contentDocument.getElementById("dvTB_" + Page.Grid.Id + "_");
var footer = printFrame.contentDocument.getElementById("dvCF_" + Page.Grid.Id + "_");
var status = printFrame.contentDocument.getElementById("dvStatus_" + Page.Grid.Id);
status.style.display = "none";
gridFrame.style.height = "auto";
header.appendChild(content.firstChild);
if (footer) {
header.appendChild(footer.firstChild);
footer.parentElement.removeChild(footer);
}
content.parentElement.removeChild(content);
}
printFrame.contentDocument.close(); // necessary for IE >= 10
printFrame.focus(); // necessary for IE >= 10
};
this.OnInitialize();
}
function EntityBase(options) {
this.__entityType = "EntityBase";
Object.defineProperty(this, "OnPropertyChanged", {
value: function (propertyName, oldValue, newValue) { },
writable: true,
enumerable: false,
configurable: true
});
ExtendableObject.call(this, options);
this.IsDirty = false;
this.__SetMethod("GetKeyValues", function () {
var primaryKeys = this.GetPrimaryKeys();
var result = [];
for (var i = 0; i < primaryKeys.length; i++) {
result.push(this[primaryKeys[i]]);
}
return result.length > 1 ? result : result[0];
});
this.__SetMethod("GetPrimaryKeys", function () {
var dbSet = this.__dbSet ? this.__dbSet : App.DataContext.DbSet(this.__entityType);
return dbSet.PrimaryKeys;
});
this.__SetMethod("IsPrimaryKeysMatch", function (primaryKeys) {
if (primaryKeys.length == 1) {
return this.GetKeyValues() == primaryKeys[this.GetPrimaryKeys()[0]];
} else {
var keys = this.GetPrimaryKeys();
for (var prop in keys) {
if (this[prop] != primaryKeys[prop])
return false;
}
return true;
}
});
this.__SetMethod("IsPropertyChanged", function (prop) {
if (this.__originalValues.hasOwnProperty(prop) && this.__originalValues[prop] != this[prop])
return true;
return false;
});
this.__SetMethod("GetOriginalValue", function (prop) {
if (this.IsPropertyChanged(prop)) {
return this.__originalValues[prop];
}
return null;
});
this.__SetMethod("SetProperty", function (prop) {
var entity = this;
var registerCollectionChange = function (arrayValue) {
if (!arrayValue.OnCollectionChange) {
arrayValue.OnCollectionChange = function (oldValue, value, result, array) {
if (!oldValue.itemEquals(array)) {
if (entity.__enableTrackChanges && prop != "IsDirty") {
var oldValueDefault = oldValue === "" || oldValue === undefined || oldValue === null ? [] : oldValue;
var valueDefault = array === "" || array === undefined || array === null ? [] : array;
if (oldValueDefault != valueDefault) {
if (!oldValueDefault.itemEquals(valueDefault)) {
if (!entity.__originalValues.hasOwnProperty(prop)) {
entity.__originalValues[prop] = ([]).concat(oldValueDefault);
}
else {
if (entity.__originalValues[prop].itemEquals(valueDefault)) {
delete entity.__originalValues[prop];
}
}
}
}
entity.IsDirty = Object.keys(entity.__originalValues).length > 0;
}
}
entity.OnPropertyChanged(prop, oldValue, array);
}
}
}
if (Array.isArray(this[prop])) {
if (!this[prop].OnCollectionChange) {
registerCollectionChange(this[prop]);
}
}
this.ModifyProperty(prop, function (oldValue, value) {
if (oldValue !== value) {
if (Array.isArray(value)) {
if (!value.OnCollectionChange) {
registerCollectionChange(this[prop]);
}
}
if (this.__enableTrackChanges && prop != "IsDirty") {
if (Array.isArray(oldValue) || Array.isArray(value)) {
var oldValueDefault = oldValue === "" || oldValue === undefined || oldValue === null ? [] : oldValue;
var valueDefault = value === "" || value === undefined || value === null ? [] : value;
if (this.__originalValues.hasOwnProperty(prop) && this.__originalValues[prop].itemEquals(valueDefault)) {
delete entity.__originalValues[prop];
}
}
else {
var oldValueDefault = oldValue === "" || oldValue === undefined || oldValue === null ? null : oldValue;
var valueDefault = value === "" || value === undefined || value === null ? null : value;
if (!Object.isEquals(oldValueDefault, valueDefault)) {
if (!this.__originalValues.hasOwnProperty(prop)) {
this.__originalValues[prop] = oldValueDefault;
}
else {
if (this.__originalValues[prop] == valueDefault) {
delete this.__originalValues[prop];
}
}
}
this.IsDirty = Object.keys(this.__originalValues).length > 0;
}
}
this.OnPropertyChanged(prop, oldValue, value);
}
});
});
this.__SetMethod("Initialize", function () {
for (var prop in this) {
var value = this[prop];
if (this.hasOwnProperty(prop) && typeof (value) != "function" && prop != "EntityAspect") {
this.SetProperty(prop);
}
}
Object.defineProperty(this, "IsDirty", {
enumerable: false,
});
Object.defineProperty(this, "__originalValues", {
value: {},
enumerable: false,
configurable: true,
writable: true
});
Object.defineProperty(this, "IsNew", {
get: function () {
return this.EntityAspect && this.EntityAspect.EntityState == App.DataContext.EntityState.Added;
},
enumerable: false,
configurable: true
});
Object.defineProperty(this, "__entityType", {
value: this.__entityType,
enumerable: false,
configurable: true,
writable: true
});
Object.defineProperty(this, "__enableTrackChanges", {
value: false,
enumerable: false,
configurable: true,
writable: true
});
Object.defineProperty(this, "__dbSet", {
value: null,
enumerable: false,
configurable: true,
writable: true
});
Object.defineProperty(this, "__stash", {
value: {},
enumerable: false,
configurable: true,
writable: true
});
Object.defineProperty(this, "__validators", {
value: {},
enumerable: false,
configurable: true,
writable: true
});
Object.defineProperty(this, "ValidationResult", {
value: null,
enumerable: false,
configurable: true,
writable: true
});
});
this.__SetMethod("BeginTrack", function () {
this.__enableTrackChanges = true;
});
this.__SetMethod("StopTrack", function () {
this.__enableTrackChanges = false;
});
this.__SetMethod("AcceptPropertyChanges", function (props) {
if (typeof (props) == "string") {
props = props.split(",");
}
if (!props) {
props = Object.keys(this.__originalValues);
}
if (!Array.isArray(props))
return false;
var entity = this;
props.each(function (prop) {
if (entity.ValidationResult)
entity.ValidationResult[prop] = null;
if (entity.__originalValues)
delete entity.__originalValues[prop];
});
this.IsDirty = Object.keys(this.__originalValues).length > 0;
});
this.__SetMethod("AcceptChanges", function (isAll) {
if (isAll === true) {
this.AcceptAllChanges();
}
else if (typeof (isAll) !== "undefined") {
this.AcceptPropertyChanges(isAll);
}
else {
this.ValidationResult = null;
this.__originalValues = {};
this.IsDirty = false;
if (this.__dbSet) {
if (this.EntityAspect.EntityState == DataContext.prototype.EntityState.Deleted) {
this.__dbSet.Delete(this);
}
else {
this.__dbSet.Context.SetUnchanged(this);
}
}
}
});
this.__SetMethod("AcceptAllChanges", function () {
var entityList = [];
var acceptChanges = function (entity, entityList) {
if (!entity.Is)
return;
entity.AcceptChanges();
entityList.push(entity);
for (var prop in entity) {
var value = entity[prop];
if (typeof (value) == "function") {
continue;
}
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
if (typeof (value[i]) == "object" && value[i] != null && value[i].EntityAspect) {
if (entityList.indexOf(value[i]) < 0) {
acceptChanges(value[i], entityList);
}
}
}
}
else if (typeof (value) == "object" && value != null && value.EntityAspect) {
if (entityList.indexOf(value) < 0) {
acceptChanges(value, entityList);
}
}
}
};
acceptChanges(this, entityList);
this.IsDirty = false;
});
this.__SetMethod("ResetChanges", function () {
for (var prop in this.__originalValues) {
this[prop] = this.__originalValues[prop];
}
this.IsDirty = false;
});
this.__SetMethod("Reset", function (prop) {
if (typeof (prop) != "string") {
this.ResetChanges();
}
else if (this.__originalValues.hasOwnProperty(prop)) {
this[prop] = this.__originalValues[prop];
delete this.__originalValues[prop];
this.IsDirty = Object.keys(this.__originalValues).length > 0;
}
});
this.__SetMethod("GetAllChangedProperties", function () {
var result = [];
for (var prop in this.__originalValues) {
result.push(prop);
}
return result;
});
this.__SetMethod("StashChanges", function (props, stashName) {
if (!stashName) {
stashName = "default";
}
if (!props) {
props = Object.keys(this);
}
else if (!Array.isArray(props)) {
props = [props];
}
for (var i = 0; i < props.length; i++) {
var prop = props[i];
var value = this[prop];
if (!this.__stash[stashName]) {
this.__stash[stashName] = {};
}
this.__stash[stashName][prop] = Array.isArray(value) ? ([]).concat(value) : value;
}
});
this.__SetMethod("ApplyStash", function (props, stashName) {
if (!stashName) {
stashName = "default";
}
if (!props) {
if (this.__stash[stashName])
props = Object.keys(this.__stash[stashName]);
else
props = []
}
else if (!Array.isArray(props)) {
props = [props];
}
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (this.__stash.hasOwnProperty(stashName) && this.__stash[stashName].hasOwnProperty(prop)) {
var value = this.__stash[stashName][prop];
if (Array.isArray(value)) {
var context = null;
if (this.__dbSet)
context = this.__dbSet.Context;
else if (App.DataContext)
context = App.DataContext;
if (context)
context.RevertDeleted(value);
}
this[prop] = value;
}
}
});
this.__SetMethod("HasStash", function (stashName) {
if (!stashName) {
stashName = "default";
}
return this.__stash.hasOwnProperty(stashName);
});
this.__SetMethod("RemoveStash", function (props, stashName) {
if (!stashName) {
stashName = "default";
}
if (props === true) {
delete this.__stash[stashName];
}
else if (props) {
if (!Array.isArray(props)) {
props = [props];
}
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (this.__stash.hasOwnProperty(stashName)) {
delete this.__stash[stashName][prop];
}
}
}
});
this.__SetMethod("UpdateData", function (data) {
for (var prop in data) {
if (prop == "EntityAspect" || this.GetPrimaryKeys().indexOf(prop) >= 0) {
continue;
}
if (!this.hasOwnProperty(prop) && typeof (data[prop]) != "function") {
this.SetProperty(prop);
}
if (Array.isArray(data[prop])) {
if (!this[prop]) {
this[prop] = [];
}
if (!Array.isArray(this[prop])) {
continue;
}
for (var i = 0, length = data[prop].length; i < length; i++) {
var value = data[prop][i];
if (value && typeof (value) == "object" && !Date.IsDate(value)) {
var dbSet = this[prop][i] && this[prop][i].__dbSet ? this[prop][i].__dbSet : App.DataContext.DbSet(App.DataContext.GetTypeName(prop));
var existing = dbSet.Find(value);
if (!existing) {
var clone = JSON.parse(JSON.stringify(value));
existing = App.DataContext.ParseEntity(clone, dbSet.EntityType);
}
existing.UpdateData(value);
}
else {
this[prop][i] = value;
}
}
}
else if (this.__dbSet.NavigationProperties.indexOf(prop) >= 0) {
if (data[prop] && typeof (data[prop]) == "object" && !Date.IsDate(value)) {
var dbSet = this[prop] && this[prop].__dbSet ? this[prop].__dbSet : App.DataContext.DbSet(App.DataContext.GetTypeName(prop));
var existing = dbSet.Find(data[prop]);
if (!existing) {
var clone = JSON.parse(JSON.stringify(data[prop]));
existing = App.DataContext.ParseEntity(clone, dbSet.EntityType);
if (this.__dbSet && this.__dbSet.NavigationProperties.indexOf(prop) >= 0) {
this.SyncNavigationProp(prop);
}
}
existing.UpdateData(data[prop]);
}
}
else {
this[prop] = data[prop];
}
}
});
this.__SetMethod("ModifyProperty", function (propName, setterFn, getterFn) {
var desc = Object.getOwnPropertyDescriptor(this, propName);
var oldSet = desc ? desc.set : undefined;
var oldGet = desc ? desc.get : undefined;
var tempValue = desc ? desc.value : undefined;
Object.defineProperty(this, propName, {
get: function () {
if (typeof (getterFn) == "function") getterFn.apply(this, arguments);
if (typeof (oldGet) == "function")
return oldGet.apply(this, arguments);
else
return tempValue;
},
set: function (value) {
var oldValue = this[propName];
if (typeof (oldSet) == "function")
oldSet.apply(this, arguments);
else
tempValue = value;
if (typeof (setterFn) == "function") {
setterFn.call(this, oldValue, value);
}
},
enumerable: true,
configurable: true
});
});
this.__SetMethod("Is", function (entityType) {
return this.__entityType == entityType;
});
this.__SetMethod("Clone", function (option, isAutoRegister) {
var clone = {};
for (var prop in this) {
var value = this[prop];
if (typeof (value) != "function" && value != null && !value.Is && prop != "EntityAspect" && !Array.isArray(value))
clone[prop] = value;
}
if (option) {
for (var prop in option) {
var value = option[prop];
clone[prop] = Array.isArray(value) ? ([]).concat(value) : value;
}
}
var result = this.__dbSet.New(clone, isAutoRegister);
// result.AcceptChanges(); considered unsafe, reason is clone method is expected to use Added state.
return result;
});
this.__SetMethod("Copy", function (option) {
var exclude = ([]).concat(this.__dbSet.NavigationProperties);
for (var i = 0, length = exclude.length; i < length; i++) {
exclude.push(exclude[i] + "Id");
}
exclude = exclude.concat(this.__dbSet.ComputedProperties);
exclude = exclude.concat(this.__dbSet.PrimaryKeys);
exclude.push("EntityAspect");
for (var prop in option) {
if (exclude.indexOf(prop) < 0 && ((typeof (option[prop]) != "object" || option[prop] == null) && (typeof (this[prop]) != "object" || this[prop] == null))) {
this[prop] = option[prop];
}
}
for (var i = 0; i < this.__dbSet.ComputedProperties.length; i++) {
App.BindingService.TriggerChange(this, this.__dbSet.ComputedProperties[i]);
}
});
this.__SetMethod("SyncNavigationProp", function (props) {
if (this.__dbSet) {
this.__dbSet.SyncNavigationProp(this, props);
}
});
// validation
this.__SetMethod("RegisterValidators", function (validators) {
for (var i = 0; i < validators.length; i++) {
var validator = validators[i];
if (window[validator.ValidatorType]) {
var validatorObject = new window[validator.ValidatorType](validator.Validator);
validatorObject.MemberName = validator.MemberName;
this.AddValidator(validatorObject);
}
}
});
this.__SetMethod("AddValidator", function (validator) {
if (!this.__validators[validator.MemberName]) {
this.__validators[validator.MemberName] = [];
}
var canRegister = true;
if (validator.constructor.name != "ClientValidator" && validator.constructor.name != "CustomValidator") {
canRegister = !(this.__validators[validator.MemberName].find(function (item) { return item.constructor == validator.constructor }));
}
if (canRegister)
this.__validators[validator.MemberName].push(validator);
});
this.__SetMethod("Validate", function (props) {
if (props && typeof (props) == "string") {
props = props.split(/\s*,\s*/);
}
var dbSet = this.__dbSet ? this.__dbSet : App.DataContext.DbSet(this.__entityType);
this.ValidationResult = dbSet.GetValidationResult(this, props);
if (this.ValidationResult)
return this.ValidationResult.IsSuccess;
return true;
});
this.__SetMethod("RemoveValidationState", function (props) {
if (!props || !this.ValidationResult)
return false;
if (typeof (props) == "string") {
props = props.split(/\s*,\s*/);
}
var pass = false;
for (var i = 0; i < props.length; i++) {
if (this.ValidationResult && typeof (this.ValidationResult) == "object" && this.ValidationResult.hasOwnProperty(props[i])) {
this.ValidationResult[props[i]] = null;
delete this.ValidationResult[props[i]];
pass = true;
}
}
if (pass) {
var isValidateSuccess = true;
for (var key in this.ValidationResult) {
if (key != "IsSuccess" && this.ValidationResult[key] && this.ValidationResult[key].hasOwnProperty("IsSuccess"))
isValidateSuccess = isValidateSuccess && this.ValidationResult[key].IsSuccess;
}
this.ValidationResult.IsSuccess = isValidateSuccess;
}
return true;
});
this.__SetMethod("GetPropertyValidators", function (prop) {
var result = [];
if (!prop) {
return result;
}
var dbSet = this.__dbSet ? this.__dbSet : App.DataContext.DbSet(this.__entityType);
if (dbSet.Validators[prop]) {
result = result.concat(dbSet.Validators[prop]);
}
if (this.__validators[prop]) {
result = result.concat(this.__validators[prop]);
}
return result;
});
this.Initialize();
}
function DataSet(options) {
this.EntityType = "EntityBase";
this.PrimaryKeys = [this.EntityType + "Id"];
this.Context = null;
ExtendableObject.call(this, options);
this.NavigationProperties = [];
this.ComputedProperties = {};
this.Data = [];
this.DataDictionary = {};
this.Find = function (object) {
return this.DataDictionary[this.GeneratePrimaryKeys(object)] || null;
};
this.Attach = function (entity, force, enableCheckId) {
enableCheckId = typeof (enableCheckId) != "undefined" ? enableCheckId : true;
entity.__dbSet = this;
if ((entity.Is && entity.Is(this.EntityType) || force) && this.Data.indexOf(entity) < 0) {
var pass = true;
for (var _i = 0; _i < this.PrimaryKeys.length; _i++) {
var key = this.PrimaryKeys[_i];
if (!entity[key] || entity[key] == "00000000-0000-0000-0000-000000000000") {
pass = false;
entity[key] = this.GetNewId();
}
}
if (enableCheckId && pass) {
var existingEntity = this.Find(entity);
if (existingEntity) {
return existingEntity;
}
}
if (this.Context) {
if (!entity.EntityAspect) {
this.Context.SetUnchanged(entity);
}
else if (entity.EntityAspect.EntityState == this.Context.EntityState.Added) {
this.Context.SetAdd(entity);
}
}
if (this.Context && (!entity.EntityAspect || !entity.EntityAspect.EntityState))
this.Context.SetUnchanged(entity);
this.SyncNavigationProp(entity);
this.Data.push(entity);
this.DataDictionary[this.GeneratePrimaryKeys(entity)] = entity;
return entity;
}
}
this.GeneratePrimaryKeys = function (object) {
var keyValues = [];
if (Array.isArray(object)) {
keyValues = object;
}
else if (typeof (object) == "object") {
for (var _i = 0; _i < this.PrimaryKeys.length; _i++) {
var key = this.PrimaryKeys[_i];
keyValues.push(object[key]);
}
}
else {
keyValues = [object];
}
return keyValues.join("|");
};
this.New = function (options, IsAutoRegister) {
options = options ? options : {};
var result = {};
var firstData = this.Data[0];
if (firstData) {
for (var prop in firstData) {
if (!options.hasOwnProperty(prop) && typeof (firstData[prop]) != "function" && prop != "__type")
result[prop] = Array.isArray(firstData[prop]) ? [] : null;
}
}
else if (typeof result.IsDeleted === "undefined") {
result.IsDeleted = false;
}
for (var prop in options) {
if (typeof (options[prop]) != "function" && prop != "EntityAspect")
result[prop] = options[prop];
}
// don't regenerate primary key if it's exist and unique.
var generateNewKey = true;
var isEntityHasKeys = true;
this.PrimaryKeys.each(function (key) {
if (!result[key]) {
isEntityHasKeys = false;
return false;
}
});
if (isEntityHasKeys) {
generateNewKey = this.Find(result) != null;
}
if (generateNewKey) {
for (var _i = 0; _i < this.PrimaryKeys.length; _i++) {
var key = this.PrimaryKeys[_i];
result[key] = this.GetNewId();
}
}
result.EntityAspect = {
EntityState: this.Context.EntityState.Added
}
result = this.Context.ParseEntity(result, this.EntityType, IsAutoRegister);
return result;
};
this.Delete = function (entities) {
if (!Array.isArray(entities)) {
entities = [entities];
}
for (var _i = 0; _i < entities.length; _i++) {
var entity = entities[_i];
var index = null;
if ((index = this.Data.indexOf(entity)) >= 0) {
this.Data.splice(index, 1);
this.DataDictionary[this.GeneratePrimaryKeys(entity)] = undefined;
}
for (var i = 0; i < this.NavigationProperties.length; i++) {
var navProp = this.NavigationProperties[i];
var targetObj = entity[navProp];
if (targetObj) {
var scalarNavProp = this.EntityType;
var listNavProp = this.EntityType.replace(/([xs])$/, "$1es").replace(/y$/, "ies").replace(/([^s])$/, "$1s");
if (targetObj.hasOwnProperty(scalarNavProp)) {
for (var j = 0; j < this.PrimaryKeys.length; j++) {
var key = this.PrimaryKeys[j];
if (targetObj[scalarNavProp][key] == entity[key]) {
targetObj[scalarNavProp][key] = null;
targetObj.AcceptPropertyChanges(scalarNavProp);
}
}
}
else if (targetObj.hasOwnProperty(listNavProp)) {
if (Array.isArray(targetObj[listNavProp]) && (index = targetObj[listNavProp].indexOf(entity)) >= 0) {
targetObj[listNavProp].splice(index, 1);
targetObj.AcceptPropertyChanges(listNavProp);
}
}
}
}
}
};
this.RegisterNavProp = function (targetProp) {
if (this.NavigationProperties.indexOf(targetProp) < 0)
this.NavigationProperties.push(targetProp);
};
this.RegisterComProp = function (prop, fn) {
this.ComputedProperties[prop] = fn;
var dbset = this;
this.Data.each(function (item) {
dbset.SetComputedProperty(item, prop, fn);
});
};
this.SetComputedProperty = function (entity, prop, fn) {
Object.defineProperty(entity, prop, {
get: fn,
enumerable: false,
configurable: true
});
}
this.ApplyComputedProperties = function (entity) {
for (var comProp in this.ComputedProperties) {
this.SetComputedProperty(entity, comProp, this.ComputedProperties[comProp]);
}
}
this.SetNavigationProperty = function (entity, prop) {
var value = entity[prop];
var dataSource = value && value.Is ? this.Context.DbSet(value.__entityType) : this.Context.DbSet(this.Context.GetTypeName(prop));
var keyProp = dataSource.PrimaryKeys[0];
if (dataSource.PrimaryKeys.length > 1 && dataSource.PrimaryKeys.indexOf(prop + "Id") > 0) {
keyProp = prop + "Id";
}
var entityKeyProp = prop + "Id";
if (entity.hasOwnProperty(keyProp) && !entity.hasOwnProperty(entityKeyProp)) {
entityKeyProp = keyProp;
}
var targetProp = prop;
var scalarNavProp = entity.__entityType;
var listNavProp = entity.__entityType.replace(/([xs])$/, "$1es").replace(/y$/, "ies").replace(/([^s])$/, "$1s");
entity.ModifyProperty(
entityKeyProp,
function (oldValue, value) {
if (this.__dbSet && this.__dbSet.Context && !this.__dbSet.Context.EnableAutoRelationMap) {
return;
}
if (dataSource && value != oldValue && Array.isArray(dataSource.Data)) {
if (this[targetProp] && this.__dbSet) {
if (this[targetProp].hasOwnProperty(listNavProp)) {
if (Array.isArray(this[targetProp][listNavProp])) {
this[targetProp][listNavProp].remove(this);
this[targetProp].AcceptPropertyChanges(listNavProp);
}
}
else if (this[targetProp].hasOwnProperty(scalarNavProp)) {
if (this[targetProp][scalarNavProp] == this) {
this[targetProp][scalarNavProp] = null;
this[targetProp].AcceptPropertyChanges(scalarNavProp);
}
}
}
this[targetProp] = null;
}
if (this[targetProp] == null) {
var data = value ? dataSource.Find(value) : null;
this[targetProp] = data;
}
if (this[targetProp] && this.__dbSet && this.__dbSet.Find(this.GetKeyValues())) {
if (this[targetProp].hasOwnProperty(listNavProp)) {
if (!Array.isArray(this[targetProp][listNavProp]) && !this[targetProp][listNavProp]) {
this[targetProp][listNavProp] = [];
this[targetProp].AcceptPropertyChanges(listNavProp);
}
if (Array.isArray(this[targetProp][listNavProp]) && this[targetProp][listNavProp].indexOf(this) < 0) {
this[targetProp][listNavProp].add(this);
this[targetProp].AcceptPropertyChanges(listNavProp);
}
}
else if (this[targetProp].hasOwnProperty(scalarNavProp)) {
this[targetProp][scalarNavProp] = this;
this[targetProp].AcceptPropertyChanges(scalarNavProp);
}
}
}
);
};
this.ApplyNavigationProperties = function (entity) {
for (var i = 0; i < this.NavigationProperties.length; i++) {
var navProp = this.NavigationProperties[i];
this.SetNavigationProperty(entity, navProp);
}
}
this.SyncNavigationProp = function (entity, navProps) {
if (!Array.isArray(navProps)) {
navProps = this.NavigationProperties;
}
for (var i = 0; i < navProps.length; i++) {
var navProp = navProps[i];
var value = entity[navProp];
var targetKey = navProp + "Id";
var keys = value ? this.Context.DbSet(value.__entityType).PrimaryKeys : this.Context.DbSet(this.Context.GetTypeName(navProp)).PrimaryKeys;
var valueTargetKey = keys[0];
if (keys.length > 1 && keys.indexOf(targetKey) > 0) {
valueTargetKey = targetKey;
}
if (entity.hasOwnProperty(valueTargetKey) && !entity.hasOwnProperty(targetKey)) {
targetKey = valueTargetKey;
}
var keyValue = value ? value[valueTargetKey] : entity[targetKey];
if (keyValue) {
entity[targetKey] = keyValue;
}
}
}
this.GetNewId = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
this.Validators = {};
this.AddValidator = function (validator) {
if (!this.Validators[validator.MemberName]) {
this.Validators[validator.MemberName] = [];
}
var canRegister = true;
if (validator.constructor.name != "ClientValidator" && validator.constructor.name != "CustomValidator") {
canRegister = !(this.Validators[validator.MemberName].find(function (item) { return item.constructor == validator.constructor }));
}
if (canRegister)
this.Validators[validator.MemberName].push(validator);
}
this.RemoveValidator = function (validator) {
var mvalidators = this.Validators[validator.MemberName];
if (!mvalidators) {
return;
}
var exitingValidator;
if (validator.constructor.name == "ClientValidator") {
exitingValidator = (mvalidators.find(function (item) { return item.constructor.name == validator.constructor.name && item.ClientValidate == validator.ClientValidate }));
}
else if (validator.constructor.name == "CustomValidator") {
exitingValidator = (mvalidators.find(function (item) { return item.constructor.name == validator.constructor.name && (item.IsValid + "") == (validator.IsValid + "") }));
}
else {
exitingValidator = (mvalidators.find(function (item) { return item.constructor.name == validator.constructor.name }));
}
if (exitingValidator) {
mvalidators.remove(exitingValidator);
}
}
this.GetValidationResult = function (entity, props) {
var result = new ValidationResultInfo();
if (!entity.Is(this.EntityType))
return result;
for (var memberName in entity.__validators) {
if (props && props.indexOf(memberName) < 0) {
continue;
}
for (var i = 0; i < entity.__validators[memberName].length; i++) {
var validator = entity.__validators[memberName][i];
if (result[memberName] && !result[memberName].IsSuccess) {
continue;
}
if (entity.hasOwnProperty(memberName))
result.AddValidationResult(memberName, validator.Validate(entity));
}
}
if (!entity.EntityAspect || entity.EntityAspect.EntityState == this.Context.Detached || entity.EntityAspect.EntityState == this.Context.Unchanged)
return result;
if (props && typeof (props) == "string") {
props = props.split(/\s*,\s*/);
}
for (var memberName in this.Validators) {
if (props && props.indexOf(memberName) < 0) {
continue;
}
for (var i = 0; i < this.Validators[memberName].length; i++) {
var validator = this.Validators[memberName][i];
if (result[memberName] && !result[memberName].IsSuccess) {
continue;
}
if (entity.hasOwnProperty(memberName))
result.AddValidationResult(memberName, validator.Validate(entity));
}
}
return result;
}
}
function DataContext(options) {
this.EnableTrackChanges = true;
this.EnableAutoRelationMap = true;
this.GetDefaultOption = function () {
return {};
};
ExtendableObject.call(this, options);
this.HasDirtyEntity = false;
this.DirtyEntityCount = 0;
this.SkipDeleted = true;
this.Clone = function (source) {
if (source)
return JSON.parse(JSON.stringify(source));
return {};
};
this.GetTypeName = function (prop) {
if (prop[prop.length - 1] == "s") {
prop = prop.replace(/ies$/, "y").replace(/([xs])es$/, "$1").replace(/([^s])s$/, "$1").replace(/1e$/, "");
}
return prop;
};
this.SetSubDbSet = function (sub, base) {
this[sub] = this.DbSet(base);
};
this.ParseEntities = function (entities, entityType, IsAutoRegister) {
return this.ParseEntity(entities, entityType, IsAutoRegister);
};
this.ParseEntity = function (entities, entityType, IsAutoRegister) {
if (Array.isArray(entities)) {
for (var i = 0; i < entities.length; i++) {
entities[i] = this.ParseEntityOnly(entities[i], entityType, IsAutoRegister);
}
this.ParseEntityChild(entities, IsAutoRegister);
}
else {
entities = this.ParseEntityOnly(entities, entityType, IsAutoRegister);
this.ParseEntityChild([entities], IsAutoRegister);
}
return entities;
}
this.ParseEntityOnly = function (entity, entityType, IsAutoRegister) {
IsAutoRegister = typeof (IsAutoRegister) == "undefined" ? true : IsAutoRegister;
var dbSet = this.DbSet(entityType);
if (entity.Is)
return entity
var findedEntity = null;
if ((findedEntity = dbSet.Find(entity)) != null) {
//findedEntity.UpdateData(entity);
return findedEntity;
}
var options = this.GetDefaultOption();
options.__entityType = dbSet.EntityType;
EntityBase.call(entity, options);
if (IsAutoRegister) {
this.RegisterEntity(entity, entityType);
}
return entity;
}
this.ParseEntityChild = function (entities, IsAutoRegister) {
IsAutoRegister = typeof (IsAutoRegister) == "undefined" ? true : IsAutoRegister;
var temp = [];
for (var _i = 0; _i < entities.length; _i++) {
var entity = entities[_i];
if (!entity.Is)
continue;
var dbSet = this.DbSet(entity.__entityType);
for (var prop in entity) {
var value = entity[prop];
if (!entity.hasOwnProperty(prop) || typeof (value) == "function" || prop == "EntityAspect") {
continue;
}
var entityType = this.GetTypeName(prop);
var isNavigationProperty = typeof (value) == "object" && !Array.isArray(value) && (value != null && value.Is && value.Is(entityType) || (entity.hasOwnProperty(entityType + "Id") || value && value.hasOwnProperty(entity.__entityType + "Id")) || !!App.DataContext[entityType]);
var isEntity = isNavigationProperty || Array.isArray(value) || (typeof (value) == "object" && value != null && !Date.IsDate(value));
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
if (typeof (value[i]) == "object" && value[i].IsDeleted && this.SkipDeleted) {
value.remove(value[i]);
i--;
}
else if (isEntity && typeof (value[i]) == "object" && value[i] != null && !value[i].Is) {
var old = value[i];
if (old.hasOwnProperty(entity.__entityType + "Id") && !old.hasOwnProperty(entity.__entityType)) {
old[entity.__entityType] = null;
}
value[i] = this.ParseEntityOnly(value[i], entityType, IsAutoRegister);
if (old == value[i])
temp.push(value[i]);
}
}
}
else {
if (isEntity) {
if (value != null && !value.Is) {
if (value.IsDeleted && this.SkipDeleted) {
entity[prop] = null;
}
else {
var old = value;
entity[prop] = this.ParseEntityOnly(value, entityType, IsAutoRegister);
if (old == entity[prop])
temp.push(value);
}
}
}
}
if (isNavigationProperty) {
dbSet.RegisterNavProp(prop);
}
}
dbSet.ApplyNavigationProperties(entity);
dbSet.ApplyComputedProperties(entity);
if (this.EnableTrackChanges) {
setTimeout(function (entity) { entity.BeginTrack(); }, 100, entity);
}
}
if (temp.length > 0)
this.ParseEntityChild(temp);
// sync navigation property after all entities have been registered
var dataContext = this;
entities.each(function (entity) {
if (entity.Is) {
var dbSet = dataContext.DbSet(entity.__entityType);
dbSet.SyncNavigationProp(entity);
}
});
}
this.ParseEntityTree = function (entity, entityType, IsNotAutoRegister) {
var dbSet = this.DbSet(entityType);
if (entity.Is)
return entity;
var findedEntity = null;
if ((findedEntity = dbSet.Find(entity)) != null) {
return findedEntity;
}
var options = this.GetDefaultOption();
options.__entityType = entityType;
EntityBase.call(entity, options);
if (!IsNotAutoRegister) {
this.RegisterEntity(entity, entityType);
}
for (var prop in entity) {
var value = entity[prop];
if (!entity.hasOwnProperty(prop) || typeof (value) == "function" || prop == "EntityAspect") {
continue;
}
var entityType = this.GetTypeName(prop);
var isNavigationProperty = typeof (value) == "object" && (value != null && value.Is && value.Is(entityType) || entity.hasOwnProperty(entityType + "Id") && !Array.isArray(value));
var isEntity = isNavigationProperty || Array.isArray(value);
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
if (isEntity) {
value[i] = this.ParseEntity(value[i], entityType, IsNotAutoRegister);
}
}
}
else {
if (isEntity) {
if (value != null) {
value = this.ParseEntity(value, entityType, IsNotAutoRegister);
}
}
}
if (isNavigationProperty) {
dbSet.RegisterNavProp(prop);
}
}
dbSet.ApplyNavigationProperties(entity);
dbSet.SyncNavigationProp(entity);
if (this.EnableTrackChanges) {
entity.BeginTrack();
}
return entity;
};
this.RegisterEntity = function (entity, entityType) {
if (Array.isArray(entity) && entity.length <= 0 && !entityType)
return;
entityType = entityType ? entityType : Array.isArray(entity) ? entity[0].__entityType : entity.__entityType;
if (!this[entityType]) {
this.CreateDbSet(entityType, [entityType + "Id"]);
}
if (Array.isArray(entity)) {
for (var i = 0; i < entity.length; i++) {
this.RegisterEntity(entity[i], entityType);
}
}
else {
this[entityType].Attach(entity, true);
}
};
this.GetEntityById = function (id, entityType) {
if (!this[entityType] || !(this[entityType] instanceof DataSet)) {
return false;
}
this[entityType].Find(id);
};
this.DbSet = function (entityType) {
if (!this[entityType]) {
this.CreateDbSet(entityType, [entityType + "Id"]);
}
return this[entityType];
};
this.CreateDbSet = function (entityType, primaryKeys) {
var option = {
EntityType: entityType,
PrimaryKeys: primaryKeys,
Context: this
};
this[entityType] = new DataSet(option);
}
this.GetCleanEntity = function (entity, filters) {
var entityList = [];
var include = null;
if (Array.isArray(filters)) {
include = {};
for (var i = 0; i < filters.length; i++) {
var pathes = filters[i].split(".");
var obj = include;
for (var _i = 0; _i < pathes.length; _i++) {
var path = pathes[_i];
if (!obj.hasOwnProperty(path)) {
obj[path] = {};
}
obj = obj[path];
}
}
}
var cleanEntities = function (cleanModels, entityList) {
var nextCleanModels = [];
cleanModels.each(function (cleanModel) {
var entity = cleanModel.entity;
var data = cleanModel.data;
var includeList = cleanModel.includeList;
for (var prop in entity) {
var value = entity[prop];
if (typeof (value) == "function" || prop == "ValidationResult") {
continue;
}
if (prop == "EntityAspect") {
data[prop] = {
EntityState: value.EntityState == App.DataContext.EntityState.Unchanged ? App.DataContext.EntityState.Detached : value.EntityState
}
}
else if (Array.isArray(value) || (typeof (value) == "object" && value != null && !Date.IsDate(value))) {
if (includeList && !includeList.hasOwnProperty(prop)) {
continue;
}
if (Array.isArray(value)) {
data[prop] = [];
for (var i = 0; i < value.length; i++) {
if (typeof (value[i]) == "object" && value[i] != null && value[i].Is) {
if (entityList.indexOf(value[i]) < 0) {
var newEn = {};
entityList.push(value[i]);
nextCleanModels.push({ data: newEn, entity: value[i], includeList: includeList ? includeList[prop] : null });
data[prop].push(newEn);
}
}
else {
data[prop].push(value[i]);
}
}
}
else {
if (entityList.indexOf(value) < 0) {
var newEn = {};
entityList.push(value);
nextCleanModels.push({ data: newEn, entity: value, includeList: includeList ? includeList[prop] : null });
data[prop] = newEn;
}
}
}
else if (value == null) {
data[prop] = "NULL";
} else {
data[prop] = value;
}
}
})
if (nextCleanModels.length > 0) {
cleanEntities.call(this, nextCleanModels, entityList);
}
};
var cleanEntity = function (entity, entityList, includeList) {
var data = {};
entityList.push(entity);
cleanEntities.call(this, [{ data: data, entity: entity, includeList: includeList }], entityList);
return data;
}
return cleanEntity.call(this, entity, entityList, include);
}
this.Delete = function (entities, isRemove) {
if (!Array.isArray(entities)) {
entities = [entities];
}
for (var i = entities.length - 1; i >= 0; i--) {
var entity = entities[i];
if (entity.EntityAspect.EntityState == this.EntityState.Added) {
entity.IsDeleted = true;
this.OnChangeState(entity, this.EntityState.Added, this.EntityState.Deleted);
this.DbSet(entity.__entityType).Delete(entity);
}
else {
entity.StashChanges(entity.GetAllChangedProperties(), "BeforeDeleteState");
entity.ResetChanges();
this.SetDelete(entity);
}
}
};
this.EnableTrackDirty = false;
this.DirtyEntities = [];
this.AddedEntities = [];
this.DeleteEntities = [];
this.OnChangeState = function (entity, before, after) {
if (entity.__dbSet == null || !this.EnableTrackDirty) {
return;
}
if (before == this.EntityState.Modified && after == this.EntityState.Added) {
this.DirtyEntities.remove(entity);
}
else if (after == this.EntityState.Added) {
if (entity.IsDirty)
this.DirtyEntities.add(entity);
this.AddedEntities.add(entity);
}
else if (after == this.EntityState.Deleted) {
this.AddedEntities.remove(entity);
this.DirtyEntities.remove(entity);
if (before == this.EntityState.Unchanged && before == this.EntityState.Modified)
this.DeleteEntities.add(entity);
}
else if (after == this.EntityState.Modified) {
this.DirtyEntities.add(entity);
}
else if (after == this.EntityState.Unchanged) {
this.DirtyEntities.remove(entity);
this.AddedEntities.remove(entity);
}
this.HasDirtyEntity = (this.DirtyEntities.length + this.AddedEntities.length + this.DeleteEntities.length) > 0;
}
this.RevertDeleted = function (entities) {
if (!Array.isArray(entities) && entities) {
entities = [entities];
}
for (var i = 0; i < entities.length; i++) {
var item = entities[i];
if (item.Is) {
if (item.HasStash("BeforeDeleteState")) {
item.ApplyStash(null, "BeforeDeleteState");
item.RemoveStash(true, "BeforeDeleteState");
}
if (item.EntityAspect.EntityState == this.EntityState.Deleted) {
if (item.IsDirty) {
App.DataContext.SetUpdate(item);
}
else {
App.DataContext.SetUnchanged(item);
}
}
else if (item.EntityAspect.EntityState == this.EntityState.Added && item.IsDeleted) {
this.DbSet(item.__entityType).Attach(item);
}
item.IsDeleted = false;
// sync navigation property
item.SyncNavigationProp();
}
}
}
this.SetUnchanged = function (entities) {
if (!Array.isArray(entities)) {
entities = [entities];
}
for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
this.OnChangeState(entity, entity.EntityAspect ? entity.EntityAspect.EntityState : null, this.EntityState.Unchanged);
entity.EntityAspect = {
EntityState: this.EntityState.Unchanged
};
if (entity.IsDirty) {
entity.AcceptChanges();
}
}
};
this.SetDelete = function (entities) {
if (!Array.isArray(entities)) {
entities = [entities];
}
for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
var oldState = entity.EntityAspect ? entity.EntityAspect.EntityState : null;
entity.IsDeleted = true;
}
};
this.SetAdd = function (entities) {
if (!Array.isArray(entities)) {
entities = [entities];
}
for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
this.OnChangeState(entity, entity.EntityAspect ? entity.EntityAspect.EntityState : null, this.EntityState.Added);
entity.EntityAspect = {
EntityState: this.EntityState.Added
};
entity.IsDeleted = false;
}
};
this.SetUpdate = function (entities) {
if (!Array.isArray(entities)) {
entities = [entities];
}
for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
this.OnChangeState(entity, entity.EntityAspect ? entity.EntityAspect.EntityState : null, this.EntityState.Modified);
if (!entity.EntityAspect || entity.EntityAspect.EntityState != this.EntityState.Added) {
entity.EntityAspect = {
EntityState: this.EntityState.Modified
};
}
}
};
this.HardDelete = function (entities) {
if (!Array.isArray(entities)) {
entities = [entities];
}
for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
this.OnChangeState(entity, entity.EntityAspect ? entity.EntityAspect.EntityState : null, this.EntityState.Deleted);
entity.IsDeleted = true;
entity.EntityAspect = {
EntityState: this.EntityState.Deleted
};
}
};
this.ClearAll = function () {
for (var prop in this) {
var value = this[prop];
if (value instanceof DataSet) {
delete this[prop];
}
}
this.HasDirtyEntity = false;
this.DirtyEntities = [];
this.AddedEntities = [];
this.DirtyEntityCount = 0;
}
// validation
this.RegisterValidators = function (validators) {
for (var i = 0; i < validators.length; i++) {
var validator = validators[i];
if (window[validator.ValidatorType]) {
var validatorObject = new window[validator.ValidatorType](validator.Validator);
validatorObject.MemberName = validator.MemberName;
this.DbSet(validator.EntityType).AddValidator(validatorObject);
}
}
}
this.ValidateCompleteEntity = function (entity) {
var validateCompleteEntity = function (entity, entityList) {
entityList.push(entity);
var result = entity.Validate();
if (!result) { console.log(entity); }
for (prop in entity) {
var value = entity[prop];
if (value && value.Is) {
value = [value];
}
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
if (value[i].Is && entityList.indexOf(value[i]) < 0) {
var validationResult = validateCompleteEntity(value[i], entityList);
result = result && validationResult;
}
}
}
}
return result;
};
return validateCompleteEntity(entity, []);
}
}
DataContext.prototype.EntityState = {
Modified: "Modified",
Deleted: "Deleted",
Added: "Added",
Unchanged: "Unchanged",
Detached: "Detached"
};
var ObjectHelper = {
SetComputedProperty: function (entity, propName, fn) {
Object.defineProperty(entity, propName, {
get: fn,
enumerable: true,
configurable: true
});
},
}
function App(options) {
this.AppBar = null;
this.CurrentPage = null;
this.Resources = null;
this._initialized = false;
this.Initialize = function () {
return true;
}
this.OnAppStart = function () { }
this.OnAppReady = function () { }
this.InitializeService = function () { }
this.OnError = function (type, errors) {
console.error(errors);
}
ExtendableObject.call(this, options);
var defaultHandler = {};
this.DefaultHandler = function (name, fn) {
if (typeof (fn) == "function") {
var savedFn = (function (fn, me) { return function () { return fn.apply(me, arguments); }; })(fn, this);
defaultHandler[name] = savedFn;
}
else if (typeof (fn) == "undefined") {
return defaultHandler[name];
}
}
this.OnNavigated = function (contentWindow) {
if (!contentWindow.Page) {
this.OnError("load", "could not found current Page object.");
return false;
}
window.App.CurrentPage = contentWindow.Page;
window.App.AppBar.HelpLink = App.CurrentPage.HelpLink;
window.App.CurrentPage.OnNavigated(window.App.NavigationService.CurrentNavigationItem);
window.App.CurrentPage.OnPageReady();
App.AppView.models.PageModel = window.App.CurrentPage;
window.App.DataContext.EnableTrackDirty = true;
//navigationService onloaded
App.NavigationService.OnLoaded(App.NavigationService.CurrentNavigationItem, contentWindow);
}
this.Register = function (name, objConstructor, parameter, type, isLiveTime) {
isLiveTime = typeof (isLiveTime) != "undefined" ? isLiveTime : true;
if (!Array.isArray(this["__" + type])) this["__" + type] = [];
this["__" + type].push(name);
if (typeof (objConstructor) == "object")
this[name] = objConstructor;
else {
if (isLiveTime) {
var tempObj = {};
objConstructor.apply(tempObj, parameter);
this[name] = tempObj;
}
else {
Object.defineProperty(this, "__param" + name, {
value: parameter,
configurable: true,
writable: true
});
this[name] = objConstructor;
}
}
}
this.GetDefault = function (name) {
if (!this[name]) {
return null;
}
var result;
if (typeof (this[name]) == "function") {
result = {};
this[name].apply(result, this["__param" + name]);
}
else {
result = this[name];
}
return result;
}
this.GetAllRegistered = function (type) {
if (!this["__" + type]) {
return false;
}
var result = {};
for (var i = 0; i < this["__" + type].length; i++) {
var item = this["__" + type][i];
result[item] = this.GetDefault(item);
}
return result;
}
this.RegisterService = function (name, serviceFn, parameter, isLiveTime) {
isLiveTime = typeof (isLiveTime) != "undefined" ? isLiveTime : true;
this.Register(name, serviceFn, parameter, "service", isLiveTime);
}
this.GetService = function (name) {
return this.GetDefault(name);
}
this.GetAllService = function () {
return this.GetAllRegistered("service");
};
this.Start = function () {
if (this._initialized)
return;
this._initialized = this.Initialize();
if (this._initialized) {
this.OnAppStart();
this.InitializeService();
}
}
this.SendAmplitude = function (data) {
var send = true;
if (App.Model.IsDebug) {
data.EventType = data.EventType.replaceAll(" ", "_");
}
data.Properties.StoreId = App.Model.StoreSetting.Store.Id;
data.Properties.UserStatus = App.Model.Username.includes("@iseller") ? "Support" : "Non Support";
if (!App.Model.Brand.IsPartner) {
if (data.Properties.hasOwnProperty('ChannelMarketplace')) {
if (data.Properties.ChannelMarketplace) {
data.Properties.ChannelMarketplace = data.Properties.ChannelMarketplace.replaceAll("outlet", "online");
} else {
send = false;
}
}
if (send) {
amplitude.setUserId(App.Model.StoreSetting.Store.Id);
amplitude.track(data.EventType, data.Properties);
}
}
}
this.Initialize();
}
function SetApp() {
var app = null;
if (window.parent != window) {
try {
var rootWindow = window;
do {
rootWindow = rootWindow.parent;
}
while (!rootWindow.App && rootWindow.parent != rootWindow);
app = rootWindow.App;
}
catch (e) { }
}
if (!app) {
var lastNotificationDate = new Date();
var notifTO = null;
app = new App({
OnAppStart: function () {
this.DefaultHandler("SaveCommand", function (command, data, filter, dataParser) {
if (command)
command.IsProcessing = true;
var promise = App.HttpService.Save(data, filter, dataParser);
promise.always(function (result) {
if (command)
command.IsProcessing = false;
});
return promise;
});
this.DefaultHandler("CancelCommand", function (command, data) {
if (data != null) {
data.ResetChanges();
App.CurrentPage.HasUnsavedChanges = function () {
return false;
}
}
var param = {};
var url = "";
if (App.AppBar.Breadcrumbs.length > 1) {
var bc = App.AppBar.Breadcrumbs[App.AppBar.Breadcrumbs.length - 2];
url = bc.Url;
param = bc.Parameter;
}
else {
url = App.NavigationService.CurrentNavigationItem.Url.split("/");
url.pop();
url = url.join("/");
}
var btitles = App.NavigationService.CurrentNavigationItem.BreadcrumbTitles;
if (Array.isArray(btitles)) btitles.shift();
var navItem = new NavigationItem({
Url: url,
BreadcrumbTitles: btitles,
Parameter: App.NavigationService.CurrentNavigationItem.Parameter
});
App.NavigationService.Navigate(navItem);
});
this.DefaultHandler("DuplicateCommand", function (command, data) {
App.CurrentPage.HasUnsavedChanges = function () {
return false;
}
var url = App.NavigationService.CurrentNavigationItem.Url.replace("{id}", "Add/{duplicateid}");
var parameter = {
duplicateid: App.NavigationService.CurrentNavigationItem.Parameter.id
};
var navItem = new NavigationItem({
Url: url,
Parameter: parameter
});
App.NavigationService.Navigate(navItem);
});
// register sidebar event
EventManager.RegisterEvent(window.App.RootWindow, "blur", function (event) {
window.App.HideSidebar(event);
});
var mainContent = document.querySelector(".main-container.appbar-container");
EventManager.RegisterEvent(mainContent, "click", function () {
window.App.HideSidebar();
});
},
RootWindow: window,
Deferred: function (additionalTuples, isOverwrite) {
var tuples = [
// action, add listener, listener list, final state
["resolve", "done", jQuery.Callbacks("once memory stopOnFalse"), "resolved"],
["reject", "fail", jQuery.Callbacks("once memory stopOnFalse"), "rejected"],
["notify", "progress", jQuery.Callbacks("memory")]
],
state = "pending",
promise = {
state: function () {
return state;
},
always: function () {
if (deferred.done)
deferred.done(arguments)
if (deferred.fail)
deferred.fail(arguments);
return this;
},
then: function ( /* fnDone, fnFail, fnProgress */) {
var fns = arguments;
return jQuery.Deferred(function (newDefer) {
jQuery.each(tuples, function (i, tuple) {
var fn = jQuery.isFunction(fns[i]) && fns[i];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[tuple[1]](function () {
var returned = fn && fn.apply(this, arguments);
if (returned && jQuery.isFunction(returned.promise)) {
returned.promise()
.done(newDefer.resolve)
.fail(newDefer.reject)
.progress(newDefer.notify);
} else {
newDefer[tuple[0] + "With"](this === promise ? newDefer.promise() : this, fn ? [returned] : arguments);
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function (obj) {
return obj != null ? jQuery.extend(obj, promise) : promise;
}
},
deferred = {};
if (Array.isArray(additionalTuples)) {
tuples = isOverwrite ? additionalTuples : tuples.concat(additionalTuples);
}
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each(tuples, function (i, tuple) {
var list = tuple[2],
stateString = tuple[3];
// promise[ done | fail | progress ] = list.add
promise[tuple[1]] = list.add;
// Handle state
if (stateString && i <= 2) {
list.add(function () {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[i ^ 1][2].disable, tuples[2][2].lock);
}
// deferred[ resolve | reject | notify ]
deferred[tuple[0]] = function () {
deferred[tuple[0] + "With"](this === deferred ? promise : this, arguments);
return this;
};
deferred[tuple[0] + "With"] = list.fireWith;
});
// Make the deferred a promise
promise.promise(deferred);
// All done!
return deferred;
},
BindFunction: function (fn, me, args) {
return function () {
var completeArguments = args;
if (!Array.isArray(completeArguments)) {
completeArguments = [];
}
for (var i = 0; i < arguments.length; i++) {
completeArguments.push(arguments[i]);
}
fn.apply(me, completeArguments)
};
},
SetNumberFormat: function (obj) {
if (!obj)
return;
App.NumberFormat = obj;
},
SetDateFormat: function (dateFormat) {
if (dateFormat) {
App.DateFormat = dateFormat;
}
},
InitializeService: function () {
this.Resources = window.__resources;
delete window.__resources;
this.Resources.GetString = function (key) {
if (this.hasOwnProperty(key))
return this[key];
return key;
}
this.RegisterService("PresenterService", new PresenterService({
OnInitialize: function () {
this.Dialog.OnDialogShowed = function (option) {
if (option.ContentMode == "iframe") {
if (option.ShowHeader) {
App.PresenterService.Progress.Hide(option.HeaderElement);
}
else {
App.PresenterService.Progress.HideLoader(option.BodyElement);
}
ISMaterialTheme.RegisterAllBehaviour(option.IFrame.contentDocument);
}
else {
ISMaterialTheme.RegisterAllBehaviour(option.Element);
}
};
this.Dialog.OnBeforeShow = function (option) {
if (option.ContentMode == "iframe") {
if (option.ShowHeader) {
App.PresenterService.Progress.Show(option.HeaderElement);
}
else {
App.PresenterService.Progress.ShowLoader(option.BodyElement);
}
}
};
this.Dialog.DefaultHandler("SaveHandler", function (commandName, data, model, dialog) {
if (commandName == "SaveCommand") {
dialog.DefaultHandler("SaveCommand")(model.button.Command, data);
}
else {
dialog.DefaultHandler("CancelCommand")(null, data);
}
});
this.Dialog.DefaultHandler("SaveCommand", function (command, data) {
var modal = this;
command.IsProcessing = true;
var promise = null;
if (data.IsNew) {
promise = App.HttpService.Insert(data);
}
else {
promise = App.HttpService.Update(data);
}
setTimeout(function () {
promise.done(function (result) {
command.IsProcessing = false;
if (result.IsSuccess) {
modal.Close();
}
}).fail(function (result) {
command.IsProcessing = false;
});
});
return promise;
});
this.Dialog.DefaultHandler("CancelCommand", function (command, data) {
if (command && command.Is && !data) {
data = command;
}
if (data && data.Is) {
if (data.IsNew) {
App.DataContext.Delete(data);
}
else {
data.ResetChanges();
}
}
this.Close();
});
}
}));
this.RegisterService("NavigationService", new NavigationService({
BeforeNavigate: function (navigationItem, navigationTarget) {
if (App.Model && App.Model.IsNotAccessible == true && App.Model.NotAccesibleRedirectUrl.toLowerCase() != navigationItem.Url.toLowerCase()) {
navigationItem.Url = App.Model.NotAccesibleRedirectUrl;
this.SetNavigationInfo(navigationItem);
}
if (App.CurrentPage && App.CurrentPage.HasUnsavedChanges()) {
var service = this;
if (service.DirtyFormShowed)
return false;
service.DirtyFormShowed = true;
App.PresenterService.Confirm.Show(App.Resources.DirtyFormConfirm).done(function () {
App.DataContext.ClearAll();
service.Navigate(navigationItem, navigationTarget);
}).always(function () {
service.DirtyFormShowed = false;
});
return false;
}
if (navigationItem.NavigationTarget === false)
return true;
if (this.NavigationTarget) {
// ensure old content is not clickable
var blocker = document.createElement("div");
blocker.style.cssText = "background-color:white;opacity:0;position:absolute;z-index:10;top:0;left:0;right:0;bottom:0";
this.NavigationTarget.contentDocument.body.appendChild(blocker);
this.NavigationTarget.contentDocument.body.removeAttribute("isloaded");
}
if (App.CurrentPage) {
App.DataContext.EnableTrackDirty = false;
// delay unbind to ensure templated text is not seen
var currentPage = App.CurrentPage;
if (currentPage.BindingView) {
setTimeout(function () {
currentPage.OnUnload();
App.BindingService.Unbind(currentPage.BindingView);
}, 300);
}
App.ToggleAppbar(true);
window.App.DataContext.ClearAll();
}
App.PresenterService.Progress.Show("page-load");
return true;
},
AfterNavigate: function (navigationItem) {
window.App.AppBar.SecondaryButtons = [];
window.App.AppBar.PrimaryButton = null;
window.App.AppBar.HelpLink = "";
App.HideSidebar();
if (navigationItem.NavigationTarget === false)
return true;
// breadcrumb
if (!this.PrevNavigationItem || this.PrevNavigationItem.Url != navigationItem.Url) {
var currentPath = this.GetNavigationPath(navigationItem);
if (navigationItem.BreadcrumbTitles) {
navigationItem.BreadcrumbTitles.reverse().each(function (title, index) {
if (title)
currentPath[currentPath.length - (1 + index)].Title = title;
});
}
window.App.AppBar.SetBreadcrumb(currentPath);
}
var sidebar = document.querySelector("aside.sidebar");
if (!sidebar)
return;
var prevNode = sidebar.querySelector(".active");
var node = this.GetSiteMapNode(navigationItem);
if (!node)
return;
var activeNode = sidebar.querySelector("[href='" + navigationItem.Url + "']");
while (activeNode == null && node.parentElement) {
node = node.parentElement;
var url = node.getAttribute("url");
activeNode = url ? sidebar.querySelector("[href='" + url + "']") : null;
}
if (activeNode)
activeNode = activeNode.parentElement;
if (activeNode == prevNode)
return;
// add current active state
if (activeNode) {
var parent = activeNode.parentElement;
while (parent && !parent.classList.contains("sidebar-menu")) {
if (parent.tagName == "UL") {
parent.parentElement.classList.add("active-group");
if (!parent.classList.contains("in")) {
parent.previousElementSibling.click();
}
}
parent = parent.parentElement;
}
activeNode.classList.add("active");
}
if (!prevNode)
return;
// remove previous active state
var parent = prevNode.parentElement;
var activeNodeParent = activeNode ? activeNode.parentElement : null;
while (parent != activeNodeParent && parent && parent.classList && !parent.classList.contains("sidebar-menu")) {
if (parent.tagName == "UL") {
parent.parentElement.classList.remove("active-group");
if (parent.classList.contains("in")) {
parent.previousElementSibling.click();
}
}
parent = parent.parentElement;
}
prevNode.classList.remove("active");
},
OnLoaded: function (navigationItem, scope) {
if (navigationItem.__isHandled) {
return;
}
navigationItem.__isHandled = true;
// avoid flickering by settling no-animation first
setTimeout(function () {
try {
App.ToggleAppbar();
}
catch (e) {
}
scope.document.body.removeAttribute("style");
scope.document.body.removeAttribute("no-animation");
}, 90)
setTimeout(function () {
try {
scope.document.body.setAttribute("isloaded", "");
}
catch (e) { }
}, 100);
this.SetNavigationInfo(navigationItem);
var model = { AppModel: App.Model, Resources: App.Resources, Page: scope.Page };
if (scope.Page && scope.Page.Item)
model.PageModel = scope.Page.Item;
navigationItem.PageTitle = App.BindingService.GetText(navigationItem.PageTitle, model);
history.replaceState(navigationItem.Parameter, navigationItem.PageTitle, navigationItem.CompleteUrl);
document.title = navigationItem.PageTitle;
App.PresenterService.Progress.Hide("page-load");
},
GetQuery: function (queryKey) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (pair[0] === queryKey) {
return decodeURIComponent(pair[1]);
}
}
return "";
}
}));
this.RegisterService("NotificationService", new NotificationService({
ShowErrorNotif: function (title, errorTrown, errorTrace) {
var errorNotif = new NotificationOptions({
Type: "error",
Title: title,
Text: errorTrown,
Buttons: [
new NotificationButton({
Caption: App.Resources.GetHelp,
Name: "ErrorHelp"
}),
new NotificationButton({
Caption: App.Resources.Close,
Name: "Close"
})
]
});
this.Notify(errorNotif).done(function (name) {
if (name == "ErrorHelp") {
var plainErrorTrace = errorTrace;
// strip out html, reformat with simple line break
if (errorTrace && errorTrace.toLowerCase().indexOf("") > -1) {
var dummyEl = document.createElement("div");
dummyEl.innerHTML = errorTrace;
plainErrorTrace = dummyEl.innerText.replace(/ +/g, '').replace(/[\n\r]+/g, '\n');
errorTrace = plainErrorTrace.replace(/(?:\r\n|\r|\n)/g, '
');
}
var errorConfirm = new ConfirmOption({
Template: '
' + App.Resources.DialogErrorTitle + '
' + App.Resources.DialogErrorText + '
' +
'
' + errorTrace + '
' +
'