/* 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 = ''; 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: "
" + "

" + title + "

" + "
", 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("

" + reportFilter + "

"); printFrame.contentDocument.write("

" + dateRange + "

"); 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 + '
' + '
' + '
' + '
' + '
', ShowFooter: false, Type: "danger", ShowIcon: false, Width: "600px", Model: { ExecuteMailCommand: new DelegateCommand({ Command: function (model, param) { this.IsProcessing = true; try { sendIntercomMessage(App.Model.Username, "Hello, I'd like to submit error report in iSeller WebApp with the following details:" + plainErrorTrace).done(function () { this.IsProcessing = false; App.PresenterService.Confirm.CloseConfirm(errorConfirm); }); } catch (e) { } } }), ExecuteChatCommand: new DelegateCommand({ Command: function (model, param) { App.OpenLiveChat(); } }), ExecuteContactCommand: new DelegateCommand({ Command: function (model, param) { window.open("https://isellercommerce.com/about", "_blank") } }) } }); App.PresenterService.Confirm.Show(errorConfirm); } }); } })); this.RegisterService("DataContext", new DataContext({ GetDefaultOption: function () { return { OnPropertyChanged: function (prop, oldValue, newValue) { if (oldValue !== newValue && (!Object.isEmptyValue(oldValue) || !Object.isEmptyValue(newValue))) { if (prop == "IsDirty") { if (this.EntityAspect.EntityState != App.DataContext.EntityState.Added && this.EntityAspect.EntityState != App.DataContext.EntityState.Deleted) { if (newValue) App.DataContext.SetUpdate(this); else App.DataContext.SetUnchanged(this); } else { if (newValue) App.DataContext.OnChangeState(this, null, App.DataContext.EntityState.Modified); else App.DataContext.OnChangeState(this, App.DataContext.EntityState.Modified, App.DataContext.EntityState.Added); } } this.RemoveValidationState(prop); App.BindingService.TriggerChange(this, prop); } if (App.DialogPage) { App.DialogPage.OnModelPropertyChanged(this, prop, oldValue, newValue); } else if (App.CurrentPage) { App.CurrentPage.OnModelPropertyChanged(this, prop, oldValue, newValue); } } } } })); this.RegisterService("HttpService", new HttpClientService({ OnError: function (jqXHR, textStatus, errorThrown) { if (jqXHR.statusText == "abort" || this.url == "/service/UserNotification/GetNewNotifications") return; var errorTrace = ""; if (jqXHR.responseJSON != null) errorTrace = jqXHR.responseJSON.Error.StackTraceString; else if (jqXHR.responseText) errorTrace = jqXHR.responseText.replace(/^[\w\W]*?]*>/i, ""); else errorTrace = errorThrown; errorTrace = errorTrace.replace(/<\/body>[\w\W]*$/i, ""); App.NotificationService.ShowErrorNotif(App.Resources.Error, errorThrown, errorTrace); }, OnSuccess: function (result, textStatus, jqXHR) { var notifService = App.NotificationService; if (typeof (result) === "string" && result.indexOf('"LoginViewModel"') > 0) { App.PresenterService.Confirm.Show(new AlertOption({ Text: App.Resources.SessionExpired, IsStaticBackdrop: true, ShowCancel: true, CancelText: "Login", OKText: "Continue session" })) .done(function () { var data = { Password: "" }; var confirmPassword = new ConfirmOption({ Template: '

Please enter your current password to continue your session.

{Model.VerifyUserMessage}

', OKButtonType: 'primary', OKText: 'Proceed', AutoClose: false, IsStaticBackdrop: true, Model: data }); App.PresenterService.Confirm.Show(confirmPassword) .done(function (model) { var command = this; data.VerifyUserMessage = ""; if (!data.Password) { data.VerifyUserMessage = App.Resources.AlertPasswordEntry; return false; } command.IsProcessing = true; App.HttpService.Post("Identity", "Relogin", { loginViewModel: { Username: App.Model.Username, Password: data.Password, StoreName: App.Model.StoreShortName }, forceLogin: true }) .done(function (result) { if (result.IsSuccess) { App.PresenterService.Confirm.CloseConfirm(confirmPassword); App.GetNotification(); } else { data.VerifyUserMessage = result.Message; } }) .fail(function (result) { data.VerifyUserMessage = App.Resources.AlertPasswordNotCorrect; }) .always(function () { command.IsProcessing = false; }); return false; }) .fail(function () { App.PresenterService.Confirm.CloseConfirm(confirmPassword); App.RootWindow.onbeforeunload = null; App.NavigationService.Reload(); }); }) .fail(function () { App.RootWindow.onbeforeunload = null; App.NavigationService.Reload(); }); setTimeout(function () { clearTimeout(notifTO); }, 100); return false; } if (result.RedirectURL) { var navItem = new NavigationItem(result.RedirectURL); App.DataContext.HasDirtyEntity = false; App.NavigationService.Navigate(navItem, null); return; } else { if (typeof (result.IsSuccess) == "boolean") { if (result.IsSuccess) { if (result.ShowNotification && (result.Message || result.Status)) { var buttons = [ new NotificationButton({ Name: "Close", Caption: App.Resources.Close }) ]; var currentNav = App.NavigationService.CurrentNavigationItem; if (this.Entity && this.Entity == App.CurrentPage.Item && this.Entity.IsNew) { buttons.add( new NotificationButton({ Name: "AddAnother", Caption: App.Resources.AddAnother }) ); } var notifOption = new NotificationOptions({ Type: "success", Title: result.Status, Text: result.Message, Buttons: buttons }); notifService.Notify(notifOption).done(function (name) { if (name == "AddAnother") { if (currentNav.Parameter.duplicateid) { delete currentNav.Parameter.duplicateid; currentNav.Url = currentNav.Url.replace("/{duplicateid}", ""); } App.NavigationService.Navigate(currentNav); } }); } } else { if (result.ValidationErrors) { for (var i = 0; i < result.ValidationErrors.length; i++) { var validationError = result.ValidationErrors[i]; var entity; if (validationError.PrimaryKeys && Object.keys(validationError.PrimaryKeys).length > 0) entity = App.DataContext.DbSet(validationError.EntityType).Find(validationError.PrimaryKeys); else if (this.Entity && this.Entity.Is(validationError.EntityType)) entity = this.Entity; else entity = App.DataContext.DbSet(validationError.EntityType).Data[0]; // support server validation error for Added entity if (!entity && App.HttpService.InsertDataContext) { var insertedEntity = App.HttpService.InsertDataContext; if (insertedEntity.IsPrimaryKeysMatch(validationError.PrimaryKeys)) entity = insertedEntity; } if (entity) { var validationResultInfo = new ValidationResultInfo(); for (var _i = 0; _i < validationError.Errors.length; _i++) { var error = validationError.Errors[_i]; if (entity.hasOwnProperty(error.MemberName)) validationResultInfo.AddValidationResult(error.MemberName, new ValidationResult({ MemberName: error.MemberName, IsSuccess: false, Message: error.ErrorMessage })); } entity.ValidationResult = validationResultInfo; } } } else if (result.ShowNotificationOnError) { var message = result.LocalizedMessage ? result.LocalizedMessage : result.Message; if (result.Status || message) App.NotificationService.ShowErrorNotif(result.Status, message, result.Error ? result.Error.StackTraceString : message); } } } } }, ParseUrl: function (controller, action, data, filter) { return "/service/" + controller + "/" + action; }, ParseData: function (data, filter) { if ((data && data.Is) || (typeof (data) === "object" && data != null)) { data = App.DataContext.GetCleanEntity(data, filter); } return data; }, Save: function (data, filter, dataParser) { if (!data.Is) { console.error("this method only for entity"); } var promise = null; var validationSuccess = App.DataContext.ValidateCompleteEntity(data); if (validationSuccess) { var promise = this.Post(data.__entityType, "Save", data, filter, undefined, dataParser); var service = this; promise.done(function (result) { if (result.IsSuccess) { if (result.Data) { service.UpdateChanges(result.Data); } data.AcceptAllChanges(); } }); } else { var deferred = App.Deferred(); promise = deferred.promise(); deferred.rejectWith(promise, [{ IsSuccess: false, Data: null, MessageKey: "ValidationFailed" }]); } return promise; }, Insert: function (data) { if (!data.Is && !data.IsNew) { console.error("this method only for entity"); } var validationSuccess = data.Validate(); if (validationSuccess) { // save current reference for validation reference this.InsertDataContext = data; var promise = this.Post(data.__entityType, "Insert", data, []); var service = this; promise.done(function (result) { if (result.IsSuccess) { App.DataContext.RegisterEntity(data); if (result.Data) { service.UpdateChanges(result.Data); } data.AcceptChanges(); data.SyncNavigationProp(); service.InsertDataContext = null; } }); } else { var deferred = App.Deferred(); promise = deferred.promise(); deferred.rejectWith(promise, [{ IsSuccess: false, Data: null, MessageKey: "ValidationFailed" }]); } return promise; }, Update: function (data) { if (!data.Is) { console.error("this method only for entity"); } if (data.IsDirty) { var validationSuccess = data.Validate(); if (validationSuccess) { var promise = this.Put(data.__entityType, "Update", data, []); var service = this; promise.done(function (result) { if (result.IsSuccess) { if (result.Data) { service.UpdateChanges(result.Data); } data.AcceptChanges(); } }); } else { var deferred = App.Deferred(); promise = deferred.promise(); deferred.rejectWith(promise, [{ IsSuccess: false, Data: null, MessageKey: "ValidationFailed" }]); } } else { var deferred = App.Deferred(); promise = deferred.promise(); deferred.resolveWith(promise, [{ IsSuccess: true, Data: null, MessageKey: "DataNotModified" }]); } return promise; }, UpdateChanges: function (savedEntities) { for (var i = 0; i < savedEntities.length; i++) { var entityInfo = savedEntities[i]; var dbSet = App.DataContext.DbSet(entityInfo.Type); var entity = entityInfo.Entity; var existing = dbSet.Find(entity); if (existing != null) { entityInfo.Entity = existing; existing.UpdateData(entity); if (existing.IsDeleted) { App.DataContext.HardDelete(existing); } existing.AcceptChanges(); } else if (!entity.IsDeleted) { entityInfo.Entity = App.DataContext.ParseEntity(entity, entityInfo.Type); } } }, Delete: function (entityType, primaryKeys) { var data = null; if (entityType.Is) { data = entityType; entityType = data.__entityType; primaryKeys = data.GetKeyValues(); } var promise = null; if (data && data.Is && data.IsNew) { App.DataContext.Delete(data); var deferred = App.Deferred(); promise = deferred.promise(); deferred.resolveWith(promise, [{ IsSuccess: true, Data: null }]); } else { if (!Array.isArray(primaryKeys)) { primaryKeys = [primaryKeys]; } var service = this; promise = this.HttpDelete(entityType, "Delete", { primaryKeys: primaryKeys }); promise.done(function (result) { if (result.IsSuccess) { var entity = App.DataContext.DbSet(entityType).Find(primaryKeys); if (entity) { App.DataContext.Delete(entity); entity.AcceptChanges(); } if (result.Data) { service.UpdateChanges(result.Data); } } }); } return promise; }, GetAll: function (entityType, queryDescriptor) { var service = this; var promise = this.Post(entityType, "GetSimpleData", queryDescriptor); promise.done(function (result) { if (result.IsSuccess) { if (result.Data) service.UpdateChanges(result.Data); } }); return promise; }, Find: function (entityType, primaryKeys) { if (!Array.isArray(primaryKeys)) { primaryKeys = [primaryKeys]; } var promise = null; var exist = App.DataContext.DbSet(entityType).Find(primaryKeys); if (exist) { var deferred = App.Deferred(); promise = deferred.promise(); deferred.resolveWith(promise, [{ IsSuccess: true, Data: exist }]); } else { var service = this; promise = this.Put(entityType, "Find", { primaryKeys: primaryKeys }).done(function (result) { if (result.IsSuccess) { if (result.Data) { service.UpdateChanges(result.Data); if (Array.isArray(result.Data) && result.Data.length == 1) { result.Data = result.Data[0].Entity; } } } }); } return promise; }, })); this.RegisterService("BindingService", new BindingService({ Context: window.rivets, OnInitialize: function () { this.Context._.ComponentBinding.prototype.update = function (mod) { this.componentView.update(mod); }; var oriComUnbind = this.Context._.ComponentBinding.prototype.unbind; this.Context._.ComponentBinding.prototype.unbind = function (mod) { this.component.destroy && this.component.destroy.call(this, this.el); return oriComUnbind.apply(this, Array.from(arguments)); }; var originalValueRoutine = this.Context.binders.value.routine; this.Context.binders.value.routine = function (el, value) { var result = originalValueRoutine(el, value); // raised change event EventManager.TriggerEvent(el, "change"); return result; }; var rivet = this.Context["_"]; var oldSightglass = rivet.sightglass; this.Context["_"].sightglass = function () { var observer = oldSightglass.apply(this, arguments); observer.constructor.prototype.setValue = function (value) { if (typeof this.target === "undefined" || this.target === null) { for (var i = this.objectPath.length - 1; i < this.tokens.length; i++) { this.objectPath[i][this.tokens[i].path] = {}; } } if (typeof this.target === "object" && this.target !== null) this.adapter(this.key).set(this.target, this.key.path, value); } rivet.sightglass = oldSightglass; return observer; } this.Context.binders.value.bind = function (el) { if (!(el.tagName === 'INPUT' && el.type === 'radio')) { this.event = el.tagName === 'SELECT' ? 'change' : 'input'; if (el.tagName === 'INPUT') { // safari auto complete issue App.BindingService.Context["_"].Util.bindEvent(el, "blur", this.publish); } return App.BindingService.Context["_"].Util.bindEvent(el, this.event, this.publish); } } this.Context.binders.value.unbind = function (el) { if (!(el.tagName === 'INPUT' && el.type === 'radio')) { if (el.tagName === 'INPUT') { // safari auto complete issue App.BindingService.Context["_"].Util.unbindEvent(el, "blur", this.publish); } return App.BindingService.Context["_"].Util.unbindEvent(el, this.event, this.publish); } } // fix rivets each unbind this.Context.binders['each-*'].unbind = function (el) { var view, _i, _len, _ref1; if (this.iterated != null) { _ref1 = this.iterated; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { view = _ref1[_i]; view.unbind(); if (view.els[0].parentNode) view.els[0].parentNode.removeChild(view.els[0]); } el.setAttribute([this.view.prefix, this.type].join('-').replace('--', '-'), this.keypath); if (this.marker && this.marker.parentNode) { this.marker.parentNode.insertBefore(el, this.marker); this.marker.parentNode.removeChild(this.marker); this.marker = null; } } }; this.Context.binders['on-*'].routine = function (el, value) { if (this.handler) { App.BindingService.Context["_"].Util.unbindEvent(el, this.args[0], this.handler); } this.handler = this.eventHandler(value); if (this.args[0] == "click") { var oldHandler = this.handler; this.handler = function () { if (this.hasAttribute("disabled")) return; oldHandler.apply(this, arguments); }; } return App.BindingService.Context["_"].Util.bindEvent(el, this.args[0], this.handler); }; this.Context.binders['amplitude-*'] = { "function": true, priority: 1001, unbind: function (el) { if (this.handler) { return App.BindingService.Context["_"].Util.unbindEvent(el, this.args[0], this.handler); } }, routine: function (el, value) { if (this.handler) { App.BindingService.Context["_"].Util.unbindEvent(el, this.args[0], this.handler); } var handler = this.eventHandler(value); this.handler = function (e, m) { //if (e.type == 'click' && this.getAttribute("disabled") !== '') // return; var data = handler(e, m); App.SendAmplitude(data); }; return App.BindingService.Context["_"].Util.bindEvent(el, this.args[0], this.handler); } }; this.Context.binders.enabled = function (el, value) { el.disabled = !value; if (el.disabled) { el.setAttribute("disabled", true); } else { el.removeAttribute("disabled"); } return el.disabled; }; this.Context.binders.disabled = function (el, value) { el.disabled = !!value; if (el.disabled) { el.setAttribute("disabled", true); } else { el.removeAttribute("disabled"); } return el.disabled; }; var __indexOf = [].indexOf || function (item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; this.Context.adapters['.'].observe = function (obj, keypath, callback) { var callbacks, desc, value; callbacks = this.weakReference(obj).callbacks; if (callbacks[keypath] == null) { callbacks[keypath] = []; desc = Object.getOwnPropertyDescriptor(obj, keypath); if (!((desc != null ? desc.get && desc.get != "modelget" : void 0) || (desc != null ? desc.set && desc.set != "modelset" : void 0))) { var oldSet = desc ? desc.set : undefined; var oldGet = desc ? desc.get : undefined; value = obj[keypath]; Object.defineProperty(obj, keypath, { enumerable: desc && desc.enumerable === false ? false : true, configurable: true, get: function () { if (typeof (oldGet) == "function") return oldGet.apply(this, arguments); return value; }, set: (function (_this) { return function (newValue) { var cb, map, _i, _len, _ref1; var cb, map, _i, _len, _ref1; if (newValue !== value) { _this.unobserveMutations(value, obj[_this.id], keypath); if (typeof (oldSet) == "function") oldSet.call(this, newValue); else value = newValue; if (map = _this.weakmap[obj[_this.id]]) { callbacks = map.callbacks; if (callbacks[keypath]) { _ref1 = callbacks[keypath]; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { cb = _ref1[_i]; cb && cb(); } } return _this.observeMutations(newValue, obj[_this.id], keypath); } } }; })(this) }); } } if (__indexOf.call(callbacks[keypath], callback) < 0) { callbacks[keypath].push(callback); } return this.observeMutations(obj[keypath], obj[this.id], keypath); }; this.Context.adapters['.'].stubFunction = function (obj, fn) { var map, original, weakmap; original = obj[fn]; map = this.weakReference(obj); weakmap = this.weakmap; return obj[fn] = function () { var callback, k, r, response, _i, _len, _ref1, _ref2, _ref3, _ref4; response = original.apply(obj, arguments); _ref1 = map.pointers; for (r in _ref1) { k = _ref1[r]; _ref4 = (_ref2 = (_ref3 = weakmap[r]) != null ? _ref3.callbacks[k] : void 0) != null ? _ref2 : []; for (_i = 0, _len = _ref4.length; _i < _len; _i++) { callback = _ref4[_i]; if (callback) callback(); } } return response; }; } this.Context.formatters['='] = function (value, arg) { return value == arg; } this.Context.formatters['==='] = function (value, arg) { return value === arg; } this.Context.formatters['!='] = function (value, arg) { return value != arg; } this.Context.formatters['not'] = function (value, arg) { return !value; } this.Context.formatters['>'] = function (value, arg) { return value > arg; } this.Context.formatters['>='] = function (value, arg) { return value >= arg; } this.Context.formatters['<'] = function (value, arg) { return value < arg; } this.Context.formatters['<='] = function (value, arg) { return value <= arg; } this.Context.formatters['and'] = this.Context.formatters['&&'] = function (value, arg) { return value && arg; } this.Context.formatters['or'] = this.Context.formatters['||'] = function (value, arg) { return value || arg; } this.Context.formatters['isFirst'] = function (value, arg) { return value[0] == arg; } this.Context.formatters['isLast'] = function (value, arg) { return value[value.length - 1] == arg; } this.Context.formatters['int'] = { publish: function (value) { var val = parseInt(value) return isNaN(val) ? null : val; } } this.Context.formatters['float'] = { publish: function (value) { var val = parseFloat(value) return isNaN(val) ? null : val; } } this.Context.formatters['=?'] = { read: function (value, arg1, arg2, arg3) { return value == arg1; }, publish: function (value, arg1, arg2, arg3) { return value ? arg1.replace(/^'|'$/g, "") : arg3.replace(/^'|'$/g, ""); } } this.Context.formatters['count'] = function (value, arg) { return value && value.length ? value.length : 0; } this.Context.formatters['*'] = function (value, arg) { value = parseFloat(value); if (isNaN(value)) value = 0; arg = parseFloat(arg); if (isNaN(arg)) arg = 0; return value * arg; } this.Context.formatters['?'] = function (value, arg1, arg2, arg3) { return value ? arg1 : arg3; } this.Context.formatters['??'] = function (value, arg1) { return Object.isEmptyValue(value) ? arg1 : value; } this.Context.formatters['format'] = function (value, arg) { var vals = [value] if (arguments.length > 2) { for (var i = 2; i < arguments.length; i++) { vals.push(arguments[i]) } } arg = (arg ? arg : "").replace(/\[\[([0-9]+)\]\]/g, "{$1}"); return arg.formatString.apply(arg, vals); } this.Context.formatters['formatDate'] = function (value, format, placeholder) { if (!Date.IsDate(value)) { value = JSON.parse(`"${value}"`) } if (Date.IsDate(value)) { date = new Date(value); if (!format) format = App.DateFormat; return date.toString(format) } if (placeholder) return placeholder; return value; } this.Context.formatters['formatPhone'] = function (value, arg) { // only support Indonesian phone number value = (value && value.replace(/\D/g, '')) || ''; if (value === '') return value; arg = arg || '62'; if (value.startsWith('0')) { value = arg + value.substring(1); } if (!value.startsWith('62')) { // todo check for other country code here. value = arg + value; } const countryCode = value.substring(0, 2); const operatorCode = value.substring(2, 5); return '+' + countryCode + ' ' + operatorCode + '-' + value.substring(5, 9) + '-' + value.substring(9); } this.Context.formatters['lowercase'] = function (value) { return value.toString().toLowerCase(); } this.Context.formatters['uppercase'] = function (value) { return value.toString().toUpperCase(); } this.Context.formatters['capitalize'] = function (value, isAll) { value = (value || "").toString().trim(); if (isAll) return value.split(" ").each(function (item) { return item.charAt(0).toUpperCase() + item.slice(1); }).join(" "); if (value.length > 1) return value.charAt(0).toUpperCase() + value.slice(1); return value; } this.Context.formatters['buttonStyle'] = function (value, size) { var baseClass = "btn"; if (!value) { value = "default"; } switch (value.toLowerCase()) { case 'danger': case 'destructive': baseClass += " danger"; break; case 'primary': baseClass += " primary"; break; default: baseClass += " default"; break; } if (!size) { size = "medium"; } switch (size.toLowerCase()) { case 'xs': case 'xsmall': baseClass += " xsmall"; break; case 'sm': case 'small': baseClass += " small"; break; case 'lg': case 'large': baseClass += " large"; break; case 'md': case 'medium': default: baseClass += " medium"; break; } return baseClass; } this.Context.formatters['buttonResponsive'] = function (value, iconSize) { var button = this; value += " responsive-button"; if (button && !button.Icon) { value += " show-text"; } switch (iconSize) { case 'xs': case 'xsmall': value += " r-xs-icon-button"; break; case 'sm': case 'small': value += " r-sm-icon-button"; break; case 'md': case 'medium': value += " r-md-icon-button"; break; case 'lg': case 'large': value += " r-lg-icon-button"; break; default: value += " r-xs-icon-button"; break; } return value; } this.Context.formatters['listActionStyle'] = function (value, size) { var baseClass = ""; if (!value) { value = "default"; } switch (value.toLowerCase()) { case 'danger': case 'destructive': baseClass += " danger color-danger"; break; case 'primary': baseClass += " primary color-primary-500"; break; default: baseClass += ""; break; } return baseClass; } this.Context.formatters['isNullorEmpty'] = function (value) { return value === null || value === undefined || value === ""; } this.Context.formatters['in'] = function (value, arg, splitChar) { if (arg) { if (splitChar) { return arg.split(splitChar).indexOf(value) >= 0; } else if (arg.indexOf) { return arg.indexOf(value) >= 0; } } return value == arg; } this.Context.formatters['contain'] = function (value, arg) { if (value && value.indexOf) { return value.indexOf(arg) >= 0; } return value == arg; } this.Context.formatters['filter'] = this.Context.formatters['Filter'] = function (value, compare) { if (!Array.isArray(value)) { value = [value]; } if (!compare) { compare = "return Item"; } compare = eval("(function (Item, index){" + compare + "})"); result = []; result = value.findAll(compare); return result; } this.Context.formatters['group'] = function (value, compare) { if (!Array.isArray(value)) { var temp = []; if (value) { temp.push(value); } value = temp; } if (!compare) { compare = "return Item"; } compare = eval("(function (Item, index){" + compare + "})"); result = []; result = value.group(compare); return result; } this.Context.formatters['isNotDeleted'] = this.Context.formatters['filterNotDeleted'] = function (value) { if (Array.isArray(value)) { return value.findAll(function (item) { return !item.IsDeleted }); } else { return value && !value.IsDeleted ? value : null; } } this.Context.formatters['sort'] = function (value, compare) { if (!Array.isArray(value)) { return; } if (!compare) { compare = "return 0"; } compare = eval("(function (a, b){" + compare + "})"); result = []; value = ([]).concat(value); result = value.sort(compare); return result; } this.Context.formatters['indexvalue'] = function (value, arg) { if (Array.isArray(value)) { return value[arg]; } if (Array.isArray(arg)) { return arg[value]; } return null; } this.Context.formatters['FilterExcept'] = function (value, arg, compare) { if (!Array.isArray(value)) { value = [value]; } if (!compare) { compare = "return sourceItem == compareItem"; } compare = eval("(function (sourceItem, compareItem){" + compare + "})"); var result = []; if (Array.isArray(arg)) { for (var i = 0; i < value.length; i++) { var isMatch = false; for (var j = 0; j < arg.length && !isMatch; j++) { isMatch = compare.call(value, value[i], arg[j]); } if (!isMatch) { result.push(value[i]); } } } else { for (var i = 0; i < value.length; i++) { var isMatch = compare.call(value, value[i], arg); if (!isMatch) { result.push(value[i]); } } } return result; } this.Context.formatters['isNewEntity'] = function (value) { return value && value.EntityAspect && value.EntityAspect.EntityState == App.DataContext.EntityState.Added; } this.Context.formatters['activeStatus'] = function (value, arg) { return (value ? App.Resources.Active : App.Resources.Inactive); } this.Context.formatters['param'] = function (value, arg) { var param = Array.prototype.slice.call(arguments, 1); if (typeof (value) == "function") { return App.BindFunction(value, this, param); } return value; } this.Context.formatters['absolute'] = function (value, arg) { var value = parseFloat(value); if (value < 0) value = value * -1; return value; } this.Context.formatters['eval'] = function (value, arg) { var win = App.NavigationService.GetContentWindow(); if (!win) win = window; var result = false; try { var fn = eval("(function(value){" + arg + "})"); result = fn.call(win, value); } catch (e) { result = false; } return result; } this.Context.formatters['resources'] = this.Context.formatters['resource'] = function (value, arg) { if (arg) value = arg + value; if (App.Resources.hasOwnProperty(value)) return App.Resources[value]; return value; } this.Context.formatters['resourceFormat'] = function (value) { var args = []; for (var i = 1; i < arguments.length; i++) { if (arguments[i]) { args.push(arguments[i]); } } if (App.Resources.hasOwnProperty(value)) return String.prototype.formatString.apply(App.Resources[value].toString(), args); return value; } this.Context.formatters['valuetoresource'] = function (value, resourceKey) { var args = []; for (var i = 2; i < arguments.length; i++) { if (arguments[i]) { args.push(arguments[i]); } } if (App.Resources.hasOwnProperty(resourceKey)) return String.prototype.formatString.apply(App.Resources[resourceKey].toString(), args); return resourceKey; } this.Context.formatters['indexOf'] = function (value, arg) { return value.indexOf(arg); } this.Context.formatters['color'] = function (color) { if (typeof (color) == "object" && color) { color = color.Value; } return color ? color.replace(/^#FF/i, "#") : ""; } this.Context.formatters['FormatReportFilter'] = function (filterItem) { var result = ""; var filter = App.CurrentPage.Filters.find(function (item) { return item.PropertyName == filterItem.PropertyName || item.SecondPropertyName == filterItem.PropertyName; }) if (filter == null) return; result = filter.Caption; var localizedOperator = ""; var filterOperatorItem = filter.FilterOperators.find(function (item) { return item.Value == filterItem.Operator; }); if (filterOperatorItem) { localizedOperator = filterOperatorItem.Text; } result += " " + (localizedOperator ? localizedOperator : filterItem.Operator); var localizedValue = ""; if (filterItem.DisplayValue) { localizedValue = filterItem.DisplayValue; } result += " " + (localizedValue ? localizedValue : filterItem.Value); return result; } this.Context.formatters.currency = { read: function (value, rounding, minLength, precision) { if (value != null && value != undefined) { var floatValue = parseFloat(value); value = isNaN(floatValue) ? App.UnformatNumber(value) : floatValue; return App.FormatCurrency(value, rounding, precision, minLength); } return ""; }, publish: function (value, minLength) { var floatValue = parseFloat(value); value = isNaN(floatValue) ? App.UnformatNumber(value) : floatValue; return value; } } this.Context.formatters.number = { read: function (value, rounding, precision) { if (value != null && value != undefined) { var floatValue = parseFloat(value); value = isNaN(floatValue) ? App.UnformatNumber(value) : floatValue; return App.FormatNumber(value, rounding, precision); } return ""; }, publish: function (value, minLength) { var floatValue = parseFloat(value); value = isNaN(floatValue) ? App.UnformatNumber(value) : floatValue; return value; } } var d = {}; this.Context.formatters['fx'] = function (fnx) { var fn = fnx; if (typeof fnx != "function") { if (!d[fnx]) { var i = fnx.indexOf("=>"); var h = fnx.substring(0, i).trim(); if (h.indexOf("(") < 0) { h = "(" + h + ")"; } h = "function" + h; var b = fnx.substring(i + 2).trim().replace(/`/g, "'"); if (b[0] !== "{") { b = "{ return " + b.replace(/`/g, "'") + ";}"; } d[fnx] = eval("(" + h + b + ")"); } fn = d[fnx]; } var args = Array.from(arguments); args.shift(); var result = null; try { result = fn.apply(this, args); } catch (e) { } return result; } this.Context.formatters['ffx'] = function (fnx) { var fn = fnx; if (typeof fnx != "function") { if (!d[fnx]) { var i = fnx.indexOf("=>"); var h = fnx.substring(0, i).trim(); if (h.indexOf("(") < 0) { h = "(" + h + ")"; } h = "function" + h; var b = fnx.substring(i + 2).trim().replace(/(^|[^\\])`/g, "$1'"); if (b[0] !== "{") { b = "{ return " + b.replace(/([^\\])`/g, "$1'") + ";}"; } d[fnx] = eval("(" + h + b + ")"); } fn = d[fnx]; } return fn; } this.Context.formatters['fn'] = function (value, arg) { if (arg && arg.replace) arg = arg.replace(/\([^()]\)\s*$/, ""); var win = null, wins = [App.NavigationService.GetContentWindow()]; var contWinds = wins[0].document.getElementsByTagName("iframe"); for (var i = 0; i < contWinds.length; i++) { wins.unshift(contWinds[i].contentWindow); } // support dialog iframe if (App.DialogPage != null && App.DialogPage.PresenterService.Dialog.Stacks) { for (var i = 0; i < App.DialogPage.PresenterService.Dialog.Stacks.length; i++) { var dialogOp = App.DialogPage.PresenterService.Dialog.Stacks[i]; if (dialogOp.IFrame) wins.unshift(dialogOp.IFrame.contentWindow); } } for (var i = 0; i < wins.length; i++) { try { if (wins[i][arg]) { win = wins[i]; break; } } catch (e) { } } var args = [value]; for (var i = 2; i < arguments.length; i++) { args.push(arguments[i]); } if (win) return win.eval(arg).apply(this, args); else return value; } this.Context.formatters['propertyValue'] = function (value, arg) { return value.hasOwnProperty(arg) ? value[arg] : value; } this.Context.formatters['dialogTitle'] = function (entity, arg) { var result = ""; if (entity.IsNew) { result += App.Resources.Add + " " + App.GetResourceString(entity.__entityType) } else { result += App.Resources.Edit + " " + App.GetResourceString(entity.__entityType) + (entity.Name ? " - " + entity.Name : ""); } return result; } this.Context.formatters['localize'] = function (key, resources, language) { var resourceObject = resources && resources[key]; if (!resourceObject) { return key; } return resourceObject[language] || resourceObject["en-US"]; } // products page this.Context.formatters['join'] = function (values, keyPath) { var result = ""; if (!Array.isArray(values)) { values = [values]; } values.forEach(function (item) { if (keyPath) { keyPath = keyPath.split("."); for (var i = 0; i < keyPath.length; i++) { item = item[keyPath[i]]; } } result += item; }); return result; } this.Context.formatters['split'] = function (value, splitter, at) { value = value || "" let arr = value.split(splitter) at = parseInt(at) if (isNaN(at)) return arr if (arr.length > at) return arr[at] } this.RegisterBindings(); //components function ModernInputViewModel(options) { this.value = null; this.element = null; this.multipleSelection = false; this.inputDisabled = false; this.valueField = "."; this.displayField = "."; this.searchText = ""; this.separator = ";,"; this.addOnLostFocus = true; this.showDropdownButton = false; this.showTag = true; this.enableDropdown = false; this.isLoadOnDemand = false; this.pageSize = 20; this.page = 1; this.pageRows = 0; this.totalRows = 0; this.enableSearch = false; this.SelectedItem = []; this.inputStyle = ""; this.dropdownStyle = "dropdown-menu"; this.activeDropdownStyle = "active"; this.hoverDropdownStyle = "hover"; this.allowNewValue = true; this.enableDataSource = true; this.valueOnchange = null; this.isLoading = false; this.focus = 0; var selectcolor = ""; this.onInitialize = function () { }; this.valueCompare = function (a, b) { return this.GetItemValue(a) === this.GetItemValue(b); } Object.defineProperty(this, "selectColor", { set: function (value) { selectcolor = value; var val = this.value; this.value = this.multipleSelection ? [] : ""; this.value = val; }, get: function () { return selectcolor; }, enumerable: true, configurable: true }); // dropdown this.dataSource = null; this.enableFilter = true; this.createValue = function (text) { return text; }; Object.defineProperty(this, "showedDataSource", { get: function () { var self = this; var data = this.dataSource ? this.dataSource.findAll(function (d) { return self.value.find(function (a) { return self.valueCompare(a, self.GetItemValue(d)); }) == null }) : []; if (this.enableSearch && this.searchText.trim().length > 0) { var value = this.searchText.trim().toLowerCase(); data = data.findAll(function (item) { return item.toLowerCase().indexOf(value) >= 0 }) } this.totalRows = data.length; if (data.length > 0 && this.isLoadOnDemand) { data = data.slice(0, (this.page * this.pageSize)); } this.pageRows = data.length; return data; }, enumerable: true, configurable: true }); ExtendableObject.call(this, options); this.hoverIndex = -1; this.showDropdown = false; this.AddValue = function (item) { if (this.isLoading) return; var itemValue = this.GetItemValue(item); var itemDisplay = this.GetItemDisplay(item); if (this.multipleSelection) { var self = this; existing = this.dataSource ? this.dataSource.find(function (a) { return self.valueCompare(self.GetItemValue(a), itemValue); }) : null; if ((this.dataSource && existing) || !this.dataSource || this.allowNewValue) { var isExist = this.value.find(function (a) { return self.valueCompare(a, itemValue); }) != null; if (!isExist) { self.searchText = ""; this.value.push(itemValue); if (this.dataSource) this.dataSource.remove(existing); this.SelectedItem.push(itemDisplay); } if (typeof (this.valueOnchange) == "function") { this.valueOnchange(this.value, "add", itemValue, this); } } } else { if (this.SelectedItem != item) { this.SelectedItem = item; this.value = itemValue; this.searchText = itemDisplay; App.BindingService.TriggerChange(this, "dataSource"); if (typeof (this.valueOnchange) == "function") { this.valueOnchange(this.value, "set", null, this); } } } }; this.RemoveValue = function (item) { var itemValue = this.GetItemValue(item); var itemDisplay = this.GetItemDisplay(item); if (this.multipleSelection) { var self = this; var existing = this.value.find(function (a) { return self.valueCompare(a, itemValue); }); if (existing) { this.value.remove(existing); if (this.dataSource) this.dataSource.add(existing, 0); this.SelectedItem.remove(existing); self.searchText = ""; self.lastSearchText = ""; if (typeof (this.valueOnchange) == "function") { this.valueOnchange(this.value, "del", itemValue, this); } } } else { this.SelectedItem = null; this.value = null; if (typeof (this.valueOnchange) == "function") { this.valueOnchange(this.value, "set", null, this); } } }; this.GetItemValue = function (item) { var paths = this.valueField.split("."); var value = item; var prop = paths.pop(); if (prop) { for (var i = 0; i < paths.length && value; i++) { value = value[paths[i]]; } if (value) { value = value[prop]; } } return value; }; this.GetItemDisplay = function (item) { var paths = this.displayField.split("."); var value = item; var prop = paths.pop(); if (prop) { for (var i = 0; i < paths.length && value; i++) { value = value[paths[i]]; } if (value) { value = value[prop]; } } return value; }; this.Initialize = function () { this.element._rvModel = this; this.element.onclick = function () { var input = this.getElementsByTagName("input")[0]; input.focus(); EventManager.TriggerEvent(input, "focus"); } if (this.multipleSelection) { this.value = this.value ? this.value : []; this.SelectedItem = this.SelectedItem ? this.SelectedItem : []; } if (this.dataSource == null) { this.enableDataSource = false; } if (this.onInitialize) { this.onInitialize.call(this.element, this); } }; this.GetModel = function () { return this.element._rvModel; }; // event this.TagRemoveClick = function (event, model) { var root = model.GetModel(); root.RemoveValue(model.item); if (root._hideTO) { clearTimeout(root._hideTO); root._hideTO = null; } } this.SearchKeyup = function (event, model) { var model = model.GetModel(); if (!model.multipleSelection) return; var regexp = new RegExp("[" + model.separator + "]", "g"); var charCode = (typeof event.which == "number") ? event.which : event.keyCode; if (model.searchText.search(regexp) >= 0) { values = model.searchText.split(regexp); model.searchText = ""; if (values && values.length > 0) { values.each(function (value) { if (value.trim()) { model.AddValue(model.createValue(value.trim())); } }); } event.preventDefault(); if (charCode == 9) { this.focus(); } } //delete else if (charCode == 8 && !model.searchText) { if (model.__isDeleted && Array.isArray(model.value)) { var remValue = model.value[model.value.length - 1]; model.RemoveValue(remValue); model.__isDeleted = false; } else { model.__isDeleted = true; } } else { model.__isDeleted = false; } if (model.dataSourceProvider && (model.searchText !== model.lastSearchText || model.searchText)) { model.dataSource = []; model.isShowNewValue = model.isEmpty = false; model.isLoading = true; if (model.promise) { model.promise.abort(); model.promise = null; } var searchText = model.searchText; var callback = function (result) { model.isLoading = false; model.dataSource = result.findAll(function (n) { return model.value.find(function (a) { return model.valueCompare(a, model.GetItemValue(n)); }) == null; }); if (model.allowNewValue) model.isShowNewValue = searchText && result.find(function (n) { return model.GetItemDisplay(n) == searchText; }) == null; model.lastSearchText = searchText; model.isEmpty = !model.isShowNewValue && model.dataSource.length <= 0; }; model.promise = model.dataSourceProvider(model.searchText, model, callback); } }; this.SearchKeydown = function (event, model) { var model = model.GetModel(); if (!model.multipleSelection) return; var charCode = (typeof event.which == "number") ? event.which : event.keyCode; if (charCode == 13 || charCode == 9) { value = model.searchText.trim(); if (!value) return; if (!model.isLoading) { model.AddValue(model.createValue(value)); model.searchText = ""; } event.preventDefault(); if (charCode == 9) { this.focus(); } } else if (model.enableSearch && model.searchText.trim().length > 0) { App.BindingService.TriggerChange(model, "dataSource"); } }; this.ClickItem = function (event, model) { var rootModel = model.GetModel(); var itemValue = rootModel.GetItemValue(model.item); var isExist = (this.value || []).find(function (a) { return rootModel.valueCompare(a, itemValue); }) != null; if (rootModel.value && isExist) { rootModel.RemoveValue(model.item); } else { rootModel.AddValue(model.item); } if (rootModel._hideTO) { clearTimeout(rootModel._hideTO); rootModel._hideTO = null; } }; this.ClickNewItem = function (event, model) { var model = model.GetModel(); var value = model.searchText.trim(); if (!value) return; model.AddValue(model.createValue(value)); if (model._hideTO) { clearTimeout(model._hideTO); model._hideTO = null; } }; this.InputFocus = function (event, model) { var root = model.GetModel(); if (root.enableDropdown) { root.focus++; if (root._hideTO) clearTimeout(root._hideTO); if (root.dataSourceProvider && root.focus == 1 && (root.searchText !== root.lastSearchText || (!root.searchText && root._hideTO))) { root.dataSource = []; root._hideTO = null; root.isShowNewValue = root.isEmpty = false; root.isLoading = true; if (root.promise) { root.promise.abort(); root.promise = null; } var searchText = root.searchText.trim(); var callback = function (result) { root.isLoading = false; root.dataSource = result.findAll(function (n) { return root.value.find(function (a) { return root.valueCompare(a, root.GetItemValue(n)); }) == null; }); if (model.allowNewValue) root.isShowNewValue = searchText && result.find(function (n) { return root.GetItemDisplay(n) == searchText; }) == null; root.lastSearchText = searchText; root.isEmpty = !root.isShowNewValue && root.dataSource.length <= 0; }; root.promise = root.dataSourceProvider(root.searchText, root, callback); } root.showDropdown = true; } } this.InputBlur = function (event, model) { var root = model.GetModel(); root.focus = 0; if (root.addOnLostFocus) { var value = model.searchText.trim(); if (value) { root.AddValue(model.createValue(value)); root.searchText = ""; } } if (root.enableDropdown) { root._hideTO = setTimeout(function () { root.showDropdown = false; }, 200); } }; this.ItemHover = function (event, model) { var root = model.GetModel(); root.hoverIndex = root.dataSource.indexOf(model.item); }; this.DropdownScroll = function (event, model) { if (!model.isLoadOnDemand) return; var dropdownElement = model.element.childNodes[model.element.childNodes.length - 2]; if (dropdownElement.offsetHeight + dropdownElement.scrollTop >= dropdownElement.scrollHeight) { model.page++; App.BindingService.TriggerChange(model, "dataSource"); } }; this.Initialize(); } this.Context.components['modern-input'] = { static: [ 'multiSelection', 'valueField', 'displayField', 'separator', 'showDropdownButton', 'inputStyle', 'dropdownStyle', 'class', 'initialize' ], template: function () { var temp = this.locals(); var displayField = "item" + (temp.displayField && temp.displayField != "." ? "." + temp.displayField : ""); var valueField = "item" + (temp.valueField && temp.valueField != "." ? "." + temp.valueField : ""); var enableDropdown = temp.enableDropdown; var elstr = '{' + displayField + '}' + '' + (enableDropdown ? '' : ''); if (enableDropdown && temp.isLoadOnDemand) { elstr += ''; } return elstr; }, initialize: function (el, attributes) { attributes.element = el; var model = new ModernInputViewModel(attributes); return model; } }; }, TriggerChange: function (model, path) { var paths = path.split("."); var keypath = paths.pop(); for (var i = 0; i < paths.length; i++) { model = model[paths[i]]; } model[keypath]; // some computed property need this; for (var adapterKey in this.Context.adapters) { var adapter = this.Context.adapters[adapterKey]; if (map = adapter.weakmap[model[adapter.id]]) { callbacks = map.callbacks; if (callbacks[keypath]) { _ref1 = callbacks[keypath]; for (var _i = 0, _len = _ref1.length; _i < _len; _i++) { cb = _ref1[_i]; cb && cb(); } } } } }, Bindings: [ new WebComboBindingAdapter(), new WebInputBindingAdapter(), new CheckboxBindingAdapter(), new InitializeBindingAdapter(), new WebTextEditorBindingAdapter(), new HideAnimationBindingAdapter(), new StyleBindingAdapter(), new ShowAnimationBindingAdapter(), new ValidationBindingAdapter(), new TooltipBindingAdapter(), new CommandBindingAdapter(), new CommandIsProcessingBindingAdapter(), new CanExecuteCommandBindingAdapter(), new CommandParameterBindingAdapter(), new NumberBindingAdapter(), new TemplateBindingAdapter(), new AliasBindingAdapter(), new ImageBindingAdapter(), new AddClassAdapter() ] })); }, ToggleAppbar: function (forceShowRootAppbar) { if (this.NavigationService.NavigationTarget && !forceShowRootAppbar) { var frameAppbar = this.NavigationService.NavigationTarget.contentDocument.getElementById("frame-appbar"); if (frameAppbar && frameAppbar.innerHTML.trim()) { if (App.CurrentPage.constructor.name != "ReportPage") { App.AppBar.frameAppbarBinding = App.BindingService.Bind(frameAppbar, { AppBar: App.AppBar, Page: App.CurrentPage }); } setTimeout(function () { document.getElementById("appbar").classList.add("soft-hide"); if (App.CurrentPage.constructor.name == "ReportPage") { App.CurrentPage.UpdateActionButtonBar(); var exportButton = App.AppBar.SecondaryButtons.find(function (item) { return item.Name == "Export"; }); if (exportButton) { exportButton.Command.CanExecuteCommand = function (model, param) { return !(model.Page || model.PageModel).IsSummary; } } App.AppBar.frameAppbarBinding = App.BindingService.Bind(frameAppbar, { AppBar: App.AppBar, Page: App.CurrentPage }); } }, 300) return; } } document.getElementById("appbar").classList.remove("soft-hide"); if (App.AppBar.frameAppbarBinding) { App.BindingService.Unbind(App.AppBar.frameAppbarBinding); } }, ShowSidebar: function () { var sidebar = document.querySelector("aside.sidebar-left"); if (sidebar) sidebar.classList.add("open"); App.RootWindow.focus(); }, HideSidebar: function (event) { if (event && event.type === "blur") { App.IsBlurHide = true; event.stopPropagation(); event.returnValue = false; setTimeout(function () { App.IsBlurHide = false; }, 100); } var sidebar = document.querySelector("aside.sidebar-left"); if (sidebar) sidebar.classList.remove("open"); }, ToggleSidebar: function (event) { if (App.IsBlurHide) { App.IsBlurHide = false; return false; } var sidebar = document.querySelector("aside.sidebar-left"); if (sidebar) sidebar.classList.contains("open") ? App.HideSidebar() : App.ShowSidebar(); event.stopPropagation(); return false; }, GetNotification: function () { if (notifTO) notifTO = clearTimeout(notifTO); notifTO = setTimeout(function () { App.HttpService.Post("UserNotification", "GetNewNotifications", { since: lastNotificationDate }) .done(function (result) { if (result.IsSuccess) { lastNotificationDate = new Date(); for (var i = 0; i < result.Data.length; i++) { var notif = result.Data[i]; var model = {}; var source = {}; if (notif.Properties) { try { model = JSON.parse(notif.Properties); } catch (e) { } } if (notif.SourceProperties) { try { source = JSON.parse(notif.SourceProperties); } catch (e) { } } var buttons = [ new NotificationButton({ Name: "Close", Caption: App.Resources.Close }) ]; if (model.Actions) { buttons = model.Actions.findAll(function (o) { return !!o.Url; }).select(function (o) { return new NotificationButton({ Name: o.Name, Caption: o.Text, Url: o.Url }) }).concat(buttons); } var title = (source.Category || notif.Source).replace("module", "").split("_").select(function (o) { return o[0].toUpperCase() + o.substr(1); }).join(" ") + " Notification"; var notifOption = new NotificationOptions({ Type: notif.Type == "critical" ? "danger" : notif.Type, AutoClose: source.Category !== "background_process", Duration: source.Category === "background_process" ? -1 : 10000, Title: title, Text: notif.Message, Buttons: buttons }); App.NotificationService.Notify(notifOption).done(function (name) { var btn = notifOption.Buttons.find(function (btn) { return btn.Name === name; }); if (btn.Url) { setTimeout(function () { App.HttpService.Put("UserNotification", "MarkAsResponsed", { userNotificationId: notif.UserNotificationId }); }, 100); if (name === "DownloadFile") { App.RootWindow.location.href = btn.Url; return; } if (btn.Url == "/Catalog/Inventory") btn.Url = "/Catalog/Inventories"; else if (btn.Url == "/Settings/PointOfSale") btn.Url = "/Settings/PointOfSales"; App.NavigationService.Navigate(btn.Url); } }); } } }) .always(function () { App.GetNotification(); }); }, 30 * 1000); }, StopNotification: function () { if (notifTO) notifTO = clearTimeout(notifTO); }, OnAppReady: function () { this.AppBar.Breadcrumbs = []; this.NavigationService.NavigationTarget = document.getElementById("content-frame"); this.NavigationService.SiteMap = document.getElementById("_sitemap_node"); if (!this.NavigationService.CurrentNavigationItem) this.NavigationService.SetCurrentNavigationItem(); if (ISMaterialTheme) { ISMaterialTheme.RegisterAllBehaviour(); } if (App.Model.IsLoggedIn && !App.Model.IsDebug) this.GetNotification(); }, OpenLiveChat: function () { if (typeof (showIntercom) != "undefined") showIntercom(); else window.parent.showIntercom(); }, OpenLiveChatWithMessage: function (message) { if (typeof (showIntercomWithMessage) != "undefined") showIntercomWithMessage(message); else window.parent.showIntercomWithMessage(message); }, SendSystemMessage: function (message) { try { sendIntercomMessage("iseller-system@iseller.io", message); } catch (e) { } }, AppBar: { JumpModel: { __oldItem: {}, IsShow: false, Items: [], SelectedItem: null, SetJumpListWidth: function (width) { var jumplist = App.NavigationService.NavigationTarget.contentDocument.getElementsByClassName("jump-list"); if (jumplist.length > 0) { jumplist = jumplist[0]; jumplist.style.width = width; } }, OnSelectedChange: function (id, text, value) { if (App.CurrentPage && typeof (App.CurrentPage.OnItemChange) == "function") { App.CurrentPage.OnItemChange(unescape(text), value); } } }, SetTemplate: function (els) { if (!Array.isArray(els)) { els = [els]; } var navTemp = document.getElementById("nav-template"); navTemp.innerHTML = ""; for (var i = 0; i < els.length; i++) { if (els[i]) navTemp.appendChild(els[i]); } }, ClickBreadcrumb: function (event, model) { if (App.AppBar.Breadcrumbs.indexOf(model.bitem) < App.AppBar.Breadcrumbs.length - 1) { var navItem = new NavigationItem({ Url: model.bitem.Url, Parameter: model.bitem.Parameter, BreadcrumbTitles: [model.bitem.Title] }); App.GetService("NavigationService").Navigate(navItem); } }, SetBreadcrumb: function (items) { this.Breadcrumbs = []; for (var i = 0; i < items.length; i++) { var item = items[i]; App.AppBar.Breadcrumbs.push(new BreadcrumbItem({ Title: item.Title, Icon: item.Icon, Url: (i == items.length - 1) ? "" : item.Url })); } //this.BreadCrumb.Update(items); }, InitializeDropdown: function () { var dropdown = this; setTimeout(function () { new Dropdown(dropdown); }, 10); }, Breadcrumbs: [], SecondaryButtons: [], PrimaryButton: null, MaxShowedAction: 2 }, GetResourceString: function (key) { if (App.Resources && App.Resources.hasOwnProperty(key)) return App.Resources[key]; return key; }, FormatNumber: function (value, rounding, precision, format) { if ((["round", "ceil", "floor"]).indexOf(rounding) < 0) { rounding = "floor"; } if (isNaN(parseInt(precision)) && precision !== "") { precision = App.NumberFormat.Currency.Precision; } var numberFormat = "%v"; if (value < 0) { numberFormat = "-%v"; value = value * -1; } var roundedValue = value; if (!isNaN(parseInt(precision))) { var power = Math.pow(10, precision); roundedValue = Math[rounding](Math.round(value * power * 10) / 10) / power; } var valueSplit = App.ToFixedNumber(roundedValue).toString().split('.'); var thousandValue = valueSplit[0]; var decimalValue = valueSplit.length > 1 ? valueSplit[1] : ""; for (var gindex = 0, i = gsize = App.NumberFormat.Number.GroupSizes[0]; i < thousandValue.length; i = i + gsize) { var thousandValue = [thousandValue.slice(0, thousandValue.length - i), ",", thousandValue.slice(thousandValue.length - i)].join(''); i++; if (gindex < App.NumberFormat.Number.GroupSizes.length - 1) { gindex++; gsize = App.NumberFormat.Number.GroupSizes[gindex]; } } var result = thousandValue.replace(/,/ig, App.NumberFormat.Number.Thousand) + (decimalValue ? App.NumberFormat.Number.Decimal + decimalValue : ""); result = numberFormat.replace("%v", result); return result; }, FormatCurrency: function (value, rounding, precision, minLength, format) { if ((["round", "ceil", "floor"]).indexOf(rounding) < 0) { rounding = "floor"; } if (isNaN(parseInt(precision)) && precision !== "") { precision = App.NumberFormat.Currency.Precision; } var numberFormat = "%v"; var cformats = App.NumberFormat.Currency.Format; if (value > 0) { numberFormat = cformats.Pos; } else if (value < 0) { numberFormat = cformats.Neg; value = value * -1; } else { numberFormat = cformats.Zero; } var roundedValue = value; if (!isNaN(parseInt(precision))) { var power = Math.pow(10, precision); roundedValue = Math[rounding](value * power) / power; } var valueSplit = App.ToFixedNumber(roundedValue).toString().split('.'); var thousandValue = valueSplit[0]; var decimalValue = valueSplit.length > 1 ? valueSplit[1] : ""; for (var gindex = 0, i = gsize = App.NumberFormat.Currency.GroupSizes[0]; i < thousandValue.length; i = i + gsize) { var thousandValue = [thousandValue.slice(0, thousandValue.length - i), ",", thousandValue.slice(thousandValue.length - i)].join(''); i++; if (gindex < App.NumberFormat.Currency.GroupSizes.length - 1) { gindex++; gsize = App.NumberFormat.Currency.GroupSizes[gindex]; } } if (minLength && !isNaN(minLength)) { var spacelength = minLength - thousandValue.toString().length; if (spacelength > 0) { var space = ""; for (var i = 0; i < spacelength; i++) { space += " "; } numberFormat = numberFormat.replace("%s ", "%s " + space); } } var result = thousandValue.replace(/,/ig, App.NumberFormat.Currency.Thousand) + (decimalValue ? App.NumberFormat.Currency.Decimal + decimalValue : ""); result = numberFormat.replace("%v", result); result = result.replace("%s", App.NumberFormat.Currency.Symbol); return result; }, UnformatNumber: function (value) { value = value || 0; // Return the value as-is if it's already a number: if (typeof value === "number") return value; var isCurrency = ("" + value).indexOf(App.NumberFormat.Currency.Symbol) >= 0; // Default decimal point comes from settings, but could be set to eg. "," in opts: var decimal = App.NumberFormat[isCurrency ? "Number" : "Currency"].Decimal; var thousand = App.NumberFormat[isCurrency ? "Number" : "Currency"].Thousand; // Build regex to strip out everything except digits, decimal point and minus sign: var regex = new RegExp("[^0-9." + decimal + "]", ["g"]); var unformatted = ("" + value) .replace(regex, '') // strip out any cruft .replace(decimal, '.') // make sure decimal point is standard var negFormat = "-%v"; if (isCurrency) { var cformats = App.NumberFormat.Currency.Format; if (cformats.Neg != cformats.Pos && cformats.Neg != cformats.Zero) { negFormat = cformats.Neg; } } var negRegexp = new RegExp("^" + negFormat.replace(/(.)/g, "\\$1").replace(/\\%\\v/g, "[0-9" + decimal + thousand + "]+").replace(/\\%\\s/g, App.NumberFormat.Currency.Symbol) + "$", ["g"]); if (negRegexp.test("" + value) || (isCurrency && (new RegExp("^-[ ]*" + App.NumberFormat.Currency.Symbol + "[ ]*[0-9" + decimal + thousand + "]+[ ]*$", ["g"])).test(value + ""))) { unformatted = "-" + unformatted; } unformatted = parseFloat(unformatted); // This will fail silently which may cause trouble, let's wait and see: return !isNaN(unformatted) ? unformatted : 0; }, ToFixedNumber: function (x) { if (typeof x !== "number" || isNaN(x)) x = ""; if (Math.abs(x) < 1.0) { var e = parseInt(x.toString().split('e-')[1]); if (e) { x *= Math.pow(10, e - 1); x = '0.' + (new Array(e)).join('0') + x.toString().substring(2); } } else { var e = parseInt(x.toString().split('+')[1]); if (e > 20) { e -= 20; x /= Math.pow(10, e); x += (new Array(e + 1)).join('0'); } } return x; }, Round: function (x, precision) { if (!x) { return x; } return math.round(x, precision); } }); } window.App = app; } SetApp(); document.addEventListener("DOMContentLoaded", function () { // dropdown var dropdowns = document.querySelectorAll('[data-role="dropdown"]'); for (var i = 0; i < dropdowns.length; i++) { new Dropdown(dropdowns[i]); } MultiValueInput.prototype.Register(); }, false); // multi value tag input function MultiValueInput(el, options) { this.Element = (typeof (el) == "string" ? document.getElementById(el) : el); this.Id = ""; this.FrameStyle = "multi-control"; this.InputStyle = "multi-control-input"; this.ValueStyle = "selected-label"; this.Icon = "ios-close-empty"; this.CloseButtonStyle = "selected-label-close"; this.Separator = " "; this.Values = []; ExtendableObject.call(this, options); this.GetValue = function () { return this.Values; } this.Initialize = function () { this.Element.className += " " + this.FrameStyle; this.Id = this.Element.id; this.Textbox = document.createElement("input"); this.Textbox.className = this.InputStyle; if (this.Element.id) { this.Textbox.id = this.Element.id; this.Element.id = this.Element.id + "_multicontrol"; } this.Element.appendChild(this.Textbox); var value = this.Element.getAttribute("data-value"); var separator = this.Element.getAttribute("data-separator"); if (separator) this.Separator = separator; if (value) { var values = value.split(this.Separator); for (var i = 0; i < values.length; i++) { this.AddValue(values[i], false); } } this.RegisterBehavior(); if (window.IS && window.IS.RuntimeObjects) { window.IS.RuntimeObjects.push(this); } } this.RegisterBehavior = function () { var self = this; EventManager.RegisterEvent(this.Textbox, "keydown", function (e) { if (String.fromCharCode(e.keyCode) == self.Separator || e.keyCode == 13) { value = this.value.trim(); self.AddValue(value); this.value = ""; e.preventDefault(); } }); EventManager.RegisterEvent(this.Textbox, "focus", function (e) { self.Element.classList.add("focus"); }); EventManager.RegisterEvent(this.Textbox, "blur", function (e) { self.Element.classList.remove("focus"); }); EventManager.RegisterEvent(this.Element, "click", function (e) { self.Textbox.focus(); }); }; this.AddValue = function (value) { var self = this; this.Values.push(value); var el = document.createElement("span"); el.className = this.ValueStyle; el.style.opacity = 0; el.innerText = value; el.setAttribute("data-value", value); var closeEl = document.createElement("button"); closeEl.className = this.CloseButtonStyle; closeEl.type = "button"; closeEl.innerHTML = ''; el.appendChild(closeEl); this.Element.insertBefore(el, this.Textbox); EventManager.RegisterEvent(el, "click", function (e) { e.preventDefault(); }); AnimationService.SetAnimationProperty(el, { opacity: 1 }); EventManager.RegisterEvent(closeEl, "click", function (e) { value = this.getAttribute("data-value"); self.RemoveValue(value, this.parentElement); }) }; this.RemoveValue = function (value, el) { var self = this; var index = this.Values.indexOf(value); if (index >= 0) this.Values.splice(index, 1); el = el ? el : this.Element.querySelector("." + this.ValueStyle + "[data-value=" + value + "]"); if (el) { AnimationService.Hide(el, "animate-toggle", function (el) { el.parentElement.removeChild(el); EventManager.TriggerEvent(self.Textbox, "blur"); }, false); } } if (this.Element) { this.Initialize(); } } MultiValueInput.prototype.Selector = "[data-control='multi-input']"; MultiValueInput.prototype.Register = function () { var elements = document.querySelectorAll(MultiValueInput.prototype.Selector); for (var i = 0; i < elements.length; i++) { var item = new MultiValueInput(elements[i]); ISMaterialTheme.AddInputEffect(item.Textbox); } } // editable combo function editableComboLostFocus(id) { var combo = ISGetObject(id); if (!combo.IsEditable) return; if (combo.LastSelectedIndex == 0 && combo.SelectedIndex == 0) { var row = combo.GetRow(combo.SelectedIndex); if (row.IsNew) { combo.LastSelectedIndex = -1; } } } function editableComboNew(id) { var combo = ISGetObject(id); if (!combo.IsEditable) return; //if (!combo.ResultBoxShown) return; tdata = combo.GetTData(); var searchText = combo.TextObj.value; var pass = searchText == ""; if (!pass && combo.DataSourceInternal) { var exist = combo.DataSourceInternal.Rows.find(function (row) { return row.Cells.GetNamedItem(combo.DataTextField).Value == searchText }); pass = exist != null; } if (pass) { combo.__hasNewRow = false; if (combo.Rows.length > 0) { var comboRow = combo.Rows[0]; comboRow.IsNew = false; } combo.UpdateUI(); } else { var selectedrow = combo.GetSelectedRow(); if (selectedrow) combo.UnhighlightRow(selectedrow); combo.InsertAtTop = true; combo.__hasNewRow = true; combo.AddItem(searchText, searchText, null, true); WC40Engine.AddRowElement(combo, true); combo.InsertAtTop = false; combo.UpdateUI(); var comboRow = combo.Rows[0]; comboRow.Text = comboRow.Value = searchText; var cell = comboRow.GetCells().GetNamedItem(combo.DataTextField); cell.Text = cell.Value = searchText; comboRow._UIState = "Changed"; combo.UpdateUI(); comboRow = combo.Rows[0]; comboRow.IsNew = true; combo.LastSelectedIndex = combo.SelectedIndex = 0; WC40Engine.HighlightSelection(combo, comboRow.RowElement); } setTimeout(function () { for (var i = 0; i < combo.Rows.length; i++) { var row = combo.Rows[i]; var cells = row.GetCells(); // add actions var actionEl = cells.GetNamedItem("Action").GetElement(); actionEl.classList.add("text-right"); if (combo.__hasNewRow && i == 0) { actionEl.innerHTML = ''; } else { actionEl.innerHTML = ''; if (combo.DisableEdit) { actionEl.children[0].style.display = "none"; } else { actionEl.children[0].onmousedown = (function (rowObj) { return function () { editableComboEdit.call(Page, rowObj) }; }).call(this, row); } if (combo.DisableDelete) { actionEl.children[1].style.display = "none"; } else { actionEl.children[1].onmousedown = (function (rowObj) { return function () { editableComboDelete.call(Page, rowObj) }; }).call(this, row); } } } var emptyTemplate = combo.ResultBox._e.querySelector(".combo-empty-desc"); if (emptyTemplate == null) { var emptyTemplate = document.createElement("div"); emptyTemplate.className = "combo-empty-desc"; emptyTemplate.innerHTML = "

No items found.
Start typing to add a new item.

"; combo.ResultBox._e.firstChild.appendChild(emptyTemplate); combo.ResultBox._e.firstChild.style.position = "relative"; } if (combo.Rows.length <= 0) { emptyTemplate.classList.remove("hide"); } else { emptyTemplate.classList.add("hide"); } }, 600); } function editableComboItemSelected(id, text, value) { var combo = ISGetObject(id); if (!combo.IsEditable) return; var comboRow = combo.GetRow(combo.SelectedIndex); var entityType = combo.TextObj.getAttribute("entity-type"); if (comboRow) { if (comboRow.IsNew && !comboRow.__isShown) { comboRow.__isShown = true; if (typeof (combo.__oldValue) == "undefined") { combo.__oldValue = combo.Value ? combo.Value : ""; combo.__oldText = combo.Text ? combo.Text : ""; } var text = comboRow.GetTextData(); var defaultValue = combo.TextObj.getAttribute("entity-default"); var option = {}; if (defaultValue) { try { option = eval("(" + defaultValue + ")"); } catch (e) { } } option[combo.DataTextField] = text; var data = App.DataContext.DbSet(entityType).New(option, false); editableShowComboModal(data, combo); } } } function editableShowComboModal(model, combo) { var entityType = combo.TextObj.getAttribute("entity-type"); var modal = combo.TextObj.getAttribute("edit-modal"); var isAutoAdd = combo.TextObj.getAttribute("auto-add"); var isNew = model.IsNew; var saveButton = new DialogButton({ Caption: App.Resources.Save, Name: "SaveCommand", Type: "primary", }); var option = null; if (modal) { option = DialogOptions.GetModalOptions(modal); option.Buttons.unshift(new DialogButton({ Caption: App.Resources.Cancel, Name: "CancelCommand" })); saveButton.Command.CanExecuteCommand = function () { return model.IsDirty || isNew; } model.OnPropertyChanged = function (prop, oldValue, newValue) { if (prop == "IsDirty") { if (this.EntityAspect.EntityState != App.DataContext.EntityState.Added && this.EntityAspect.EntityState != App.DataContext.EntityState.Deleted) { if (newValue) this.EntityAspect.EntityState = App.DataContext.EntityState.Modified; else this.EntityAspect.EntityState = App.DataContext.EntityState.Unchanged; } } saveButton.Command.RaiseCanExecuteChange(); this.RemoveValidationState(prop); App.BindingService.TriggerChange(this, prop); } option.Buttons.push(saveButton); option.Model = model; option.Page = Page; } if (!option && !isAutoAdd) { isAutoAdd = true; } var isNoDialog = isNew && isAutoAdd && isAutoAdd.toLowerCase() == "true"; var coreSaveFn = function (data) { var command = saveButton.Command; command.IsProcessing = true; var promise = null; if (data.IsNew) { promise = App.HttpService.Insert(data); } else { promise = App.HttpService.Update(data); } promise.done(function (result) { if (result.IsSuccess) { data.AcceptChanges(); if (combo.Value == data[combo.DataValueField] || isNew) { combo.SetValue(data[combo.DataValueField]); combo.SetText(data[combo.DataTextField]); var selectedRowEl = combo.GetSelectedRow(); if (selectedRowEl && selectedRowEl.dataValue == data[combo.DataTextField]) { selectedRowEl.dataValue = data[combo.DataValueField]; } if (isNew) { data.__dbSet.Data.remove(data); data.__dbSet.DataDictionary[data.__dbSet.GeneratePrimaryKeys(data)] = undefined; } } var ds = combo.DataSource; if (Array.isArray(ds)) { if (isNew) { var newItem = {}; newItem[combo.DataValueField] = data[combo.DataValueField]; newItem[combo.DataTextField] = data[combo.DataTextField]; ds.push(newItem); combo.DataSource = ds; combo.Value = newItem[combo.DataValueField]; } else { var exist = ds.find(function (item) { return item[combo.DataValueField] == data[combo.DataValueField]; }); if (exist) { for (var prop in data) { exist[prop] = data[prop]; } combo.DataSource = ds; } } } combo.IsDirty = true; if (!isNoDialog) App.PresenterService.Dialog.Close(); } else { if (combo.__oldValue) { combo.Value = combo.__oldValue; combo.oldValue = null; } } }) .always(function () { command.IsProcessing = false; }); } if (isNoDialog) { var defaultValueFn = combo.TextObj.getAttribute("get-defaultvalue"); if (window[defaultValueFn]) { var defaultValue = window[defaultValueFn](); for (var prop in defaultValue) { model[prop] = defaultValue[prop]; } } coreSaveFn.call(saveButton.Command, model); } else { App.PresenterService.Dialog.Show(option).done(function (commandName, data, model, dialog) { var command = this; if (commandName == "SaveCommand") { coreSaveFn.call(command, data); } else { if (typeof (combo.__oldValue) != "undefined") { combo.SetValue(combo.__oldValue); combo.SetText(combo.__oldText); combo.__oldValue = undefined; combo.__oldText = undefined; } data.ResetChanges(); dialog.Close(); } }); } } function editableComboEdit(comboRow) { var entityType = comboRow.Combo.TextObj.getAttribute("entity-type"); this.HttpService.Find(entityType, comboRow.Value).done(function (result) { if (result.IsSuccess) { editableShowComboModal(result.Data, comboRow.Combo); } }); event.cancelBubble = true; event.returnValue = false; } function editableComboDelete(comboRow) { var entityType = comboRow.Combo.TextObj.getAttribute("entity-type"); var text = comboRow.GetTextData(); var confirmText = App.Resources.DeleteConfirm.formatString(text, entityType); this.PresenterService.Confirm.Show(confirmText) .done(function () { var combo = comboRow.Combo; var ds = comboRow.Combo.DataSource; if (ds) { var exist = ds.find(function (item) { return item[combo.DataValueField] == comboRow.Value; }); if (exist) { ds.remove(exist); combo.DataSource = ds; } } if (combo.Value == comboRow.Value) { combo.SetValue(""); combo.SetText(""); combo.LastSelectedIndex = combo.SelectedIndex = -1; } App.HttpService.Delete(entityType, comboRow.Value).done(function (result) { if (result.IsSuccess) { combo.IsDirty = true; } }); }); event.cancelBubble = true; event.returnValue = false; } function initializeEditableCombo(id) { var combo = ISGetObject(id); combo.IsEditable = true; combo.LayoutSettings.ClientSideEvents.OnBeforeItemSelected = "editableComboItemSelected"; combo.LayoutSettings.ClientSideEvents.OnShowDropDown = "editableComboNew"; combo.LayoutSettings.ClientSideEvents.OnLostFocus = "editableComboLostFocus"; combo.LayoutSettings.AlwaysShowColumnHeaders = false; combo.LayoutSettings.ComboMode = "MultipleColumns"; combo.LayoutSettings.StatusBoxVisible = false; var column = combo.Columns.GetNamedItem(combo.DataTextField); if (!column) { column = new WebComboColumn(); column.Name = column.BaseFieldName = combo.DataTextField; column.DataType = "System.String"; column.Width = "200px"; column.Bound = true; combo.Columns.Add(column); } column = combo.Columns.GetNamedItem("Action"); if (!column) { column = new WebComboColumn(); column.Name = column.BaseFieldName = "Action"; column.DataType = "System.String"; column.Width = "100%"; column.Bound = false; column.ColumnType = "Custom"; column.Width = "100px"; combo.Columns.Add(column); } var isDisableEdit = combo.TextObj.getAttribute("disable-edit"); if (isDisableEdit === "true") { combo.DisableEdit = true; } var isDisableDelete = combo.TextObj.getAttribute("disable-delete"); if (isDisableDelete === "true") { combo.DisableDelete = true; } } // allow not in list combo function AllowNotinListComboNew(id) { var combo = ISGetObject(id); tdata = combo.GetTData(); var searchText = combo.TextObj.value; var notNeedNewRow = searchText == ""; if (!notNeedNewRow) { var exist = combo.DataSource.find(function (item) { return item[combo.DataTextField] == searchText && !item.__isNew }); notNeedNewRow = exist != null; } if (notNeedNewRow) { // remove new item var newItem = combo.DataSource.find(function (item) { return item.__isNew; }); var newDataSource = combo.DataSource.concat([]); var index = combo.DataSource.indexOf(newItem); if (index >= 0) { var selectedrow = combo.GetSelectedRow(); if (selectedrow) combo.UnhighlightRow(selectedrow); var comboRow = combo.GetRow(index); newDataSource.remove(newItem); combo.DataSource = newDataSource; comboRow._UIState = "Removed"; combo.UpdateUI(); } } else { var comboRow = null; combo.__hasNewRow = true; var selectedrow = combo.GetSelectedRow(); if (selectedrow) combo.UnhighlightRow(selectedrow); var newItem = combo.DataSource.find(function (item) { return item.__isNew; }); if (!newItem) { newItem = { __isNew: true }; newItem[combo.DataTextField] = searchText; var newDataSource = combo.DataSource.concat([]); newDataSource.add(newItem, 0); combo.DataSource = newDataSource; combo.InsertAtTop = true; combo.__hasNewRow = true; combo.AddItem(searchText, searchText, null, true); combo.InsertAtTop = false; combo.UpdateUI(); comboRow = combo.GetRow(0); } else { var index = combo.DataSource.indexOf(newItem); comboRow = combo.GetRow(index); } newItem[combo.DataTextField] = searchText; comboRow.Text = comboRow.Value = searchText; var cell = comboRow.GetCells().GetNamedItem(combo.DataTextField); cell.Text = cell.Value = searchText; comboRow._UIState = "Changed"; comboRow.IsNew = true; combo.UpdateUI(); combo.LastSelectedIndex = combo.SelectedIndex = 0; WC40Engine.HighlightSelection(combo, comboRow.RowElement); combo.Value = searchText; combo.Text = searchText; } for (var i = 0; i < combo.Rows.length; i++) { var row = combo.Rows[i]; var cells = row.GetCells(); // add actions var actionEl = cells.GetNamedItem("Action").GetElement(); if (actionEl) { actionEl.classList.add("text-right"); if (combo.__hasNewRow && i == 0) { actionEl.innerHTML = ''; } } } var emptyTemplate = combo.ResultBox._e.querySelector(".combo-empty-desc"); if (emptyTemplate == null) { var emptyTemplate = document.createElement("div"); emptyTemplate.className = "combo-empty-desc"; emptyTemplate.innerHTML = "

No items found.
Start typing to add a new item.

"; combo.ResultBox._e.firstChild.appendChild(emptyTemplate); combo.ResultBox._e.firstChild.style.position = "relative"; } if (combo.Rows.length <= 0) { emptyTemplate.classList.remove("hide"); } else { emptyTemplate.classList.add("hide"); } } function initializeAllowNotinListCombo(id) { var combo = ISGetObject(id); combo.LayoutSettings.ClientSideEvents.OnShowDropDown = "AllowNotinListComboNew"; combo.LayoutSettings.AlwaysShowColumnHeaders = false; combo.LayoutSettings.ComboMode = "MultipleColumns"; combo.LayoutSettings.StatusBoxVisible = false; var column = combo.Columns.GetNamedItem(combo.DataTextField); if (!column) { column = new WebComboColumn(); column.Name = column.BaseFieldName = combo.DataTextField; column.DataType = "System.String"; column.Width = "200px"; column.Bound = true; combo.Columns.Add(column); } column = combo.Columns.GetNamedItem("Action"); if (!column) { column = new WebComboColumn(); column.Name = column.BaseFieldName = "Action"; column.DataType = "System.String"; column.Width = "100%"; column.Bound = false; column.ColumnType = "Custom"; column.Width = "100px"; combo.Columns.Add(column); } } // fileuploader function initializeUploader(controlId, b, c) { var imageUploader = ISGetObject(controlId); var clientEvents = imageUploader.ClientSideEvents; clientEvents.OnCompleted = "UploaderCompleted;" + (clientEvents.OnCompleted ? ";" + clientEvents.OnCompleted : ""); clientEvents.OnValidate = "UploaderValidate;" + (clientEvents.OnValidate ? ";" + clientEvents.OnValidate : ""); clientEvents.OnError = "UploaderError;" + (clientEvents.OnError ? ";" + clientEvents.OnError : ""); } function UploaderValidate(controlId, validateType, value, isSuccess) { var uploader = ISGetObject(controlId); if (!isSuccess) { var errorText = ""; switch (validateType) { case "ValidateByType": errorText = App.Resources.UploaderWrongType.formatString(uploader.FileTypes); break; case "ValidateByFileName": errorText = App.Resources.UploaderErrorFileName.formatString(value); break; default: errorText = App.Resources.ErrorMessageUploadSize.formatString(uploader.UploadSizeLimit); break; } var alert = new AlertOption({ Type: "danger", Text: errorText }); App.PresenterService.Confirm.Show(alert); } return isSuccess; } function UploaderError(controlId, fileInfo) { var uploader = ISGetObject(controlId); var message = fileInfo.ErrorMessage; if (message == "Upload size limit is reached") { var limit = ""; if (uploader.UploadSizeLimit >= 1048576) { limit = Math.floor(uploader.UploadSizeLimit / 1048576) + " MB"; } else if (uploader.UploadSizeLimit >= 1024) { limit = Math.floor(uploader.UploadSizeLimit / 1024) + " KB"; } else { limit = uploader.UploadSizeLimit + " B"; } message = App.Resources.ErrorMessageUploadSize.formatString(limit) } var alert = new AlertOption({ Type: "danger", Text: message }); App.PresenterService.Confirm.Show(alert); uploader.DoStartOver(); } function UploaderCompleted(controlId, fileInfo) { var uploader = ISGetObject(controlId); uploader.DoStartOver(); } adjustHeight = function (el) { el.style.overflow = "hidden"; el.style.height = ""; el.offsetHeight; el.style.height = el.scrollHeight + "px"; el.offsetHeight; el.style.height = el.scrollHeight + "px"; el.style.overflow = ""; } // common function for WebTextEditor function encodeHtml(text) { var map = { '&': '&', '<': '<', '>': '>' }; text = text.replace(/]*>.*?<\/script>/ig, ""); return text.replace(/[&<>]/g, function (m) { return map[m]; }); } function decodeHtml(text) { if (!text) return ""; var map = { '&': '&', '<': '<', '>': '>', }; var result = text; for (var key in map) { result = result.replace(new RegExp(map[key], "ig"), key); } return result; } //WEBTOUR function CloseWebTour() { $(App.RootWindow.document.body).children('.webtour-background').removeClass('active'); $(App.RootWindow.document.body).children('.webtour-background').css('pointer-events', 'none'); $(App.RootWindow.document.body).children('.webtour-overlay').css('pointer-events', 'none'); setTimeout(function () { $(App.RootWindow.document.body).children('.webtour-background').remove(); $(App.RootWindow.document.body).children('.webtour-overlay').remove(); }, 300); CookieManager.Set('WebTour', 'seen', 3650); } function CloseTokpedWebTour() { $(App.RootWindow.document.body).children('.webtour-background').removeClass('active'); $(App.RootWindow.document.body).children('.webtour-background').css('pointer-events', 'none'); $(App.RootWindow.document.body).children('.webtour-overlay').css('pointer-events', 'none'); setTimeout(function () { $(App.RootWindow.document.body).children('.webtour-background').remove(); $(App.RootWindow.document.body).children('.webtour-overlay').remove(); }, 300); CookieManager.Set('TokpedWebTour', 'seen', 3650); } function CloseListingTour() { $(App.RootWindow.document.body).children('.webtour-background').removeClass('active'); $(App.RootWindow.document.body).children('.webtour-background').css('pointer-events', 'none'); $(App.RootWindow.document.body).children('.webtour-overlay').css('pointer-events', 'none'); setTimeout(function () { $(App.RootWindow.document.body).children('.webtour-background').remove(); $(App.RootWindow.document.body).children('.webtour-overlay').remove(); }, 300); CookieManager.Set('ListingTour', 'seen', 3650); } function ToggleIntercom(el) { if ($(el).hasClass('active')) { $(el).removeClass('active'); Intercom('hide'); } else { $(el).addClass('active'); Intercom('show'); } } function RequestOTP(validPhone, option, storeid) { var key = CryptoJS.enc.Utf8.parse('8080808080808080'); var iv = CryptoJS.enc.Utf8.parse('8080808080808080'); var xsat = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(validPhone + ":" + Date.now() + ":" + storeid), key, { keySize: 128 / 8, iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); var headers = { 'X-SAT': xsat.toString() }; return App.HttpService.Post("identity", "requestOTP", { destination: validPhone, otpLength: option.OTPDigit }, null, null, null, headers) .done(function (result) { option.IsRequestingOTP = false; if (result.IsSuccess) { if (result.Data) { option.OTPCountdown = result.Data.CanRequestInSecond; option.StartCountDown(); } } else { var validationResult = option.Model.ValidationResult = option.Model.ValidationResult || new ValidationResultInfo(); validationResult.OTP = new FieldValidationResult({ IsSuccess: false, ErrorMessages: [result.Message] }); option.IsRequestingOTP = true; } }) .always(function () { option.RequestOTPCommand.RaiseCanExecuteChange(); }); }; /*! For license information please see math.js.LICENSE.txt */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.math=t():e.math=t()}(this,(()=>(()=>{var e={1977:function(e,t){var r;!function(n){"use strict";var i=Math.cosh||function(e){return Math.abs(e)<1e-9?1-e:.5*(Math.exp(e)+Math.exp(-e))},a=Math.sinh||function(e){return Math.abs(e)<1e-9?e:.5*(Math.exp(e)-Math.exp(-e))},o=function(){throw SyntaxError("Invalid Param")};function u(e,t){var r=Math.abs(e),n=Math.abs(t);return 0===e?Math.log(n):0===t?Math.log(r):r<3e3&&n<3e3?.5*Math.log(e*e+t*t):(e/=2,t/=2,.5*Math.log(e*e+t*t)+Math.LN2)}function s(e,t){if(!(this instanceof s))return new s(e,t);var r=function(e,t){var r={re:0,im:0};if(null==e)r.re=r.im=0;else if(void 0!==t)r.re=e,r.im=t;else switch(typeof e){case"object":if("im"in e&&"re"in e)r.re=e.re,r.im=e.im;else if("abs"in e&&"arg"in e){if(!Number.isFinite(e.abs)&&Number.isFinite(e.arg))return s.INFINITY;r.re=e.abs*Math.cos(e.arg),r.im=e.abs*Math.sin(e.arg)}else if("r"in e&&"phi"in e){if(!Number.isFinite(e.r)&&Number.isFinite(e.phi))return s.INFINITY;r.re=e.r*Math.cos(e.phi),r.im=e.r*Math.sin(e.phi)}else 2===e.length?(r.re=e[0],r.im=e[1]):o();break;case"string":r.im=r.re=0;var n=e.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g),i=1,a=0;null===n&&o();for(var u=0;u0&&o();break;case"number":r.im=0,r.re=e;break;default:o()}return isNaN(r.re)||isNaN(r.im),r}(e,t);this.re=r.re,this.im=r.im}s.prototype={re:0,im:0,sign:function(){var e=this.abs();return new s(this.re/e,this.im/e)},add:function(e,t){var r=new s(e,t);return this.isInfinite()&&r.isInfinite()?s.NAN:this.isInfinite()||r.isInfinite()?s.INFINITY:new s(this.re+r.re,this.im+r.im)},sub:function(e,t){var r=new s(e,t);return this.isInfinite()&&r.isInfinite()?s.NAN:this.isInfinite()||r.isInfinite()?s.INFINITY:new s(this.re-r.re,this.im-r.im)},mul:function(e,t){var r=new s(e,t);return this.isInfinite()&&r.isZero()||this.isZero()&&r.isInfinite()?s.NAN:this.isInfinite()||r.isInfinite()?s.INFINITY:0===r.im&&0===this.im?new s(this.re*r.re,0):new s(this.re*r.re-this.im*r.im,this.re*r.im+this.im*r.re)},div:function(e,t){var r=new s(e,t);if(this.isZero()&&r.isZero()||this.isInfinite()&&r.isInfinite())return s.NAN;if(this.isInfinite()||r.isZero())return s.INFINITY;if(this.isZero()||r.isInfinite())return s.ZERO;e=this.re,t=this.im;var n,i,a=r.re,o=r.im;return 0===o?new s(e/a,t/a):Math.abs(a)0)return new s(Math.pow(e,r.re),0);if(0===e)switch((r.re%4+4)%4){case 0:return new s(Math.pow(t,r.re),0);case 1:return new s(0,Math.pow(t,r.re));case 2:return new s(-Math.pow(t,r.re),0);case 3:return new s(0,-Math.pow(t,r.re))}}if(0===e&&0===t&&r.re>0&&r.im>=0)return s.ZERO;var n=Math.atan2(t,e),i=u(e,t);return e=Math.exp(r.re*i-r.im*n),t=r.im*i+r.re*n,new s(e*Math.cos(t),e*Math.sin(t))},sqrt:function(){var e,t,r=this.re,n=this.im,i=this.abs();if(r>=0){if(0===n)return new s(Math.sqrt(r),0);e=.5*Math.sqrt(2*(i+r))}else e=Math.abs(n)/Math.sqrt(2*(i-r));return t=r<=0?.5*Math.sqrt(2*(i-r)):Math.abs(n)/Math.sqrt(2*(i+r)),new s(e,n<0?-t:t)},exp:function(){var e=Math.exp(this.re);return this.im,new s(e*Math.cos(this.im),e*Math.sin(this.im))},expm1:function(){var e=this.re,t=this.im;return new s(Math.expm1(e)*Math.cos(t)+function(e){var t=Math.PI/4;if(-t>e||e>t)return Math.cos(e)-1;var r=e*e;return r*(r*(r*(r*(r*(r*(r*(r/20922789888e3-1/87178291200)+1/479001600)-1/3628800)+1/40320)-1/720)+1/24)-.5)}(t),Math.exp(e)*Math.sin(t))},log:function(){var e=this.re,t=this.im;return new s(u(e,t),Math.atan2(t,e))},abs:function(){return e=this.re,t=this.im,r=Math.abs(e),n=Math.abs(t),r<3e3&&n<3e3?Math.sqrt(r*r+n*n):(r1&&0===t,n=1-e,i=1+e,a=n*n+t*t,o=0!==a?new s((i*n-t*t)/a,(t*n+i*t)/a):new s(-1!==e?e/0:0,0!==t?t/0:0),c=o.re;return o.re=u(o.re,o.im)/2,o.im=Math.atan2(o.im,c)/2,r&&(o.im=-o.im),o},acoth:function(){var e=this.re,t=this.im;if(0===e&&0===t)return new s(0,Math.PI/2);var r=e*e+t*t;return 0!==r?new s(e/r,-t/r).atanh():new s(0!==e?e/0:0,0!==t?-t/0:0).atanh()},acsch:function(){var e=this.re,t=this.im;if(0===t)return new s(0!==e?Math.log(e+Math.sqrt(e*e+1)):1/0,0);var r=e*e+t*t;return 0!==r?new s(e/r,-t/r).asinh():new s(0!==e?e/0:0,0!==t?-t/0:0).asinh()},asech:function(){var e=this.re,t=this.im;if(this.isZero())return s.INFINITY;var r=e*e+t*t;return 0!==r?new s(e/r,-t/r).acosh():new s(0!==e?e/0:0,0!==t?-t/0:0).acosh()},inverse:function(){if(this.isZero())return s.INFINITY;if(this.isInfinite())return s.ZERO;var e=this.re,t=this.im,r=e*e+t*t;return new s(e/r,-t/r)},conjugate:function(){return new s(this.re,-this.im)},neg:function(){return new s(-this.re,-this.im)},ceil:function(e){return e=Math.pow(10,e||0),new s(Math.ceil(this.re*e)/e,Math.ceil(this.im*e)/e)},floor:function(e){return e=Math.pow(10,e||0),new s(Math.floor(this.re*e)/e,Math.floor(this.im*e)/e)},round:function(e){return e=Math.pow(10,e||0),new s(Math.round(this.re*e)/e,Math.round(this.im*e)/e)},equals:function(e,t){var r=new s(e,t);return Math.abs(r.re-this.re)<=s.EPSILON&&Math.abs(r.im-this.im)<=s.EPSILON},clone:function(){return new s(this.re,this.im)},toString:function(){var e=this.re,t=this.im,r="";return this.isNaN()?"NaN":this.isInfinite()?"Infinity":(Math.abs(e){var n=r(614),i=r(6330),a=TypeError;e.exports=function(e){if(n(e))return e;throw a(i(e)+" is not a function")}},9483:(e,t,r)=>{var n=r(4411),i=r(6330),a=TypeError;e.exports=function(e){if(n(e))return e;throw a(i(e)+" is not a constructor")}},6077:(e,t,r)=>{var n=r(614),i=String,a=TypeError;e.exports=function(e){if("object"==typeof e||n(e))return e;throw a("Can't set "+i(e)+" as a prototype")}},1223:(e,t,r)=>{var n=r(5112),i=r(30),a=r(3070).f,o=n("unscopables"),u=Array.prototype;null==u[o]&&a(u,o,{configurable:!0,value:i(null)}),e.exports=function(e){u[o][e]=!0}},1530:(e,t,r)=>{"use strict";var n=r(8710).charAt;e.exports=function(e,t,r){return t+(r?n(e,t).length:1)}},5787:(e,t,r)=>{var n=r(7976),i=TypeError;e.exports=function(e,t){if(n(t,e))return e;throw i("Incorrect invocation")}},9670:(e,t,r)=>{var n=r(111),i=String,a=TypeError;e.exports=function(e){if(n(e))return e;throw a(i(e)+" is not an object")}},7556:(e,t,r)=>{var n=r(7293);e.exports=n((function(){if("function"==typeof ArrayBuffer){var e=new ArrayBuffer(8);Object.isExtensible(e)&&Object.defineProperty(e,"a",{value:8})}}))},1285:(e,t,r)=>{"use strict";var n=r(7908),i=r(1400),a=r(6244);e.exports=function(e){for(var t=n(this),r=a(t),o=arguments.length,u=i(o>1?arguments[1]:void 0,r),s=o>2?arguments[2]:void 0,c=void 0===s?r:i(s,r);c>u;)t[u++]=e;return t}},8533:(e,t,r)=>{"use strict";var n=r(2092).forEach,i=r(9341)("forEach");e.exports=i?[].forEach:function(e){return n(this,e,arguments.length>1?arguments[1]:void 0)}},8457:(e,t,r)=>{"use strict";var n=r(9974),i=r(6916),a=r(7908),o=r(3411),u=r(7659),s=r(4411),c=r(6244),f=r(6135),l=r(4121),p=r(1246),m=Array;e.exports=function(e){var t=a(e),r=s(this),h=arguments.length,d=h>1?arguments[1]:void 0,v=void 0!==d;v&&(d=n(d,h>2?arguments[2]:void 0));var y,g,x,b,w,N,D=p(t),E=0;if(!D||this===m&&u(D))for(y=c(t),g=r?new this(y):m(y);y>E;E++)N=v?d(t[E],E):t[E],f(g,E,N);else for(w=(b=l(t,D)).next,g=r?new this:[];!(x=i(w,b)).done;E++)N=v?o(b,d,[x.value,E],!0):x.value,f(g,E,N);return g.length=E,g}},1318:(e,t,r)=>{var n=r(5656),i=r(1400),a=r(6244),o=function(e){return function(t,r,o){var u,s=n(t),c=a(s),f=i(o,c);if(e&&r!=r){for(;c>f;)if((u=s[f++])!=u)return!0}else for(;c>f;f++)if((e||f in s)&&s[f]===r)return e||f||0;return!e&&-1}};e.exports={includes:o(!0),indexOf:o(!1)}},2092:(e,t,r)=>{var n=r(9974),i=r(1702),a=r(8361),o=r(7908),u=r(6244),s=r(5417),c=i([].push),f=function(e){var t=1==e,r=2==e,i=3==e,f=4==e,l=6==e,p=7==e,m=5==e||l;return function(h,d,v,y){for(var g,x,b=o(h),w=a(b),N=n(d,v),D=u(w),E=0,A=y||s,S=t?A(h,D):r||p?A(h,0):void 0;D>E;E++)if((m||E in w)&&(x=N(g=w[E],E,b),e))if(t)S[E]=x;else if(x)switch(e){case 3:return!0;case 5:return g;case 6:return E;case 2:c(S,g)}else switch(e){case 4:return!1;case 7:c(S,g)}return l?-1:i||f?f:S}};e.exports={forEach:f(0),map:f(1),filter:f(2),some:f(3),every:f(4),find:f(5),findIndex:f(6),filterReject:f(7)}},1194:(e,t,r)=>{var n=r(7293),i=r(5112),a=r(7392),o=i("species");e.exports=function(e){return a>=51||!n((function(){var t=[];return(t.constructor={})[o]=function(){return{foo:1}},1!==t[e](Boolean).foo}))}},9341:(e,t,r)=>{"use strict";var n=r(7293);e.exports=function(e,t){var r=[][e];return!!r&&n((function(){r.call(null,t||function(){return 1},1)}))}},3671:(e,t,r)=>{var n=r(9662),i=r(7908),a=r(8361),o=r(6244),u=TypeError,s=function(e){return function(t,r,s,c){n(r);var f=i(t),l=a(f),p=o(f),m=e?p-1:0,h=e?-1:1;if(s<2)for(;;){if(m in l){c=l[m],m+=h;break}if(m+=h,e?m<0:p<=m)throw u("Reduce of empty array with no initial value")}for(;e?m>=0:p>m;m+=h)m in l&&(c=r(c,l[m],m,f));return c}};e.exports={left:s(!1),right:s(!0)}},3658:(e,t,r)=>{"use strict";var n=r(9781),i=r(3157),a=TypeError,o=Object.getOwnPropertyDescriptor,u=n&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(e){return e instanceof TypeError}}();e.exports=u?function(e,t){if(i(e)&&!o(e,"length").writable)throw a("Cannot set read only .length");return e.length=t}:function(e,t){return e.length=t}},1589:(e,t,r)=>{var n=r(1400),i=r(6244),a=r(6135),o=Array,u=Math.max;e.exports=function(e,t,r){for(var s=i(e),c=n(t,s),f=n(void 0===r?s:r,s),l=o(u(f-c,0)),p=0;c{var n=r(1702);e.exports=n([].slice)},4362:(e,t,r)=>{var n=r(1589),i=Math.floor,a=function(e,t){var r=e.length,s=i(r/2);return r<8?o(e,t):u(e,a(n(e,0,s),t),a(n(e,s),t),t)},o=function(e,t){for(var r,n,i=e.length,a=1;a0;)e[n]=e[--n];n!==a++&&(e[n]=r)}return e},u=function(e,t,r,n){for(var i=t.length,a=r.length,o=0,u=0;o{var n=r(3157),i=r(4411),a=r(111),o=r(5112)("species"),u=Array;e.exports=function(e){var t;return n(e)&&(t=e.constructor,(i(t)&&(t===u||n(t.prototype))||a(t)&&null===(t=t[o]))&&(t=void 0)),void 0===t?u:t}},5417:(e,t,r)=>{var n=r(7475);e.exports=function(e,t){return new(n(e))(0===t?0:t)}},3411:(e,t,r)=>{var n=r(9670),i=r(9212);e.exports=function(e,t,r,a){try{return a?t(n(r)[0],r[1]):t(r)}catch(t){i(e,"throw",t)}}},7072:(e,t,r)=>{var n=r(5112)("iterator"),i=!1;try{var a=0,o={next:function(){return{done:!!a++}},return:function(){i=!0}};o[n]=function(){return this},Array.from(o,(function(){throw 2}))}catch(e){}e.exports=function(e,t){if(!t&&!i)return!1;var r=!1;try{var a={};a[n]=function(){return{next:function(){return{done:r=!0}}}},e(a)}catch(e){}return r}},4326:(e,t,r)=>{var n=r(1702),i=n({}.toString),a=n("".slice);e.exports=function(e){return a(i(e),8,-1)}},648:(e,t,r)=>{var n=r(1694),i=r(614),a=r(4326),o=r(5112)("toStringTag"),u=Object,s="Arguments"==a(function(){return arguments}());e.exports=n?a:function(e){var t,r,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=u(e),o))?r:s?a(t):"Object"==(n=a(t))&&i(t.callee)?"Arguments":n}},5631:(e,t,r)=>{"use strict";var n=r(3070).f,i=r(30),a=r(9190),o=r(9974),u=r(5787),s=r(8554),c=r(408),f=r(1656),l=r(6178),p=r(6340),m=r(9781),h=r(2423).fastKey,d=r(9909),v=d.set,y=d.getterFor;e.exports={getConstructor:function(e,t,r,f){var l=e((function(e,n){u(e,p),v(e,{type:t,index:i(null),first:void 0,last:void 0,size:0}),m||(e.size=0),s(n)||c(n,e[f],{that:e,AS_ENTRIES:r})})),p=l.prototype,d=y(t),g=function(e,t,r){var n,i,a=d(e),o=x(e,t);return o?o.value=r:(a.last=o={index:i=h(t,!0),key:t,value:r,previous:n=a.last,next:void 0,removed:!1},a.first||(a.first=o),n&&(n.next=o),m?a.size++:e.size++,"F"!==i&&(a.index[i]=o)),e},x=function(e,t){var r,n=d(e),i=h(t);if("F"!==i)return n.index[i];for(r=n.first;r;r=r.next)if(r.key==t)return r};return a(p,{clear:function(){for(var e=d(this),t=e.index,r=e.first;r;)r.removed=!0,r.previous&&(r.previous=r.previous.next=void 0),delete t[r.index],r=r.next;e.first=e.last=void 0,m?e.size=0:this.size=0},delete:function(e){var t=this,r=d(t),n=x(t,e);if(n){var i=n.next,a=n.previous;delete r.index[n.index],n.removed=!0,a&&(a.next=i),i&&(i.previous=a),r.first==n&&(r.first=i),r.last==n&&(r.last=a),m?r.size--:t.size--}return!!n},forEach:function(e){for(var t,r=d(this),n=o(e,arguments.length>1?arguments[1]:void 0);t=t?t.next:r.first;)for(n(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!x(this,e)}}),a(p,r?{get:function(e){var t=x(this,e);return t&&t.value},set:function(e,t){return g(this,0===e?0:e,t)}}:{add:function(e){return g(this,e=0===e?0:e,e)}}),m&&n(p,"size",{get:function(){return d(this).size}}),l},setStrong:function(e,t,r){var n=t+" Iterator",i=y(t),a=y(n);f(e,t,(function(e,t){v(this,{type:n,target:e,state:i(e),kind:t,last:void 0})}),(function(){for(var e=a(this),t=e.kind,r=e.last;r&&r.removed;)r=r.previous;return e.target&&(e.last=r=r?r.next:e.state.first)?l("keys"==t?r.key:"values"==t?r.value:[r.key,r.value],!1):(e.target=void 0,l(void 0,!0))}),r?"entries":"values",!r,!0),p(t)}}},7710:(e,t,r)=>{"use strict";var n=r(2109),i=r(7854),a=r(1702),o=r(4705),u=r(8052),s=r(2423),c=r(408),f=r(5787),l=r(614),p=r(8554),m=r(111),h=r(7293),d=r(7072),v=r(8003),y=r(9587);e.exports=function(e,t,r){var g=-1!==e.indexOf("Map"),x=-1!==e.indexOf("Weak"),b=g?"set":"add",w=i[e],N=w&&w.prototype,D=w,E={},A=function(e){var t=a(N[e]);u(N,e,"add"==e?function(e){return t(this,0===e?0:e),this}:"delete"==e?function(e){return!(x&&!m(e))&&t(this,0===e?0:e)}:"get"==e?function(e){return x&&!m(e)?void 0:t(this,0===e?0:e)}:"has"==e?function(e){return!(x&&!m(e))&&t(this,0===e?0:e)}:function(e,r){return t(this,0===e?0:e,r),this})};if(o(e,!l(w)||!(x||N.forEach&&!h((function(){(new w).entries().next()})))))D=r.getConstructor(t,e,g,b),s.enable();else if(o(e,!0)){var S=new D,C=S[b](x?{}:-0,1)!=S,M=h((function(){S.has(1)})),F=d((function(e){new w(e)})),O=!x&&h((function(){for(var e=new w,t=5;t--;)e[b](t,t);return!e.has(-0)}));F||((D=t((function(e,t){f(e,N);var r=y(new w,e,D);return p(t)||c(t,r[b],{that:r,AS_ENTRIES:g}),r}))).prototype=N,N.constructor=D),(M||O)&&(A("delete"),A("has"),g&&A("get")),(O||C)&&A(b),x&&N.clear&&delete N.clear}return E[e]=D,n({global:!0,constructor:!0,forced:D!=w},E),v(D,e),x||r.setStrong(D,e,g),D}},9920:(e,t,r)=>{var n=r(2597),i=r(3887),a=r(1236),o=r(3070);e.exports=function(e,t,r){for(var u=i(t),s=o.f,c=a.f,f=0;f{var n=r(5112)("match");e.exports=function(e){var t=/./;try{"/./"[e](t)}catch(r){try{return t[n]=!1,"/./"[e](t)}catch(e){}}return!1}},8544:(e,t,r)=>{var n=r(7293);e.exports=!n((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}))},4230:(e,t,r)=>{var n=r(1702),i=r(4488),a=r(1340),o=/"/g,u=n("".replace);e.exports=function(e,t,r,n){var s=a(i(e)),c="<"+t;return""!==r&&(c+=" "+r+'="'+u(a(n),o,""")+'"'),c+">"+s+""}},6178:e=>{e.exports=function(e,t){return{value:e,done:t}}},8880:(e,t,r)=>{var n=r(9781),i=r(3070),a=r(9114);e.exports=n?function(e,t,r){return i.f(e,t,a(1,r))}:function(e,t,r){return e[t]=r,e}},9114:e=>{e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},6135:(e,t,r)=>{"use strict";var n=r(4948),i=r(3070),a=r(9114);e.exports=function(e,t,r){var o=n(t);o in e?i.f(e,o,a(0,r)):e[o]=r}},7045:(e,t,r)=>{var n=r(6339),i=r(3070);e.exports=function(e,t,r){return r.get&&n(r.get,t,{getter:!0}),r.set&&n(r.set,t,{setter:!0}),i.f(e,t,r)}},8052:(e,t,r)=>{var n=r(614),i=r(3070),a=r(6339),o=r(3072);e.exports=function(e,t,r,u){u||(u={});var s=u.enumerable,c=void 0!==u.name?u.name:t;if(n(r)&&a(r,c,u),u.global)s?e[t]=r:o(t,r);else{try{u.unsafe?e[t]&&(s=!0):delete e[t]}catch(e){}s?e[t]=r:i.f(e,t,{value:r,enumerable:!1,configurable:!u.nonConfigurable,writable:!u.nonWritable})}return e}},9190:(e,t,r)=>{var n=r(8052);e.exports=function(e,t,r){for(var i in t)n(e,i,t[i],r);return e}},3072:(e,t,r)=>{var n=r(7854),i=Object.defineProperty;e.exports=function(e,t){try{i(n,e,{value:t,configurable:!0,writable:!0})}catch(r){n[e]=t}return t}},5117:(e,t,r)=>{"use strict";var n=r(6330),i=TypeError;e.exports=function(e,t){if(!delete e[t])throw i("Cannot delete property "+n(t)+" of "+n(e))}},9781:(e,t,r)=>{var n=r(7293);e.exports=!n((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},4154:e=>{var t="object"==typeof document&&document.all,r=void 0===t&&void 0!==t;e.exports={all:t,IS_HTMLDDA:r}},317:(e,t,r)=>{var n=r(7854),i=r(111),a=n.document,o=i(a)&&i(a.createElement);e.exports=function(e){return o?a.createElement(e):{}}},7207:e=>{var t=TypeError;e.exports=function(e){if(e>9007199254740991)throw t("Maximum allowed index exceeded");return e}},8324:e=>{e.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},8509:(e,t,r)=>{var n=r(317)("span").classList,i=n&&n.constructor&&n.constructor.prototype;e.exports=i===Object.prototype?void 0:i},8886:(e,t,r)=>{var n=r(8113).match(/firefox\/(\d+)/i);e.exports=!!n&&+n[1]},7871:(e,t,r)=>{var n=r(3823),i=r(5268);e.exports=!n&&!i&&"object"==typeof window&&"object"==typeof document},3823:e=>{e.exports="object"==typeof Deno&&Deno&&"object"==typeof Deno.version},256:(e,t,r)=>{var n=r(8113);e.exports=/MSIE|Trident/.test(n)},1528:(e,t,r)=>{var n=r(8113),i=r(7854);e.exports=/ipad|iphone|ipod/i.test(n)&&void 0!==i.Pebble},6833:(e,t,r)=>{var n=r(8113);e.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(n)},5268:(e,t,r)=>{var n=r(4326),i=r(7854);e.exports="process"==n(i.process)},1036:(e,t,r)=>{var n=r(8113);e.exports=/web0s(?!.*chrome)/i.test(n)},8113:(e,t,r)=>{var n=r(5005);e.exports=n("navigator","userAgent")||""},7392:(e,t,r)=>{var n,i,a=r(7854),o=r(8113),u=a.process,s=a.Deno,c=u&&u.versions||s&&s.version,f=c&&c.v8;f&&(i=(n=f.split("."))[0]>0&&n[0]<4?1:+(n[0]+n[1])),!i&&o&&(!(n=o.match(/Edge\/(\d+)/))||n[1]>=74)&&(n=o.match(/Chrome\/(\d+)/))&&(i=+n[1]),e.exports=i},8008:(e,t,r)=>{var n=r(8113).match(/AppleWebKit\/(\d+)\./);e.exports=!!n&&+n[1]},748:e=>{e.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},2109:(e,t,r)=>{var n=r(7854),i=r(1236).f,a=r(8880),o=r(8052),u=r(3072),s=r(9920),c=r(4705);e.exports=function(e,t){var r,f,l,p,m,h=e.target,d=e.global,v=e.stat;if(r=d?n:v?n[h]||u(h,{}):(n[h]||{}).prototype)for(f in t){if(p=t[f],l=e.dontCallGetSet?(m=i(r,f))&&m.value:r[f],!c(d?f:h+(v?".":"#")+f,e.forced)&&void 0!==l){if(typeof p==typeof l)continue;s(p,l)}(e.sham||l&&l.sham)&&a(p,"sham",!0),o(r,f,p,e)}}},7293:e=>{e.exports=function(e){try{return!!e()}catch(e){return!0}}},7007:(e,t,r)=>{"use strict";r(4916);var n=r(1470),i=r(8052),a=r(2261),o=r(7293),u=r(5112),s=r(8880),c=u("species"),f=RegExp.prototype;e.exports=function(e,t,r,l){var p=u(e),m=!o((function(){var t={};return t[p]=function(){return 7},7!=""[e](t)})),h=m&&!o((function(){var t=!1,r=/a/;return"split"===e&&((r={}).constructor={},r.constructor[c]=function(){return r},r.flags="",r[p]=/./[p]),r.exec=function(){return t=!0,null},r[p](""),!t}));if(!m||!h||r){var d=n(/./[p]),v=t(p,""[e],(function(e,t,r,i,o){var u=n(e),s=t.exec;return s===a||s===f.exec?m&&!o?{done:!0,value:d(t,r,i)}:{done:!0,value:u(r,t,i)}:{done:!1}}));i(String.prototype,e,v[0]),i(f,p,v[1])}l&&s(f[p],"sham",!0)}},6677:(e,t,r)=>{var n=r(7293);e.exports=!n((function(){return Object.isExtensible(Object.preventExtensions({}))}))},2104:(e,t,r)=>{var n=r(4374),i=Function.prototype,a=i.apply,o=i.call;e.exports="object"==typeof Reflect&&Reflect.apply||(n?o.bind(a):function(){return o.apply(a,arguments)})},9974:(e,t,r)=>{var n=r(1470),i=r(9662),a=r(4374),o=n(n.bind);e.exports=function(e,t){return i(e),void 0===t?e:a?o(e,t):function(){return e.apply(t,arguments)}}},4374:(e,t,r)=>{var n=r(7293);e.exports=!n((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")}))},7065:(e,t,r)=>{"use strict";var n=r(1702),i=r(9662),a=r(111),o=r(2597),u=r(206),s=r(4374),c=Function,f=n([].concat),l=n([].join),p={},m=function(e,t,r){if(!o(p,t)){for(var n=[],i=0;i{var n=r(4374),i=Function.prototype.call;e.exports=n?i.bind(i):function(){return i.apply(i,arguments)}},6530:(e,t,r)=>{var n=r(9781),i=r(2597),a=Function.prototype,o=n&&Object.getOwnPropertyDescriptor,u=i(a,"name"),s=u&&"something"===function(){}.name,c=u&&(!n||n&&o(a,"name").configurable);e.exports={EXISTS:u,PROPER:s,CONFIGURABLE:c}},1470:(e,t,r)=>{var n=r(4326),i=r(1702);e.exports=function(e){if("Function"===n(e))return i(e)}},1702:(e,t,r)=>{var n=r(4374),i=Function.prototype,a=i.call,o=n&&i.bind.bind(a,a);e.exports=n?o:function(e){return function(){return a.apply(e,arguments)}}},5005:(e,t,r)=>{var n=r(7854),i=r(614),a=function(e){return i(e)?e:void 0};e.exports=function(e,t){return arguments.length<2?a(n[e]):n[e]&&n[e][t]}},1246:(e,t,r)=>{var n=r(648),i=r(8173),a=r(8554),o=r(7497),u=r(5112)("iterator");e.exports=function(e){if(!a(e))return i(e,u)||i(e,"@@iterator")||o[n(e)]}},4121:(e,t,r)=>{var n=r(6916),i=r(9662),a=r(9670),o=r(6330),u=r(1246),s=TypeError;e.exports=function(e,t){var r=arguments.length<2?u(e):t;if(i(r))return a(n(r,e));throw s(o(e)+" is not iterable")}},8173:(e,t,r)=>{var n=r(9662),i=r(8554);e.exports=function(e,t){var r=e[t];return i(r)?void 0:n(r)}},647:(e,t,r)=>{var n=r(1702),i=r(7908),a=Math.floor,o=n("".charAt),u=n("".replace),s=n("".slice),c=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,f=/\$([$&'`]|\d{1,2})/g;e.exports=function(e,t,r,n,l,p){var m=r+e.length,h=n.length,d=f;return void 0!==l&&(l=i(l),d=c),u(p,d,(function(i,u){var c;switch(o(u,0)){case"$":return"$";case"&":return e;case"`":return s(t,0,r);case"'":return s(t,m);case"<":c=l[s(u,1,-1)];break;default:var f=+u;if(0===f)return i;if(f>h){var p=a(f/10);return 0===p?i:p<=h?void 0===n[p-1]?o(u,1):n[p-1]+o(u,1):i}c=n[f-1]}return void 0===c?"":c}))}},7854:(e,t,r)=>{var n=function(e){return e&&e.Math==Math&&e};e.exports=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof r.g&&r.g)||function(){return this}()||Function("return this")()},2597:(e,t,r)=>{var n=r(1702),i=r(7908),a=n({}.hasOwnProperty);e.exports=Object.hasOwn||function(e,t){return a(i(e),t)}},3501:e=>{e.exports={}},842:(e,t,r)=>{var n=r(7854);e.exports=function(e,t){var r=n.console;r&&r.error&&(1==arguments.length?r.error(e):r.error(e,t))}},490:(e,t,r)=>{var n=r(5005);e.exports=n("document","documentElement")},4664:(e,t,r)=>{var n=r(9781),i=r(7293),a=r(317);e.exports=!n&&!i((function(){return 7!=Object.defineProperty(a("div"),"a",{get:function(){return 7}}).a}))},8361:(e,t,r)=>{var n=r(1702),i=r(7293),a=r(4326),o=Object,u=n("".split);e.exports=i((function(){return!o("z").propertyIsEnumerable(0)}))?function(e){return"String"==a(e)?u(e,""):o(e)}:o},9587:(e,t,r)=>{var n=r(614),i=r(111),a=r(7674);e.exports=function(e,t,r){var o,u;return a&&n(o=t.constructor)&&o!==r&&i(u=o.prototype)&&u!==r.prototype&&a(e,u),e}},2788:(e,t,r)=>{var n=r(1702),i=r(614),a=r(5465),o=n(Function.toString);i(a.inspectSource)||(a.inspectSource=function(e){return o(e)}),e.exports=a.inspectSource},2423:(e,t,r)=>{var n=r(2109),i=r(1702),a=r(3501),o=r(111),u=r(2597),s=r(3070).f,c=r(8006),f=r(1156),l=r(2050),p=r(9711),m=r(6677),h=!1,d=p("meta"),v=0,y=function(e){s(e,d,{value:{objectID:"O"+v++,weakData:{}}})},g=e.exports={enable:function(){g.enable=function(){},h=!0;var e=c.f,t=i([].splice),r={};r[d]=1,e(r).length&&(c.f=function(r){for(var n=e(r),i=0,a=n.length;i{var n,i,a,o=r(4811),u=r(7854),s=r(111),c=r(8880),f=r(2597),l=r(5465),p=r(6200),m=r(3501),h="Object already initialized",d=u.TypeError,v=u.WeakMap;if(o||l.state){var y=l.state||(l.state=new v);y.get=y.get,y.has=y.has,y.set=y.set,n=function(e,t){if(y.has(e))throw d(h);return t.facade=e,y.set(e,t),t},i=function(e){return y.get(e)||{}},a=function(e){return y.has(e)}}else{var g=p("state");m[g]=!0,n=function(e,t){if(f(e,g))throw d(h);return t.facade=e,c(e,g,t),t},i=function(e){return f(e,g)?e[g]:{}},a=function(e){return f(e,g)}}e.exports={set:n,get:i,has:a,enforce:function(e){return a(e)?i(e):n(e,{})},getterFor:function(e){return function(t){var r;if(!s(t)||(r=i(t)).type!==e)throw d("Incompatible receiver, "+e+" required");return r}}}},7659:(e,t,r)=>{var n=r(5112),i=r(7497),a=n("iterator"),o=Array.prototype;e.exports=function(e){return void 0!==e&&(i.Array===e||o[a]===e)}},3157:(e,t,r)=>{var n=r(4326);e.exports=Array.isArray||function(e){return"Array"==n(e)}},614:(e,t,r)=>{var n=r(4154),i=n.all;e.exports=n.IS_HTMLDDA?function(e){return"function"==typeof e||e===i}:function(e){return"function"==typeof e}},4411:(e,t,r)=>{var n=r(1702),i=r(7293),a=r(614),o=r(648),u=r(5005),s=r(2788),c=function(){},f=[],l=u("Reflect","construct"),p=/^\s*(?:class|function)\b/,m=n(p.exec),h=!p.exec(c),d=function(e){if(!a(e))return!1;try{return l(c,f,e),!0}catch(e){return!1}},v=function(e){if(!a(e))return!1;switch(o(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return h||!!m(p,s(e))}catch(e){return!0}};v.sham=!0,e.exports=!l||i((function(){var e;return d(d.call)||!d(Object)||!d((function(){e=!0}))||e}))?v:d},4705:(e,t,r)=>{var n=r(7293),i=r(614),a=/#|\.prototype\./,o=function(e,t){var r=s[u(e)];return r==f||r!=c&&(i(t)?n(t):!!t)},u=o.normalize=function(e){return String(e).replace(a,".").toLowerCase()},s=o.data={},c=o.NATIVE="N",f=o.POLYFILL="P";e.exports=o},8554:e=>{e.exports=function(e){return null==e}},111:(e,t,r)=>{var n=r(614),i=r(4154),a=i.all;e.exports=i.IS_HTMLDDA?function(e){return"object"==typeof e?null!==e:n(e)||e===a}:function(e){return"object"==typeof e?null!==e:n(e)}},1913:e=>{e.exports=!1},7850:(e,t,r)=>{var n=r(111),i=r(4326),a=r(5112)("match");e.exports=function(e){var t;return n(e)&&(void 0!==(t=e[a])?!!t:"RegExp"==i(e))}},2190:(e,t,r)=>{var n=r(5005),i=r(614),a=r(7976),o=r(3307),u=Object;e.exports=o?function(e){return"symbol"==typeof e}:function(e){var t=n("Symbol");return i(t)&&a(t.prototype,u(e))}},408:(e,t,r)=>{var n=r(9974),i=r(6916),a=r(9670),o=r(6330),u=r(7659),s=r(6244),c=r(7976),f=r(4121),l=r(1246),p=r(9212),m=TypeError,h=function(e,t){this.stopped=e,this.result=t},d=h.prototype;e.exports=function(e,t,r){var v,y,g,x,b,w,N,D=r&&r.that,E=!(!r||!r.AS_ENTRIES),A=!(!r||!r.IS_RECORD),S=!(!r||!r.IS_ITERATOR),C=!(!r||!r.INTERRUPTED),M=n(t,D),F=function(e){return v&&p(v,"normal",e),new h(!0,e)},O=function(e){return E?(a(e),C?M(e[0],e[1],F):M(e[0],e[1])):C?M(e,F):M(e)};if(A)v=e.iterator;else if(S)v=e;else{if(!(y=l(e)))throw m(o(e)+" is not iterable");if(u(y)){for(g=0,x=s(e);x>g;g++)if((b=O(e[g]))&&c(d,b))return b;return new h(!1)}v=f(e,y)}for(w=A?e.next:v.next;!(N=i(w,v)).done;){try{b=O(N.value)}catch(e){p(v,"throw",e)}if("object"==typeof b&&b&&c(d,b))return b}return new h(!1)}},9212:(e,t,r)=>{var n=r(6916),i=r(9670),a=r(8173);e.exports=function(e,t,r){var o,u;i(e);try{if(!(o=a(e,"return"))){if("throw"===t)throw r;return r}o=n(o,e)}catch(e){u=!0,o=e}if("throw"===t)throw r;if(u)throw o;return i(o),r}},3061:(e,t,r)=>{"use strict";var n=r(3383).IteratorPrototype,i=r(30),a=r(9114),o=r(8003),u=r(7497),s=function(){return this};e.exports=function(e,t,r,c){var f=t+" Iterator";return e.prototype=i(n,{next:a(+!c,r)}),o(e,f,!1,!0),u[f]=s,e}},1656:(e,t,r)=>{"use strict";var n=r(2109),i=r(6916),a=r(1913),o=r(6530),u=r(614),s=r(3061),c=r(9518),f=r(7674),l=r(8003),p=r(8880),m=r(8052),h=r(5112),d=r(7497),v=r(3383),y=o.PROPER,g=o.CONFIGURABLE,x=v.IteratorPrototype,b=v.BUGGY_SAFARI_ITERATORS,w=h("iterator"),N="keys",D="values",E="entries",A=function(){return this};e.exports=function(e,t,r,o,h,v,S){s(r,t,o);var C,M,F,O=function(e){if(e===h&&I)return I;if(!b&&e in _)return _[e];switch(e){case N:case D:case E:return function(){return new r(this,e)}}return function(){return new r(this)}},T=t+" Iterator",B=!1,_=e.prototype,k=_[w]||_["@@iterator"]||h&&_[h],I=!b&&k||O(h),R="Array"==t&&_.entries||k;if(R&&(C=c(R.call(new e)))!==Object.prototype&&C.next&&(a||c(C)===x||(f?f(C,x):u(C[w])||m(C,w,A)),l(C,T,!0,!0),a&&(d[T]=A)),y&&h==D&&k&&k.name!==D&&(!a&&g?p(_,"name",D):(B=!0,I=function(){return i(k,this)})),h)if(M={values:O(D),keys:v?I:O(N),entries:O(E)},S)for(F in M)(b||B||!(F in _))&&m(_,F,M[F]);else n({target:t,proto:!0,forced:b||B},M);return a&&!S||_[w]===I||m(_,w,I,{name:h}),d[t]=I,M}},3383:(e,t,r)=>{"use strict";var n,i,a,o=r(7293),u=r(614),s=r(111),c=r(30),f=r(9518),l=r(8052),p=r(5112),m=r(1913),h=p("iterator"),d=!1;[].keys&&("next"in(a=[].keys())?(i=f(f(a)))!==Object.prototype&&(n=i):d=!0),!s(n)||o((function(){var e={};return n[h].call(e)!==e}))?n={}:m&&(n=c(n)),u(n[h])||l(n,h,(function(){return this})),e.exports={IteratorPrototype:n,BUGGY_SAFARI_ITERATORS:d}},7497:e=>{e.exports={}},6244:(e,t,r)=>{var n=r(7466);e.exports=function(e){return n(e.length)}},6339:(e,t,r)=>{var n=r(7293),i=r(614),a=r(2597),o=r(9781),u=r(6530).CONFIGURABLE,s=r(2788),c=r(9909),f=c.enforce,l=c.get,p=Object.defineProperty,m=o&&!n((function(){return 8!==p((function(){}),"length",{value:8}).length})),h=String(String).split("String"),d=e.exports=function(e,t,r){"Symbol("===String(t).slice(0,7)&&(t="["+String(t).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),r&&r.getter&&(t="get "+t),r&&r.setter&&(t="set "+t),(!a(e,"name")||u&&e.name!==t)&&(o?p(e,"name",{value:t,configurable:!0}):e.name=t),m&&r&&a(r,"arity")&&e.length!==r.arity&&p(e,"length",{value:r.arity});try{r&&a(r,"constructor")&&r.constructor?o&&p(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(e){}var n=f(e);return a(n,"source")||(n.source=h.join("string"==typeof t?t:"")),e};Function.prototype.toString=d((function(){return i(this)&&l(this).source||s(this)}),"toString")},6736:e=>{var t=Math.expm1,r=Math.exp;e.exports=!t||t(10)>22025.465794806718||t(10)<22025.465794806718||-2e-17!=t(-2e-17)?function(e){var t=+e;return 0==t?t:t>-1e-6&&t<1e-6?t+t*t/2:r(t)-1}:t},403:e=>{var t=Math.log,r=Math.LOG10E;e.exports=Math.log10||function(e){return t(e)*r}},6513:e=>{var t=Math.log;e.exports=Math.log1p||function(e){var r=+e;return r>-1e-8&&r<1e-8?r-r*r/2:t(1+r)}},4310:e=>{e.exports=Math.sign||function(e){var t=+e;return 0==t||t!=t?t:t<0?-1:1}},4758:e=>{var t=Math.ceil,r=Math.floor;e.exports=Math.trunc||function(e){var n=+e;return(n>0?r:t)(n)}},5948:(e,t,r)=>{var n,i,a,o,u,s,c,f,l=r(7854),p=r(9974),m=r(1236).f,h=r(261).set,d=r(6833),v=r(1528),y=r(1036),g=r(5268),x=l.MutationObserver||l.WebKitMutationObserver,b=l.document,w=l.process,N=l.Promise,D=m(l,"queueMicrotask"),E=D&&D.value;E||(n=function(){var e,t;for(g&&(e=w.domain)&&e.exit();i;){t=i.fn,i=i.next;try{t()}catch(e){throw i?o():a=void 0,e}}a=void 0,e&&e.enter()},d||g||y||!x||!b?!v&&N&&N.resolve?((c=N.resolve(void 0)).constructor=N,f=p(c.then,c),o=function(){f(n)}):g?o=function(){w.nextTick(n)}:(h=p(h,l),o=function(){h(n)}):(u=!0,s=b.createTextNode(""),new x(n).observe(s,{characterData:!0}),o=function(){s.data=u=!u})),e.exports=E||function(e){var t={fn:e,next:void 0};a&&(a.next=t),i||(i=t,o()),a=t}},8523:(e,t,r)=>{"use strict";var n=r(9662),i=TypeError,a=function(e){var t,r;this.promise=new e((function(e,n){if(void 0!==t||void 0!==r)throw i("Bad Promise constructor");t=e,r=n})),this.resolve=n(t),this.reject=n(r)};e.exports.f=function(e){return new a(e)}},3929:(e,t,r)=>{var n=r(7850),i=TypeError;e.exports=function(e){if(n(e))throw i("The method doesn't accept regular expressions");return e}},2814:(e,t,r)=>{var n=r(7854),i=r(7293),a=r(1702),o=r(1340),u=r(3111).trim,s=r(1361),c=a("".charAt),f=n.parseFloat,l=n.Symbol,p=l&&l.iterator,m=1/f(s+"-0")!=-1/0||p&&!i((function(){f(Object(p))}));e.exports=m?function(e){var t=u(o(e)),r=f(t);return 0===r&&"-"==c(t,0)?-0:r}:f},3009:(e,t,r)=>{var n=r(7854),i=r(7293),a=r(1702),o=r(1340),u=r(3111).trim,s=r(1361),c=n.parseInt,f=n.Symbol,l=f&&f.iterator,p=/^[+-]?0x/i,m=a(p.exec),h=8!==c(s+"08")||22!==c(s+"0x16")||l&&!i((function(){c(Object(l))}));e.exports=h?function(e,t){var r=u(o(e));return c(r,t>>>0||(m(p,r)?16:10))}:c},30:(e,t,r)=>{var n,i=r(9670),a=r(6048),o=r(748),u=r(3501),s=r(490),c=r(317),f=r(6200)("IE_PROTO"),l=function(){},p=function(e){return"