forked from vitmalina/w2ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathw2ui-2.0.min.js
486 lines (486 loc) · 444 KB
/
w2ui-2.0.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/* w2ui 2.0.0 (4/26/2023, 10:40:17 AM) (c) http://w2ui.com, [email protected] */
class w2event{constructor(e,t){Object.assign(this,{type:t.type??null,detail:t,owner:e,target:t.target??null,phase:t.phase??"before",object:t.object??null,execute:null,isStopped:!1,isCancelled:!1,onComplete:null,listeners:[]}),delete t.type,delete t.target,delete t.object,this.complete=new Promise((e,t)=>{this._resolve=e,this._reject=t}),this.complete.catch(()=>{})}finish(e){e&&w2utils.extend(this.detail,e),this.phase="after",this.owner.trigger.call(this.owner,this)}done(e){this.listeners.push(e)}preventDefault(){this._reject(),this.isCancelled=!0}stopPropagation(){this.isStopped=!0}}class w2base{constructor(e){if(this.activeEvents=[],this.listeners=[],void 0!==e){if(!w2utils.checkName(e))return;w2ui[e]=this}this.debug=!1}on(e,r){return(e="string"==typeof e?e.split(/[,\s]+/):[e]).forEach(e=>{var t,i,s,l="string"==typeof e?e:e.type+":"+e.execute+"."+e.scope;"string"==typeof e&&([i,t]=e.split("."),[i,s]=i.replace(":complete",":after").replace(":done",":after").split(":"),e={type:i,execute:s??"before",scope:t}),(e=w2utils.extend({type:null,execute:"before",onComplete:null},e)).type?r?(Array.isArray(this.listeners)||(this.listeners=[]),this.listeners.push({name:l,edata:e,handler:r}),this.debug&&console.log("w2base: add event",{name:l,edata:e,handler:r})):console.log("ERROR: You must specify event handler function when calling .on() method of "+this.name):console.log("ERROR: You must specify event type when calling .on() method of "+this.name)}),this}off(e,r){return(e="string"==typeof e?e.split(/[,\s]+/):[e]).forEach(i=>{var e,t,s,l="string"==typeof i?i:i.type+":"+i.execute+"."+i.scope;if("string"==typeof i&&([t,e]=i.split("."),[t,s]=t.replace(":complete",":after").replace(":done",":after").split(":"),i={type:t||"*",execute:s||"",scope:e||""}),(i=w2utils.extend({type:null,execute:null,onComplete:null},i)).type||i.scope){r=r||null;let t=0;this.listeners=this.listeners.filter(e=>"*"!==i.type&&i.type!==e.edata.type||""!==i.execute&&i.execute!==e.edata.execute||""!==i.scope&&i.scope!==e.edata.scope||null!=i.handler&&i.handler!==e.edata.handler||(t++,!1)),this.debug&&console.log(`w2base: remove event (${t})`,{name:l,edata:i,handler:r})}else console.log("ERROR: You must specify event type when calling .off() method of "+this.name)}),this}trigger(e,i){if(1==arguments.length?i=e:(i.type=e,i.target=i.target??this),w2utils.isPlainObject(i)&&"after"==i.phase){if(!(i=this.activeEvents.find(e=>e.type==i.type&&e.target==i.target)))return void console.log(`ERROR: Cannot find even handler for "${i.type}" on "${i.target}".`);console.log("NOTICE: This syntax \"edata.trigger({ phase: 'after' })\" is outdated. Use edata.finish() instead.")}else i instanceof w2event||(i=new w2event(this,i),this.activeEvents.push(i));let s,t,l;Array.isArray(this.listeners)||(this.listeners=[]),this.debug&&console.log(`w2base: trigger "${i.type}:${i.phase}"`,i);for(let e=this.listeners.length-1;0<=e;e--){let t=this.listeners[e];if(!(null==t||t.edata.type!==i.type&&"*"!==t.edata.type||t.edata.target!==i.target&&null!=t.edata.target||t.edata.execute!==i.phase&&"*"!==t.edata.execute&&"*"!==t.edata.phase)&&(Object.keys(t.edata).forEach(e=>{null==i[e]&&null!=t.edata[e]&&(i[e]=t.edata[e])}),s=[],l=new RegExp(/\((.*?)\)/).exec(String(t.handler).split("=>")[0]),2===(s=l?l[1].split(/\s*,\s*/):s).length?(t.handler.call(this,i.target,i),this.debug&&console.log(" - call (old)",t.handler)):(t.handler.call(this,i),this.debug&&console.log(" - call",t.handler)),!0===i.isStopped||!0===i.stop))return i}e="on"+i.type.substr(0,1).toUpperCase()+i.type.substr(1);if(!("before"===i.phase&&"function"==typeof this[e]&&(t=this[e],s=[],l=new RegExp(/\((.*?)\)/).exec(String(t).split("=>")[0]),2===(s=l?l[1].split(/\s*,\s*/):s).length?(t.call(this,i.target,i),this.debug&&console.log(" - call: on[Event] (old)",t)):(t.call(this,i),this.debug&&console.log(" - call: on[Event]",t)),!0===i.isStopped||!0===i.stop)||null!=i.object&&"before"===i.phase&&"function"==typeof i.object[e]&&(t=i.object[e],s=[],l=new RegExp(/\((.*?)\)/).exec(String(t).split("=>")[0]),2===(s=l?l[1].split(/\s*,\s*/):s).length?(t.call(this,i.target,i),this.debug&&console.log(" - call: edata.object (old)",t)):(t.call(this,i),this.debug&&console.log(" - call: edata.object",t)),!0===i.isStopped||!0===i.stop)||"after"!==i.phase)){"function"==typeof i.onComplete&&i.onComplete.call(this,i);for(let e=0;e<i.listeners.length;e++)"function"==typeof i.listeners[e]&&(i.listeners[e].call(this,i),this.debug)&&console.log(" - call: done",t);i._resolve(i),this.debug&&console.log(`w2base: trigger "${i.type}:${i.phase}"`,i)}return i}}const w2locale={locale:"en-US",dateFormat:"m/d/yyyy",timeFormat:"hh:mi pm",datetimeFormat:"m/d/yyyy|hh:mi pm",currencyPrefix:"$",currencySuffix:"",currencyPrecision:2,groupSymbol:",",decimalSymbol:".",shortmonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],fullmonths:["January","February","March","April","May","June","July","August","September","October","November","December"],shortdays:["M","T","W","T","F","S","S"],fulldays:["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],weekStarts:"S",phrases:{"${count} letters or more...":"---","Add new record":"---","Add New":"---","Advanced Search":"---",after:"---","AJAX error. See console for more details.":"---","All Fields":"---",All:"---",Any:"---","Are you sure you want to delete ${count} ${records}?":"---","Attach files by dragging and dropping or Click to Select":"---",before:"---","begins with":"---",begins:"---",between:"---",buffered:"---",Cancel:"---",Close:"---",Column:"---",Confirmation:"---",contains:"---",Copied:"---","Copy to clipboard":"---","Current Date & Time":"---","Delete selected records":"---",Delete:"---",'Do you want to delete search item "${item}"?':"---","Edit selected record":"---",Edit:"---","Empty list":"---","ends with":"---",ends:"---","Field should be at least ${count} characters.":"---",Hide:"---",in:"---","is not":"---",is:"---","less than":"---","Line #":"---","Load ${count} more...":"---","Loading...":"---","Maximum number of files is ${count}":"---","Maximum total size is ${count}":"---",Modified:"---","more than":"---","Multiple Fields":"---",Name:"---","No items found":"---","No matches":"---",No:"---",none:"---","Not a float":"---","Not a hex number":"---","Not a valid date":"---","Not a valid email":"---","Not alpha-numeric":"---","Not an integer":"---","Not in money format":"---","not in":"---",Notification:"---",of:"---",Ok:"---",Opacity:"---","Record ID":"---",record:"---",records:"---","Refreshing...":"---","Reload data in the list":"---",Remove:"---","Remove This Field":"---","Request aborted.":"---","Required field":"---",Reset:"---","Restore Default State":"---","Returned data is not in valid JSON format.":"---","Save changed records":"---","Save Grid State":"---",Save:"---","Saved Searches":"---","Saving...":"---","Search took ${count} seconds":"---",Search:"---","Select Hour":"---","Select Minute":"---",selected:"---","Server Response ${count} seconds":"---","Show/hide columns":"---",Show:"---",Size:"---",Skip:"---","Sorting took ${count} seconds":"---","Type to search...":"---",Type:"---",Yes:"---",Yesterday:"---","Your remote data source record count has changed, reloading from the first record.":"---"}};class Query{static version=.7;constructor(e,t,i){this.context=t??document,this.previous=i??null;let s=[];if(Array.isArray(e))s=e;else if(e instanceof Node||e instanceof Window)s=[e];else if(e instanceof Query)s=e.nodes;else if("string"==typeof e){if("function"!=typeof this.context.querySelector)throw new Error("Invalid context");s=Array.from(this.context.querySelectorAll(e))}else if(null==e)s=[];else{t=Array.from(e??[]);if("object"!=typeof e||!Array.isArray(t))throw new Error(`Invalid selector "${e}"`);s=t}this.nodes=s,this.length=s.length,this.each((e,t)=>{this[t]=e})}static _fragment(e){let i=document.createElement("template");return i.innerHTML=e,i.content.childNodes.forEach(e=>{var t=Query._scriptConvert(e);t!=e&&i.content.replaceChild(t,e)}),i.content}static _scriptConvert(e){let t=e=>{var t=e.ownerDocument.createElement("script"),i=(t.text=e.text,e.attributes);for(let e=0;e<i.length;e++)t.setAttribute(i[e].name,i[e].value);return t};return(e="SCRIPT"==e.tagName?t(e):e).querySelectorAll&&e.querySelectorAll("script").forEach(e=>{e.parentNode.replaceChild(t(e),e)}),e}static _fixProp(e){var t={cellpadding:"cellPadding",cellspacing:"cellSpacing",class:"className",colspan:"colSpan",contenteditable:"contentEditable",for:"htmlFor",frameborder:"frameBorder",maxlength:"maxLength",readonly:"readOnly",rowspan:"rowSpan",tabindex:"tabIndex",usemap:"useMap"};return t[e]||e}_insert(l,i){let r=[],n=this.length;if(!(n<1)){let e=this;if("string"==typeof i)this.each(e=>{var t=Query._fragment(i);r.push(...t.childNodes),e[l](t)});else if(i instanceof Query){let s=1==n;i.each(i=>{this.each(e=>{var t=s?i:i.cloneNode(!0);r.push(t),e[l](t),Query._scriptConvert(t)})}),s||i.remove()}else{if(!(i instanceof Node))throw new Error(`Incorrect argument for "${l}(html)". It expects one string argument.`);this.each(e=>{var t=1===n?i:Query._fragment(i.outerHTML);r.push(...1===n?[i]:t.childNodes),e[l](t)}),1<n&&i.remove()}return e="replaceWith"==l?new Query(r,this.context,this):e}}_save(e,t,i){e._mQuery=e._mQuery??{},Array.isArray(i)?(e._mQuery[t]=e._mQuery[t]??[],e._mQuery[t].push(...i)):null!=i?e._mQuery[t]=i:delete e._mQuery[t]}get(e){var t=this[e=e<0?this.length+e:e];return t||(null!=e?null:this.nodes)}eq(e){let t=[this[e=e<0?this.length+e:e]];return null==t[0]&&(t=[]),new Query(t,this.context,this)}then(e){e=e(this);return null!=e?e:this}find(t){let i=[];return this.each(e=>{e=Array.from(e.querySelectorAll(t));0<e.length&&i.push(...e)}),new Query(i,this.context,this)}filter(t){let i=[];return this.each(e=>{(e===t||"string"==typeof t&&e.matches&&e.matches(t)||"function"==typeof t&&t(e))&&i.push(e)}),new Query(i,this.context,this)}next(){let t=[];return this.each(e=>{e=e.nextElementSibling;e&&t.push(e)}),new Query(t,this.context,this)}prev(){let t=[];return this.each(e=>{e=e.previousElementSibling;e&&t.push(e)}),new Query(t,this.context,this)}shadow(e){let t=[];this.each(e=>{e.shadowRoot&&t.push(e.shadowRoot)});var i=new Query(t,this.context,this);return e?i.find(e):i}closest(t){let i=[];return this.each(e=>{e=e.closest(t);e&&i.push(e)}),new Query(i,this.context,this)}host(t){let i=[],s=e=>e.parentNode?s(e.parentNode):e,l=e=>{e=s(e);i.push(e.host||e),e.host&&t&&l(e.host)};return this.each(e=>{l(e)}),new Query(i,this.context,this)}parent(e){return this.parents(e,!0)}parents(e,t){let i=[],s=e=>{if(-1==i.indexOf(e)&&i.push(e),!t&&e.parentNode)return s(e.parentNode)};this.each(e=>{e.parentNode&&s(e.parentNode)});var l=new Query(i,this.context,this);return e?l.filter(e):l}add(e){e=e instanceof Query?e.nodes:Array.isArray(e)?e:[e];return new Query(this.nodes.concat(e),this.context,this)}each(i){return this.nodes.forEach((e,t)=>{i(e,t,this)}),this}append(e){return this._insert("append",e)}prepend(e){return this._insert("prepend",e)}after(e){return this._insert("after",e)}before(e){return this._insert("before",e)}replace(e){return this._insert("replaceWith",e)}remove(){return this.each(e=>{e.remove()}),this}css(e,t){let s=e;var i,l=arguments.length;return 0===l||1===l&&"string"==typeof e?this[0]?(l=this[0].style,"string"==typeof e?(i=l.getPropertyPriority(e),l.getPropertyValue(e)+(i?"!"+i:"")):Object.fromEntries(this[0].style.cssText.split(";").filter(e=>!!e).map(e=>e.split(":").map(e=>e.trim())))):void 0:("object"!=typeof e&&((s={})[e]=t),this.each((i,e)=>{Object.keys(s).forEach(e=>{var t=String(s[e]).toLowerCase().includes("!important")?"important":"";i.style.setProperty(e,String(s[e]).replace(/\!important/i,""),t)})}),this)}addClass(e){return this.toggleClass(e,!0),this}removeClass(e){return this.toggleClass(e,!1),this}toggleClass(t,s){return"string"==typeof t&&(t=t.split(/[,\s]+/)),this.each(i=>{let e=t;(e=null==e&&!1===s?Array.from(i.classList):e).forEach(t=>{if(""!==t){let e=null!=s?s?"add":"remove":"toggle";i.classList[e](t)}})}),this}hasClass(e){if(null==(e="string"==typeof e?e.split(/[,\s]+/):e)&&0<this.length)return Array.from(this[0].classList);let i=!1;return this.each(t=>{i=i||e.every(e=>Array.from(t.classList??[]).includes(e))}),i}on(e,s,l){"function"==typeof s&&(l=s,s=void 0);let r;return s?.delegate&&(r=s.delegate,delete s.delegate),(e=e.split(/[,\s]+/)).forEach(e=>{let[t,i]=String(e).toLowerCase().split(".");if(r){let i=l;l=e=>{var t=query(e.target).parents(r);0<t.length?e.delegate=t[0]:e.delegate=e.target,(e.target.matches(r)||0<t.length)&&i(e)}}this.each(e=>{this._save(e,"events",[{event:t,scope:i,callback:l,options:s}]),e.addEventListener(t,l,s)})}),this}off(e,t,r){return"function"==typeof t&&(r=t,t=void 0),(e=(e??"").split(/[,\s]+/)).forEach(e=>{let[s,l]=String(e).toLowerCase().split(".");this.each(t=>{if(Array.isArray(t._mQuery?.events))for(let e=t._mQuery.events.length-1;0<=e;e--){var i=t._mQuery.events[e];null==l||""===l?i.event!=s&&""!==s||i.callback!=r&&null!=r||(t.removeEventListener(i.event,i.callback,i.options),t._mQuery.events.splice(e,1)):i.event!=s&&""!==s||i.scope!=l||(t.removeEventListener(i.event,i.callback,i.options),t._mQuery.events.splice(e,1))}})}),this}trigger(e,t){let i;return i=e instanceof Event||e instanceof CustomEvent?e:new(["click","dblclick","mousedown","mouseup","mousemove"].includes(e)?MouseEvent:["keydown","keyup","keypress"].includes(e)?KeyboardEvent:Event)(e,t),this.each(e=>{e.dispatchEvent(i)}),this}attr(t,i){if(void 0===i&&"string"==typeof t)return this[0]?this[0].getAttribute(t):void 0;{let e={};return"object"==typeof t?e=t:e[t]=i,this.each(i=>{Object.entries(e).forEach(([e,t])=>{i.setAttribute(e,t)})}),this}}removeAttr(){return this.each(t=>{Array.from(arguments).forEach(e=>{t.removeAttribute(e)})}),this}prop(t,i){if(void 0===i&&"string"==typeof t)return this[0]?this[0][t]:void 0;{let e={};return"object"==typeof t?e=t:e[t]=i,this.each(i=>{Object.entries(e).forEach(([e,t])=>{e=Query._fixProp(e);i[e]=t,"innerHTML"==e&&Query._scriptConvert(i)})}),this}}removeProp(){return this.each(t=>{Array.from(arguments).forEach(e=>{delete t[Query._fixProp(e)]})}),this}data(i,t){if(i instanceof Object)Object.entries(i).forEach(e=>{this.data(e[0],e[1])});else{if(i&&-1!=i.indexOf("-")&&console.error(`Key "${i}" contains "-" (dash). Dashes are not allowed in property names. Use camelCase instead.`),!(arguments.length<2))return this.each(e=>{null!=t?e.dataset[i]=t instanceof Object?JSON.stringify(t):t:delete e.dataset[i]}),this;if(this[0]){let t=Object.assign({},this[0].dataset);return Object.keys(t).forEach(e=>{if(t[e].startsWith("[")||t[e].startsWith("{"))try{t[e]=JSON.parse(t[e])}catch(e){}}),i?t[i]:t}}}removeData(e){return"string"==typeof e&&(e=e.split(/[,\s]+/)),this.each(t=>{e.forEach(e=>{delete t.dataset[e]})}),this}show(){return this.toggle(!0)}hide(){return this.toggle(!1)}toggle(r){return this.each(e=>{var t,i=e.style.display,s=getComputedStyle(e).display,l="none"==i||"none"==s;!l||null!=r&&!0!==r||(t=e instanceof HTMLTableRowElement?"table-row":e instanceof HTMLTableCellElement?"table-cell":"block",e.style.display=e._mQuery?.prevDisplay??(i==s&&"none"!=s?"":t),this._save(e,"prevDisplay",null)),l||null!=r&&!1!==r||("none"!=s&&this._save(e,"prevDisplay",s),e.style.setProperty("display","none"))})}empty(){return this.html("")}html(e){return this.prop("innerHTML",e)}text(e){return this.prop("textContent",e)}val(e){return this.prop("value",e)}change(){return this.trigger("change")}click(){return this.trigger("click")}}let query=function(e,t){if("function"!=typeof e)return new Query(e,t);"complete"==document.readyState?e():window.addEventListener("load",e)},w2ui=(query.html=e=>{e=Query._fragment(e);return query(e.children,e)},query.version=Query.version,{});class Utils{constructor(){this.version="2.0.x",this.tmp={},this.settings=this.extend({},{dataType:"HTTPJSON",dateStartYear:1950,dateEndYear:2030,macButtonOrder:!1,warnNoPhrase:!1},w2locale,{phrases:null}),this.i18nCompare=Intl.Collator().compare,this.hasLocalStorage=function(){var e="w2ui_test";try{return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch(e){return!1}}(),this.isMac=/Mac/i.test(navigator.platform),this.isMobile=/(iphone|ipod|ipad|mobile|android)/i.test(navigator.userAgent),this.isIOS=/(iphone|ipod|ipad)/i.test(navigator.platform),this.isAndroid=/(android)/i.test(navigator.userAgent),this.isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this.formatters={number(e,t){return 20<parseInt(t)&&(t=20),parseInt(t)<0&&(t=0),null==e||""===e?"":w2utils.formatNumber(parseFloat(e),t,!0)},float(e,t){return w2utils.formatters.number(e,t)},int(e,t){return w2utils.formatters.number(e,0)},money(e,t){return null==e||""===e?"":(e=w2utils.formatNumber(Number(e),w2utils.settings.currencyPrecision),(w2utils.settings.currencyPrefix||"")+e+(w2utils.settings.currencySuffix||""))},currency(e,t){return w2utils.formatters.money(e,t)},percent(e,t){return null==e||""===e?"":w2utils.formatNumber(e,t||1)+"%"},size(e,t){return null==e||""===e?"":w2utils.formatSize(parseInt(e))},date(e,t){if(""===t&&(t=w2utils.settings.dateFormat),null==e||0===e||""===e)return"";let i=w2utils.isDateTime(e,t,!0);return'<span title="'+(i=!1===i?w2utils.isDate(e,t,!0):i)+'">'+w2utils.formatDate(i,t)+"</span>"},datetime(e,t){if(""===t&&(t=w2utils.settings.datetimeFormat),null==e||0===e||""===e)return"";let i=w2utils.isDateTime(e,t,!0);return'<span title="'+(i=!1===i?w2utils.isDate(e,t,!0):i)+'">'+w2utils.formatDateTime(i,t)+"</span>"},time(e,t){if(""===t&&(t=w2utils.settings.timeFormat),null==e||0===e||""===e)return"";let i=w2utils.isDateTime(e,t="h24"===(t="h12"===t?"hh:mi pm":t)?"h24:mi":t,!0);return'<span title="'+(i=!1===i?w2utils.isDate(e,t,!0):i)+'">'+w2utils.formatTime(e,t)+"</span>"},timestamp(e,t){if(""===t&&(t=w2utils.settings.datetimeFormat),null==e||0===e||""===e)return"";let i=w2utils.isDateTime(e,t,!0);return(i=!1===i?w2utils.isDate(e,t,!0):i).toString?i.toString():""},gmt(e,t){if(""===t&&(t=w2utils.settings.datetimeFormat),null==e||0===e||""===e)return"";let i=w2utils.isDateTime(e,t,!0);return(i=!1===i?w2utils.isDate(e,t,!0):i).toUTCString?i.toUTCString():""},age(e,t){if(null==e||0===e||""===e)return"";let i=w2utils.isDateTime(e,null,!0);return'<span title="'+(i=!1===i?w2utils.isDate(e,null,!0):i)+'">'+w2utils.age(e)+(t?" "+t:"")+"</span>"},interval(e,t){return null==e||0===e||""===e?"":w2utils.interval(e)+(t?" "+t:"")},toggle(e,t){return e?"Yes":""},password(t,e){let i="";for(let e=0;e<t.length;e++)i+="*";return i}}}isBin(e){return/^[0-1]+$/.test(e)}isInt(e){return/^[-+]?[0-9]+$/.test(e)}isFloat(e){return("number"==typeof(e="string"==typeof e?e.replace(this.settings.groupSymbol,"").replace(this.settings.decimalSymbol,"."):e)||"string"==typeof e&&""!==e)&&!isNaN(Number(e))}isMoney(e){var t,i;return"object"!=typeof e&&""!==e&&(!!this.isFloat(e)||(t=this.settings,i=new RegExp("^"+(t.currencyPrefix?"\\"+t.currencyPrefix+"?":"")+"[-+]?"+(t.currencyPrefix?"\\"+t.currencyPrefix+"?":"")+"[0-9]*[\\"+t.decimalSymbol+"]?[0-9]+"+(t.currencySuffix?"\\"+t.currencySuffix+"?":"")+"$","i"),"string"==typeof e&&(e=e.replace(new RegExp(t.groupSymbol,"g"),"")),i.test(e)))}isHex(e){return/^(0x)?[0-9a-fA-F]+$/.test(e)}isAlphaNumeric(e){return/^[a-zA-Z0-9_-]+$/.test(e)}isEmail(e){return/^[a-zA-Z0-9._%\-+]+@[а-яА-Яa-zA-Z0-9.-]+\.[а-яА-Яa-zA-Z]+$/.test(e)}isIpAddress(e){return new RegExp("^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$").test(e)}isDate(i,e,t){if(!i)return!1;var s="Invalid Date";let l,r,n;if(null==e&&(e=this.settings.dateFormat),"function"==typeof i.getFullYear)n=i.getFullYear(),l=i.getMonth()+1,r=i.getDate();else if(parseInt(i)==i&&0<parseInt(i))i=new Date(parseInt(i)),n=i.getFullYear(),l=i.getMonth()+1,r=i.getDate();else{if(i=String(i),new RegExp("mon","ig").test(e)){e=e.replace(/month/gi,"m").replace(/mon/gi,"m").replace(/dd/gi,"d").replace(/[, ]/gi,"/").replace(/\/\//g,"/").toLowerCase(),i=i.replace(/[, ]/gi,"/").replace(/\/\//g,"/").toLowerCase();for(let e=0,t=this.settings.fullmonths.length;e<t;e++){var a=this.settings.fullmonths[e];i=i.replace(new RegExp(a,"ig"),parseInt(e)+1).replace(new RegExp(a.substr(0,3),"ig"),parseInt(e)+1)}}var o=i.replace(/-/g,"/").replace(/\./g,"/").toLowerCase().split("/"),e=e.replace(/-/g,"/").replace(/\./g,"/").toLowerCase();"mm/dd/yyyy"===e&&(l=o[0],r=o[1],n=o[2]),"m/d/yyyy"===e&&(l=o[0],r=o[1],n=o[2]),"dd/mm/yyyy"===e&&(l=o[1],r=o[0],n=o[2]),"d/m/yyyy"===e&&(l=o[1],r=o[0],n=o[2]),"yyyy/dd/mm"===e&&(l=o[2],r=o[1],n=o[0]),"yyyy/d/m"===e&&(l=o[2],r=o[1],n=o[0]),"yyyy/mm/dd"===e&&(l=o[1],r=o[2],n=o[0]),"yyyy/m/d"===e&&(l=o[1],r=o[2],n=o[0]),"mm/dd/yy"===e&&(l=o[0],r=o[1],n=o[2]),"m/d/yy"===e&&(l=o[0],r=o[1],n=parseInt(o[2])+1900),"dd/mm/yy"===e&&(l=o[1],r=o[0],n=parseInt(o[2])+1900),"d/m/yy"===e&&(l=o[1],r=o[0],n=parseInt(o[2])+1900),"yy/dd/mm"===e&&(l=o[2],r=o[1],n=parseInt(o[0])+1900),"yy/d/m"===e&&(l=o[2],r=o[1],n=parseInt(o[0])+1900),"yy/mm/dd"===e&&(l=o[1],r=o[2],n=parseInt(o[0])+1900),"yy/m/d"===e&&(l=o[1],r=o[2],n=parseInt(o[0])+1900)}return!!this.isInt(n)&&!!this.isInt(l)&&!!this.isInt(r)&&(n=+n,l=+l,r=+r,(s=new Date(n,l-1,r)).setFullYear(n),null!=l)&&"Invalid Date"!==String(s)&&s.getMonth()+1===l&&s.getDate()===r&&s.getFullYear()===n&&(!0!==t||s)}isTime(e,t){if(null==e)return!1;let i,s,l;s=0<=(e=(e=String(e)).toUpperCase()).indexOf("AM");var r=(l=0<=e.indexOf("PM"))||s,e=(i=r?12:24,(e=e.replace("AM","").replace("PM","").trim()).split(":"));let n=parseInt(e[0]||0),a=parseInt(e[1]||0),o=parseInt(e[2]||0);return(r&&1===e.length||2===e.length||3===e.length)&&!(""===e[0]||n<0||n>i||!this.isInt(e[0])||2<e[0].length||1<e.length&&(""===e[1]||a<0||59<a||!this.isInt(e[1])||2!==e[1].length)||2<e.length&&(""===e[2]||o<0||59<o||!this.isInt(e[2])||2!==e[2].length)||!(r||i!==n||0===a&&0===o)||r&&1===e.length&&0===n)&&(!0!==t||(l&&12!==n&&(n+=12),s&&12===n&&(n+=12),{hours:n,minutes:a,seconds:o}))}isDateTime(e,t,i){var s;return"function"==typeof e.getFullYear?!0!==i||e:(s=parseInt(e))===e?!(s<0)&&(!0!==i||new Date(s)):(s=String(e).indexOf(" "))<0?!(String(e).indexOf("T")<0||"Invalid Date"==String(new Date(e)))&&(!0!==i||new Date(e)):(t=(t=null==t?this.settings.datetimeFormat:t).split("|"),e=[e.substr(0,s),e.substr(s).trim()],t[0]=t[0].trim(),t[1]&&(t[1]=t[1].trim()),s=this.isDate(e[0],t[0],!0),t=this.isTime(e[1],!0),!1!==s&&!1!==t&&(!0!==i||(s.setHours(t.hours),s.setMinutes(t.minutes),s.setSeconds(t.seconds),s)))}age(e){let t;if(""===e||null==e)return"";if(t="function"==typeof e.getFullYear?e:parseInt(e)==e&&0<parseInt(e)?new Date(parseInt(e)):new Date(e),"Invalid Date"===String(t))return"";e=((new Date).getTime()-t.getTime())/1e3;let i="",s="";return e<0?(i=0,s="sec"):e<60?(i=Math.floor(e),s="sec",e<0&&(i=0,s="sec")):e<3600?(i=Math.floor(e/60),s="min"):e<86400?(i=Math.floor(e/60/60),s="hour"):e<2592e3?(i=Math.floor(e/24/60/60),s="day"):e<31536e3?(i=Math.floor(e/30/24/60/60*10)/10,s="month"):e<126144e3?(i=Math.floor(e/365/24/60/60*10)/10,s="year"):126144e3<=e&&(i=Math.floor(e/365.25/24/60/60*10)/10,s="year"),i+" "+s+(1<i?"s":"")}interval(e){let t="";return t=e<100?"< 0.01 sec":e<1e3?Math.floor(e/10)/100+" sec":e<1e4?Math.floor(e/100)/10+" sec":e<6e4?Math.floor(e/1e3)+" secs":e<36e5?Math.floor(e/6e4)+" mins":e<864e5?Math.floor(e/36e5*10)/10+" hours":e<2628e6?Math.floor(e/864e5*10)/10+" days":e<31536e6?Math.floor(e/2628e6*10)/10+" months":Math.floor(e/31536e5)/10+" years"}date(e){if(""===e||null==e||"object"==typeof e&&!e.getMonth)return"";let t=new Date(e);if(this.isInt(e)&&(t=new Date(Number(e))),"Invalid Date"===String(t))return"";var e=this.settings.shortmonths,i=new Date,s=new Date,l=(s.setTime(s.getTime()-864e5),e[t.getMonth()]+" "+t.getDate()+", "+t.getFullYear()),i=e[i.getMonth()]+" "+i.getDate()+", "+i.getFullYear(),e=e[s.getMonth()]+" "+s.getDate()+", "+s.getFullYear(),s=t.getHours()-(12<t.getHours()?12:0)+":"+(t.getMinutes()<10?"0":"")+t.getMinutes()+" "+(12<=t.getHours()?"pm":"am");let r=l==i?s:l;return'<span title="'+l+" "+(t.getHours()-(12<t.getHours()?12:0)+":"+(t.getMinutes()<10?"0":"")+t.getMinutes()+":"+(t.getSeconds()<10?"0":"")+t.getSeconds()+" "+(12<=t.getHours()?"pm":"am"))+'">'+(r=l==e?this.lang("Yesterday"):r)+"</span>"}formatSize(e){var t;return this.isFloat(e)&&""!==e?0===(e=parseFloat(e))?0:(t=parseInt(Math.floor(Math.log(e)/Math.log(1024))),(Math.floor(e/Math.pow(1024,t)*10)/10).toFixed(0===t?0:1)+" "+(["Bt","KB","MB","GB","TB","PB","EB","ZB"][t]||"??")):""}formatNumber(e,t,i){return null==e||""===e||"object"==typeof e?"":(i={minimumFractionDigits:parseInt(t),maximumFractionDigits:parseInt(t),useGrouping:!!i},(null==t||t<0)&&(i.minimumFractionDigits=0,i.maximumFractionDigits=20),parseFloat(e).toLocaleString(this.settings.locale,i))}formatDate(e,t){if(t=t||this.settings.dateFormat,""===e||null==e||"object"==typeof e&&!e.getMonth)return"";let i=new Date(e);var s,l;return this.isInt(e)&&(i=new Date(Number(e))),"Invalid Date"===String(i)?"":(e=i.getFullYear(),s=i.getMonth(),l=i.getDate(),t.toLowerCase().replace("month",this.settings.fullmonths[s]).replace("mon",this.settings.shortmonths[s]).replace(/yyyy/g,("000"+e).slice(-4)).replace(/yyy/g,("000"+e).slice(-4)).replace(/yy/g,("0"+e).slice(-2)).replace(/(^|[^a-z$])y/g,"$1"+e).replace(/mm/g,("0"+(s+1)).slice(-2)).replace(/dd/g,("0"+l).slice(-2)).replace(/th/g,1==l?"st":"th").replace(/th/g,2==l?"nd":"th").replace(/th/g,3==l?"rd":"th").replace(/(^|[^a-z$])m/g,"$1"+(s+1)).replace(/(^|[^a-z$])d/g,"$1"+l))}formatTime(e,t){if(t=t||this.settings.timeFormat,""===e||null==e||"object"==typeof e&&!e.getMonth)return"";let i=new Date(e);if(this.isInt(e)&&(i=new Date(Number(e))),this.isTime(e)&&(e=this.isTime(e,!0),(i=new Date).setHours(e.hours),i.setMinutes(e.minutes)),"Invalid Date"===String(i))return"";let s="am",l=i.getHours();e=i.getHours();let r=i.getMinutes(),n=i.getSeconds();return r<10&&(r="0"+r),n<10&&(n="0"+n),-1===t.indexOf("am")&&-1===t.indexOf("pm")||(12<=l&&(s="pm"),12<l&&(l-=12),0===l&&(l=12)),t.toLowerCase().replace("am",s).replace("pm",s).replace("hhh",l<10?"0"+l:l).replace("hh24",e<10?"0"+e:e).replace("h24",e).replace("hh",l).replace("mm",r).replace("mi",r).replace("ss",n).replace(/(^|[^a-z$])h/g,"$1"+l).replace(/(^|[^a-z$])m/g,"$1"+r).replace(/(^|[^a-z$])s/g,"$1"+n)}formatDateTime(e,t){let i;return""===e||null==e||"object"==typeof e&&!e.getMonth?"":("string"!=typeof t?i=[this.settings.dateFormat,this.settings.timeFormat]:((i=t.split("|"))[0]=i[0].trim(),i[1]=1<i.length?i[1].trim():this.settings.timeFormat),"h12"===i[1]&&(i[1]="h:m pm"),"h24"===i[1]&&(i[1]="h24:m"),this.formatDate(e,i[0])+" "+this.formatTime(e,i[1]))}stripSpaces(i){if(null!=i)switch(typeof i){case"number":break;case"string":i=String(i).replace(/(?:\r\n|\r|\n)/g," ").replace(/\s\s+/g," ").trim();break;case"object":Array.isArray(i)?(i=this.extend([],i)).forEach((e,t)=>{i[t]=this.stripSpaces(e)}):(i=this.extend({},i),Object.keys(i).forEach(e=>{i[e]=this.stripSpaces(i[e])}))}return i}stripTags(i){if(null!=i)switch(typeof i){case"number":break;case"string":i=String(i).replace(/<(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*>/gi,"");break;case"object":Array.isArray(i)?(i=this.extend([],i)).forEach((e,t)=>{i[t]=this.stripTags(e)}):(i=this.extend({},i),Object.keys(i).forEach(e=>{i[e]=this.stripTags(i[e])}))}return i}encodeTags(i){if(null!=i)switch(typeof i){case"number":break;case"string":i=String(i).replace(/&/g,"&").replace(/>/g,">").replace(/</g,"<").replace(/"/g,""");break;case"object":Array.isArray(i)?(i=this.extend([],i)).forEach((e,t)=>{i[t]=this.encodeTags(e)}):(i=this.extend({},i),Object.keys(i).forEach(e=>{i[e]=this.encodeTags(i[e])}))}return i}decodeTags(i){if(null!=i)switch(typeof i){case"number":break;case"string":i=String(i).replace(/>/g,">").replace(/</g,"<").replace(/"/g,'"').replace(/&/g,"&");break;case"object":Array.isArray(i)?(i=this.extend([],i)).forEach((e,t)=>{i[t]=this.decodeTags(e)}):(i=this.extend({},i),Object.keys(i).forEach(e=>{i[e]=this.decodeTags(i[e])}))}return i}escapeId(e){return""===e||null==e?"":(e+"").replace(/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,(e,t)=>t?"\0"===e?"�":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e)}unescapeId(e){return""===e||null==e?"":e.replace(/\\[\da-fA-F]{1,6}[\x20\t\r\n\f]?|\\([^\r\n\f])/g,(e,t)=>{e="0x"+e.slice(1)-65536;return t||(e<0?String.fromCharCode(65536+e):String.fromCharCode(e>>10|55296,1023&e|56320))})}base64encode(e){return btoa(e)}base64decode(e){return atob(e)}async sha256(e){e=(new TextEncoder).encode(e);return crypto.subtle.digest("SHA-256",e).then(e=>{return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join("")})}transition(r,n,a,o){return new Promise((e,t)=>{var i=getComputedStyle(r);let s=parseInt(i.width),l=parseInt(i.height);if(r&&n){switch(r.parentNode.style.cssText+="perspective: 900px; overflow: hidden;",r.style.cssText+="; position: absolute; z-index: 1019; backface-visibility: hidden",n.style.cssText+="; position: absolute; z-index: 1020; backface-visibility: hidden",a){case"slide-left":r.style.cssText+="overflow: hidden; transform: translate3d(0, 0, 0)",n.style.cssText+="overflow: hidden; transform: translate3d("+s+"px, 0, 0)",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; transform: translate3d(0, 0, 0)",r.style.cssText+="transition: 0.5s; transform: translate3d(-"+s+"px, 0, 0)"},1);break;case"slide-right":r.style.cssText+="overflow: hidden; transform: translate3d(0, 0, 0)",n.style.cssText+="overflow: hidden; transform: translate3d(-"+s+"px, 0, 0)",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; transform: translate3d(0px, 0, 0)",r.style.cssText+="transition: 0.5s; transform: translate3d("+s+"px, 0, 0)"},1);break;case"slide-down":r.style.cssText+="overflow: hidden; z-index: 1; transform: translate3d(0, 0, 0)",n.style.cssText+="overflow: hidden; z-index: 0; transform: translate3d(0, 0, 0)",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; transform: translate3d(0, 0, 0)",r.style.cssText+="transition: 0.5s; transform: translate3d(0, "+l+"px, 0)"},1);break;case"slide-up":r.style.cssText+="overflow: hidden; transform: translate3d(0, 0, 0)",n.style.cssText+="overflow: hidden; transform: translate3d(0, "+l+"px, 0)",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; transform: translate3d(0, 0, 0)",r.style.cssText+="transition: 0.5s; transform: translate3d(0, 0, 0)"},1);break;case"flip-left":r.style.cssText+="overflow: hidden; transform: rotateY(0deg)",n.style.cssText+="overflow: hidden; transform: rotateY(-180deg)",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; transform: rotateY(0deg)",r.style.cssText+="transition: 0.5s; transform: rotateY(180deg)"},1);break;case"flip-right":r.style.cssText+="overflow: hidden; transform: rotateY(0deg)",n.style.cssText+="overflow: hidden; transform: rotateY(180deg)",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; transform: rotateY(0deg)",r.style.cssText+="transition: 0.5s; transform: rotateY(-180deg)"},1);break;case"flip-down":r.style.cssText+="overflow: hidden; transform: rotateX(0deg)",n.style.cssText+="overflow: hidden; transform: rotateX(180deg)",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; transform: rotateX(0deg)",r.style.cssText+="transition: 0.5s; transform: rotateX(-180deg)"},1);break;case"flip-up":r.style.cssText+="overflow: hidden; transform: rotateX(0deg)",n.style.cssText+="overflow: hidden; transform: rotateX(-180deg)",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; transform: rotateX(0deg)",r.style.cssText+="transition: 0.5s; transform: rotateX(180deg)"},1);break;case"pop-in":r.style.cssText+="overflow: hidden; transform: translate3d(0, 0, 0)",n.style.cssText+="overflow: hidden; transform: translate3d(0, 0, 0); transform: scale(.8); opacity: 0;",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; transform: scale(1); opacity: 1;",r.style.cssText+="transition: 0.5s;"},1);break;case"pop-out":r.style.cssText+="overflow: hidden; transform: translate3d(0, 0, 0); transform: scale(1); opacity: 1;",n.style.cssText+="overflow: hidden; transform: translate3d(0, 0, 0); opacity: 0;",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; opacity: 1;",r.style.cssText+="transition: 0.5s; transform: scale(1.7); opacity: 0;"},1);break;default:r.style.cssText+="overflow: hidden; transform: translate3d(0, 0, 0)",n.style.cssText+="overflow: hidden; translate3d(0, 0, 0); opacity: 0;",query(n).show(),setTimeout(()=>{n.style.cssText+="transition: 0.5s; opacity: 1;",r.style.cssText+="transition: 0.5s"},1)}setTimeout(()=>{"slide-down"===a&&(query(r).css("z-index","1019"),query(n).css("z-index","1020")),n&&query(n).css({opacity:"1"}).css({transition:"",transform:""}),r&&query(r).css({opacity:"1"}).css({transition:"",transform:""}),"function"==typeof o&&o(),e()},500)}else console.log("ERROR: Cannot do transition when one of the divs is null")})}lock(l,r={}){if(null!=l){"string"==typeof r&&(r={msg:r}),arguments[2]&&(r.spinner=arguments[2]),r=this.extend({spinner:!1},r),l?.[0]instanceof Node&&(l=Array.isArray(l)?l:l.get()),r.msg||0===r.msg||(r.msg=""),this.unlock(l);var n=query(l).get(0);let e=n.scrollWidth,t=n.scrollHeight,i=("BODY"==n.tagName&&(e<innerWidth&&(e=innerWidth),t<innerHeight)&&(t=innerHeight),query(l).prepend(`<div class="w2ui-lock" style="height: ${t}px; width: ${e}px"></div>`+'<div class="w2ui-lock-msg"></div>'),query(l).find(".w2ui-lock"));n=query(l).find(".w2ui-lock-msg"),l=(r.msg||n.css({"background-color":"transparent","background-image":"none",border:"0px","box-shadow":"none"}),!0===r.spinner&&(r.msg=`<div class="w2ui-spinner" ${r.msg?"":'style="width: 35px; height: 35px"'}></div>`+r.msg),r.msg?n.html(r.msg).css("display","block"):n.remove(),null!=r.opacity&&i.css("opacity",r.opacity),i.css({display:"block"}),r.bgColor&&i.css({"background-color":r.bgColor}),getComputedStyle(i.get(0)));let s=l.opacity??.15;i.on("mousedown",function(){"function"==typeof r.onClick?r.onClick():i.css({transition:".2s",opacity:1.5*s})}).on("mouseup",function(){"function"!=typeof r.onClick&&i.css({transition:".2s",opacity:s})}).on("mousewheel",function(e){e&&(e.stopPropagation(),e.preventDefault())})}}unlock(e,t){var i;null!=e&&(clearTimeout(e._prevUnlock),e?.[0]instanceof Node&&(e=Array.isArray(e)?e:e.get()),this.isInt(t)&&0<t?(query(e).find(".w2ui-lock").css({transition:t/1e3+"s",opacity:0}),i=query(e).get(0),clearTimeout(i._prevUnlock),i._prevUnlock=setTimeout(()=>{query(e).find(".w2ui-lock").remove()},t)):query(e).find(".w2ui-lock").remove(),query(e).find(".w2ui-lock-msg").remove())}message(r,s){let e,t,l;var i=()=>{var e=query(r?.box).find(".w2ui-message");0!=e.length&&"function"==typeof(s=e.get(0)._msg_options||{})?.close&&s.close()};let n=e=>{var t,i=e.box._msg_prevFocus;query(r.box).find(".w2ui-message").length<=1?r.owner?r.owner.unlock(r.param,150):this.unlock(r.box,150):query(r.box).find(`#w2ui-message-${r.owner?.name}-`+(e.msgIndex-1)).css("z-index",1500),i?0<(t=query(i).closest(".w2ui-message")).length?t.get(0)._msg_options.setFocus(i):i.focus():"function"==typeof r.owner?.focus&&r.owner.focus(),query(e.box).remove(),0===e.msgIndex&&(c.css("z-index",e.tmp.zIndex),query(r.box).css("overflow",e.tmp.overflow)),e.trigger&&l.finish()};if("object"!=typeof(s="string"!=typeof s&&"number"!=typeof s?s:{width:String(s).length<300?350:550,height:String(s).length<300?170:250,text:String(s)}))return void i();null!=s.text&&(s.body=`<div class="w2ui-centered w2ui-msg-text">${s.text}</div>`),null==s.width&&(s.width=350),null==s.height&&(s.height=170),null==s.hideOn&&(s.hideOn=["esc"]),null==s.on&&(h=s,s=new w2base,w2utils.extend(s,h)),s.on("open",e=>{w2utils.bindEvents(query(s.box).find(".w2ui-eaction"),s),query(e.detail.box).find("button, input, textarea, [name=hidden-first]").off(".message").on("keydown.message",function(e){27==e.keyCode&&s.hideOn.includes("esc")&&(s.cancelAction?s.action(s.cancelAction):s.close())}),setTimeout(()=>s.setFocus(s.focus),300)}),s.off(".prom");let a={self:s,action(e){return s.on("action.prom",e),a},close(e){return s.on("close.prom",e),a},open(e){return s.on("open.prom",e),a},then(e){return s.on("open:after.prom",e),a}},o=(null==s.actions&&null==s.buttons&&null==s.html&&(s.actions={Ok(e){e.detail.self.close()}}),s.off(".buttons"),null!=s.actions&&(s.buttons="",Object.keys(s.actions).forEach(e=>{var t=s.actions[e];let i=e;"function"==typeof t&&(s.buttons+=`<button class="w2ui-btn w2ui-eaction" data-click='["action","${e}","event"]' name="${e}">${e}</button>`),"object"==typeof t&&(s.buttons+=`<button class="w2ui-btn w2ui-eaction ${t.class||""}" name="${e}" data-click='["action","${e}","event"]'
style="${t.style??""}" ${t.attrs??""}>${t.text||e}</button>`,i=Array.isArray(s.actions)?t.text:e),"string"==typeof t&&(s.buttons+=`<button class="w2ui-btn w2ui-eaction" name="${t}" data-click='["action","${t}","event"]'>${t}</button>`,i=t),"string"==typeof i&&(i=i[0].toLowerCase()+i.substr(1).replace(/\s+/g,"")),a[i]=function(t){return s.on("action.buttons",e=>{e.detail.action[0].toLowerCase()+e.detail.action.substr(1).replace(/\s+/g,"")==i&&t(e)}),a}})),Array("html","body","buttons").forEach(e=>{s[e]=String(s[e]??"").trim()}),""===s.body&&""===s.buttons||(s.html=`
<div class="w2ui-message-body">${s.body||""}</div>
<div class="w2ui-message-buttons">${s.buttons||""}</div>
`),getComputedStyle(query(r.box).get(0)));var h=parseFloat(o.width),d=parseFloat(o.height);let u=0,c=(0<query(r.after).length&&(o=getComputedStyle(query(r.after).get(0)),u=parseInt("none"!=o.display?parseInt(o.height):0)),s.width>h&&(s.width=h-10),s.height>d-u&&(s.height=d-10-u),s.originalWidth=s.width,s.originalHeight=s.height,parseInt(s.width)<0&&(s.width=h+s.width),parseInt(s.width)<10&&(s.width=10),parseInt(s.height)<0&&(s.height=d+s.height-u),parseInt(s.height)<10&&(s.height=10),s.originalHeight<0&&(s.height=d+s.originalHeight-u),s.originalWidth<0&&(s.width=h+2*s.originalWidth),query(r.box).find(r.after));return s.tmp||(s.tmp={zIndex:c.css("z-index"),overflow:o.overflow}),""===s.html&&""===s.body&&""===s.buttons?i():(s.msgIndex=query(r.box).find(".w2ui-message").length,0===s.msgIndex&&"function"==typeof this.lock&&(query(r.box).css("overflow","hidden"),r.owner?r.owner.lock(r.param):this.lock(r.box)),query(r.box).find(".w2ui-message").css("z-index",1390),c.css("z-index",1501),d=`
<div id="w2ui-message-${r.owner?.name}-${s.msgIndex}" class="w2ui-message" data-mousedown="stop"
style="z-index: 1500; left: ${(h-s.width)/2}px; top: ${u}px;
width: ${s.width}px; height: ${s.height}px; transform: translateY(-${s.height}px)"
${s.hideOn.includes("click")?r.param?`data-click='["message", "${r.param}"]`:'data-click="message"':""}>
<span name="hidden-first" tabindex="0" style="position: absolute; top: 0; outline: none"></span>
${s.html}
<span name="hidden-last" tabindex="0" style="position: absolute; top: 0; outline: none"></span>
</div>`,0<query(r.after).length?query(r.box).find(r.after).after(d):query(r.box).prepend(d),s.box=query(r.box).find(`#w2ui-message-${r.owner?.name}-`+s.msgIndex)[0],w2utils.bindEvents(s.box,this),query(s.box).addClass("animating"),(s.box._msg_options=s).box._msg_prevFocus=document.activeElement,setTimeout(()=>{!0===(l=s.trigger("open",{target:this.name,box:s.box,self:s})).isCancelled?(query(r.box).find(`#w2ui-message-${r.owner?.name}-`+s.msgIndex).remove(),0===s.msgIndex&&(c.css("z-index",s.tmp.zIndex),query(r.box).css("overflow",s.tmp.overflow))):query(s.box).css({transition:"0.3s",transform:"translateY(0px)"})},0),t=setTimeout(()=>{query(r.box).find(`#w2ui-message-${r.owner?.name}-`+s.msgIndex).removeClass("animating").css({transition:"0s"}),l.finish()},300)),s.action=(e,t)=>{let i=s.actions[e];i instanceof Object&&i.onClick&&(i=i.onClick);e=s.trigger("action",{target:this.name,action:e,self:s,originalEvent:t,value:s.input?s.input.value:null});!0!==e.isCancelled&&("function"==typeof i&&i(e),e.finish())},s.close=()=>{!0!==(l=s.trigger("close",{target:"self",box:s.box,self:s})).isCancelled&&(clearTimeout(t),query(s.box).hasClass("animating")?(clearTimeout(e),n(s)):(query(s.box).addClass("w2ui-closing animating").css({transition:"0.15s",transform:"translateY(-"+s.height+"px)"}),0!==s.msgIndex&&query(r.box).find(`#w2ui-message-${r.owner?.name}-`+(s.msgIndex-1)).css("z-index",1499),e=setTimeout(()=>{n(s)},150)))},s.setFocus=e=>{var t=query(r.box).find(".w2ui-message").length-1;let s=query(r.box).find(`#w2ui-message-${r.owner?.name}-`+t),l="input, button, select, textarea, [contentEditable], .w2ui-input";(null!=e?isNaN(e)?s.find(l).filter(e).get(0):s.find(l).get(e):s.find("[name=hidden-first]").get(0))?.focus(),query(r.box).find(".w2ui-message").find(l+",[name=hidden-first],[name=hidden-last]").off(".keep-focus"),query(s).find(l+",[name=hidden-first],[name=hidden-last]").on("blur.keep-focus",function(e){setTimeout(()=>{var e=document.activeElement,t=0<query(s).find(l).filter(e).length,i=query(e).attr("name");!t&&e&&e!==document.body&&query(s).find(l).get(0)?.focus(),"hidden-last"==i&&query(s).find(l).get(0)?.focus(),"hidden-first"==i&&query(s).find(l).get(-1)?.focus()},1)})},a}notify(i,s){return new Promise(t=>{if("object"==typeof i&&(i=(s=i).text),(s=s||{}).where=s.where??document.body,s.timeout=s.timeout??15e3,"function"==typeof this.tmp.notify_resolve&&(this.tmp.notify_resolve(),query(this.tmp.notify_where).find("#w2ui-notify").remove()),this.tmp.notify_resolve=t,this.tmp.notify_where=s.where,clearTimeout(this.tmp.notify_timer),i){if("object"==typeof s.actions){let t={};Object.keys(s.actions).forEach(e=>{t[e]=`<a class="w2ui-notify-link" value="${e}">${e}</a>`}),i=this.execTemplate(i,t)}var e=`
<div id="w2ui-notify">
<div class="${s.class} ${s.error?"w2ui-notify-error":""}">
${i}
<span class="w2ui-notify-close w2ui-icon-cross"></span>
</div>
</div>`;query(s.where).append(e),query(s.where).find("#w2ui-notify").find(".w2ui-notify-close").on("click",e=>{query(s.where).find("#w2ui-notify").remove(),t()}),s.actions&&query(s.where).find("#w2ui-notify .w2ui-notify-link").on("click",e=>{e=query(e.target).attr("value");s.actions[e](),query(s.where).find("#w2ui-notify").remove(),t()}),0<s.timeout&&(this.tmp.notify_timer=setTimeout(()=>{query(s.where).find("#w2ui-notify").remove(),t()},s.timeout))}})}confirm(e,t){w2utils.normButtons(t="string"==typeof t?{text:t}:t,{yes:"Yes",no:"No"});e=w2utils.message(e,t);return e&&e.action(e=>{e.detail.self.close()}),e}normButtons(i,s){i.actions=i.actions??{};var e=Object.keys(s);return e.forEach(t=>{var e=i["btn_"+t];e&&(s[t]={text:w2utils.lang(e.text??""),class:e.class??"",style:e.style??"",attrs:e.attrs??""},delete i["btn_"+t]),Array("text","class","style","attrs").forEach(e=>{i[t+"_"+e]&&("string"==typeof s[t]&&(s[t]={text:s[t]}),s[t][e]=i[t+"_"+e],delete i[t+"_"+e])})}),e.includes("yes")&&e.includes("no")&&(w2utils.settings.macButtonOrder?w2utils.extend(i.actions,{no:s.no,yes:s.yes}):w2utils.extend(i.actions,{yes:s.yes,no:s.no})),e.includes("ok")&&e.includes("cancel")&&(w2utils.settings.macButtonOrder?w2utils.extend(i.actions,{cancel:s.cancel,ok:s.ok}):w2utils.extend(i.actions,{ok:s.ok,cancel:s.cancel})),i}getSize(e,t){let i=0;if(0<(e=query(e)).length){e=e[0];var s=getComputedStyle(e);switch(t){case"width":i=parseFloat(s.width),"auto"===s.width&&(i=0);break;case"height":i=parseFloat(s.height),"auto"===s.height&&(i=0);break;default:i=parseFloat(s[t]??0)||0}}return i}getStrWidth(e,t){query("body").append(`
<div id="_tmp_width" style="position: absolute; top: -9000px; ${t||""}">
${this.encodeTags(e)}
</div>`);t=query("#_tmp_width")[0].clientWidth;return query("#_tmp_width").remove(),t}execTemplate(e,i){return"string"==typeof e&&i&&"object"==typeof i?e.replace(/\${([^}]+)?}/g,function(e,t){return i[t]||t}):e}marker(e,s,l={onlyFirst:!1,wholeWord:!1}){Array.isArray(s)||(s=null!=s&&""!==s?[s]:[]);let r=l.wholeWord;query(e).each(t=>{for(var e=t,i=/\<span class=\"w2ui\-marker\"\>((.|\n|\r)*)\<\/span\>/gi;-1!==e.innerHTML.indexOf('<span class="w2ui-marker"');)e.innerHTML=e.innerHTML.replace(i,"$1");s.forEach(e=>{e=(e="string"!=typeof e?String(e):e).replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&").replace(/&/g,"&").replace(/</g,">").replace(/>/g,"<");e=new RegExp((r?"\\b":"")+e+(r?"\\b":"")+"(?!([^<]+)?>)","i"+(l.onlyFirst?"":"g"));t.innerHTML=t.innerHTML.replace(e,e=>'<span class="w2ui-marker">'+e+"</span>")})})}lang(e,t){if(!e||null==this.settings.phrases||"string"!=typeof e||"<=>=".includes(e))return this.execTemplate(e,t);let i=this.settings.phrases[e];return null==i?(i=e,this.settings.warnNoPhrase&&(this.settings.missing||(this.settings.missing={}),this.settings.missing[e]="---",this.settings.phrases[e]="---",console.log(`Missing translation for "%c${e}%c", see %c w2utils.settings.phrases %c with value "---"`,"color: orange","","color: #999",""))):"---"!==i||this.settings.warnNoPhrase||(i=e),"---"===i&&(i=`<span ${this.tooltip(e)}>---</span>`),this.execTemplate(i,t)}locale(l,i,r){return new Promise((s,t)=>{if(Array.isArray(l)){this.settings.phrases={};let i=[],t={};l.forEach((e,t)=>{5===e.length&&(e="locale/"+e.toLowerCase()+".json",l[t]=e),i.push(this.locale(e,!0,!1))}),void Promise.allSettled(i).then(e=>{e.forEach(e=>{e.value&&(t[e.value.file]=e.value.data)}),l.forEach(e=>{this.settings=this.extend({},this.settings,t[e])}),s()})}else(l=l||"en-us")instanceof Object?this.settings=this.extend({},this.settings,w2locale,l):(5===l.length&&(l="locale/"+l.toLowerCase()+".json"),fetch(l,{method:"GET"}).then(e=>e.json()).then(e=>{!0!==r&&(this.settings=i?this.extend({},this.settings,e):this.extend({},this.settings,w2locale,{phrases:{}},e)),s({file:l,data:e})}).catch(e=>{console.log("ERROR: Cannot load locale "+l),t(e)}))})}scrollBarSize(){return this.tmp.scrollBarSize||(query("body").append(`
<div id="_scrollbar_width" style="position: absolute; top: -300px; width: 100px; height: 100px; overflow-y: scroll;">
<div style="height: 120px">1</div>
</div>
`),this.tmp.scrollBarSize=100-query("#_scrollbar_width > div")[0].clientWidth,query("#_scrollbar_width").remove()),this.tmp.scrollBarSize}checkName(e){return null==e?(console.log('ERROR: Property "name" is required but not supplied.'),!1):null!=w2ui[e]?(console.log(`ERROR: Object named "${e}" is already registered as w2ui.${e}.`),!1):!!this.isAlphaNumeric(e)||(console.log('ERROR: Property "name" has to be alpha-numeric (a-z, 0-9, dash and underscore).'),!1)}checkUniqueId(t,i,s,l){Array.isArray(i)||(i=[i]);let r=!0;return i.forEach(e=>{e.id===t&&(console.log(`ERROR: The item id="${t}" is not unique within the ${s} "${l}".`,i),r=!1)}),r}encodeParams(t,i=""){let s="";return Object.keys(t).forEach(e=>{""!=s&&(s+="&"),"object"==typeof t[e]?s+=this.encodeParams(t[e],i+e+(i?"]":"")+"["):s+=""+i+e+(i?"]":"")+"="+t[e]}),s}parseRoute(e){let n=[];e=e.replace(/\/\(/g,"(?:/").replace(/\+/g,"__plus__").replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g,(e,t,i,s,l,r)=>(n.push({name:s,optional:!!r}),t=t||"",(r?"":t)+"(?:"+(r?t:"")+(i||"")+(l||(i?"([^/.]+?)":"([^/]+?)"))+")"+(r||""))).replace(/([\/.])/g,"\\$1").replace(/__plus__/g,"(.+)").replace(/\*/g,"(.*)");return{path:new RegExp("^"+e+"$","i"),keys:n}}getCursorPosition(e){if(null==e)return null;let t=0;var i,s=e.ownerDocument||e.document,l=s.defaultView||s.parentWindow;let r;return["INPUT","TEXTAREA"].includes(e.tagName)?t=e.selectionStart:l.getSelection?0<(r=l.getSelection()).rangeCount&&((i=(l=r.getRangeAt(0)).cloneRange()).selectNodeContents(e),i.setEnd(l.endContainer,l.endOffset),t=i.toString().length):(r=s.selection)&&"Control"!==r.type&&(l=r.createRange(),(i=s.body.createTextRange()).moveToElementText(e),i.setEndPoint("EndToEnd",l),t=i.text.length),t}setCursorPosition(s,l,t){if(null!=s){var r=document.createRange();let i,e=window.getSelection();if(["INPUT","TEXTAREA"].includes(s.tagName))s.setSelectionRange(l,t??l);else{for(let t=0;t<s.childNodes.length;t++){let e=query(s.childNodes[t]).text();if(l<=(e=s.childNodes[t].tagName?(e=query(s.childNodes[t]).html()).replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/ /g," "):e).length){(i=(i=s.childNodes[t]).childNodes&&0<i.childNodes.length?i.childNodes[0]:i).childNodes&&0<i.childNodes.length&&(i=i.childNodes[0]);break}l-=e.length}null!=i&&(l>i.length&&(l=i.length),r.setStart(i,l),t?r.setEnd(i,t):r.collapse(!0),e.removeAllRanges(),e.addRange(r))}}}parseColor(e){if("string"!=typeof e)return null;let t={};if(3===(e="#"===(e=e.trim().toUpperCase())[0]?e.substr(1):e).length)t={r:parseInt(e[0]+e[0],16),g:parseInt(e[1]+e[1],16),b:parseInt(e[2]+e[2],16),a:1};else if(6===e.length)t={r:parseInt(e.substr(0,2),16),g:parseInt(e.substr(2,2),16),b:parseInt(e.substr(4,2),16),a:1};else if(8===e.length)t={r:parseInt(e.substr(0,2),16),g:parseInt(e.substr(2,2),16),b:parseInt(e.substr(4,2),16),a:Math.round(parseInt(e.substr(6,2),16)/255*100)/100};else if(4<e.length&&"RGB("===e.substr(0,4)){var i=e.replace("RGB","").replace(/\(/g,"").replace(/\)/g,"").split(",");t={r:parseInt(i[0],10),g:parseInt(i[1],10),b:parseInt(i[2],10),a:1}}else{if(!(5<e.length&&"RGBA("===e.substr(0,5)))return null;i=e.replace("RGBA","").replace(/\(/g,"").replace(/\)/g,"").split(",");t={r:parseInt(i[0],10),g:parseInt(i[1],10),b:parseInt(i[2],10),a:parseFloat(i[3])}}return t}hsv2rgb(e,t,i,s){let l,r,n,a,o,h,d,u;switch(1===arguments.length&&(t=e.s,i=e.v,s=e.a,e=e.h),h=(i/=100)*(1-(t/=100)),d=i*(1-(o=6*(e/=360)-(a=Math.floor(6*e)))*t),u=i*(1-(1-o)*t),a%6){case 0:l=i,r=u,n=h;break;case 1:l=d,r=i,n=h;break;case 2:l=h,r=i,n=u;break;case 3:l=h,r=d,n=i;break;case 4:l=u,r=h,n=i;break;case 5:l=i,r=h,n=d}return{r:Math.round(255*l),g:Math.round(255*r),b:Math.round(255*n),a:null!=s?s:1}}rgb2hsv(e,t,i,s){1===arguments.length&&(t=e.g,i=e.b,s=e.a,e=e.r);let l=Math.max(e,t,i),r=Math.min(e,t,i),n=l-r,a,o=0===l?0:n/l,h=l/255;switch(l){case r:a=0;break;case e:a=t-i+n*(t<i?6:0),a/=6*n;break;case t:a=i-e+2*n,a/=6*n;break;case i:a=e-t+4*n,a/=6*n}return{h:Math.round(360*a),s:Math.round(100*o),v:Math.round(100*h),a:null!=s?s:1}}tooltip(e,t){let i="mouseenter",s="mouseleave";return t=(t="object"==typeof e?e:t)||{},"string"==typeof e&&(t.html=e),t.showOn&&(i=t.showOn,delete t.showOn),t.hideOn&&(s=t.hideOn,delete t.hideOn),t.name||(t.name="no-name"),` on${i}="w2tooltip.show(this, `+`JSON.parse(w2utils.base64decode('${this.base64encode(JSON.stringify(t))}')))" `+`on${s}="w2tooltip.hide('${t.name}')"`}isPlainObject(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)&&(void 0===e.constructor||null===(e=Object.getPrototypeOf(e))||e===Object.prototype)}clone(e,i){let s;return i=Object.assign({functions:!0,elements:!0,events:!0,exclude:[]},i??{}),Array.isArray(e)?(s=Array.from(e)).forEach((e,t)=>{s[t]=this.clone(e,i)}):this.isPlainObject(e)?(s={},Object.assign(s,e),i.exclude&&i.exclude.forEach(e=>{delete s[e]}),Object.keys(s).forEach(e=>{s[e]=this.clone(s[e],i),void 0===s[e]&&delete s[e]})):e instanceof Function&&!i.functions||e instanceof Node&&!i.elements||e instanceof Event&&!i.events||(s=e),s}extend(i,s){if(Array.isArray(i)){if(!Array.isArray(s))throw new Error("Arrays can be extended with arrays only");i.splice(0,i.length),s.forEach(e=>{i.push(this.clone(e))})}else{if(i instanceof Node||i instanceof Event)throw new Error("HTML elmenents and events cannot be extended");if(i&&"object"==typeof i&&null!=s){if("object"!=typeof s)throw new Error("Object can be extended with other objects only.");Object.keys(s).forEach(e=>{var t;null!=i[e]&&"object"==typeof i[e]&&null!=s[e]&&"object"==typeof s[e]?(t=this.clone(s[e]),i[e]instanceof Node||i[e]instanceof Event?i[e]=t:(Array.isArray(i[e])&&this.isPlainObject(t)&&(i[e]={}),this.extend(i[e],t))):i[e]=this.clone(s[e])})}else if(null!=s)throw new Error("Object is not extendable, only {} or [] can be extended.")}if(2<arguments.length)for(let e=2;e<arguments.length;e++)this.extend(i,arguments[e]);return i}naturalCompare(e,t){let s,i,l=1,r=0,n=0,a=String.alphabet;function o(e,t,i){if(i){for(s=t;(i=o(e,s))<76&&65<i;)++s;return+e.slice(t-1,s)}return-1<(i=a&&a.indexOf(e.charAt(t)))?i+76:(i=e.charCodeAt(t)||0)<45||127<i?i:i<46?65:i<48?i-1:i<58?i+18:i<65?i-11:i<91?i+11:i<97?i-37:i<123?i+5:i-63}if((e+="")!=(t+=""))for(;l;)if(i=o(e,r++),l=o(t,n++),i<76&&l<76&&66<i&&66<l&&(i=o(e,r,r),l=o(t,n,r=s),n=s),i!=l)return i<l?-1:1;return 0}normMenu(i,e){return Array.isArray(i)?(i.forEach((e,t)=>{"string"==typeof e||"number"==typeof e?i[t]={id:e,text:String(e)}:null!=e?(null!=e.caption&&null==e.text&&(e.text=e.caption),null!=e.text&&null==e.id&&(e.id=e.text),null==e.text&&null!=e.id&&(e.text=e.id)):i[t]={id:null,text:"null"}}),i):"function"==typeof i?(e=i.call(this,i,e),w2utils.normMenu.call(this,e)):"object"==typeof i?Object.keys(i).map(e=>({id:e,text:i[e]})):void 0}prepareParams(i,e,t){t=t??w2utils.settings.dataType;let s=e.body;switch(t){case"HTTPJSON":s={request:s},["PUT","DELETE"].includes(e.method)&&(e.method="POST"),l();break;case"HTTP":["PUT","DELETE"].includes(e.method)&&(e.method="POST"),l();break;case"RESTFULL":["PUT","DELETE"].includes(e.method)?e.headers["Content-Type"]="application/json":l();break;case"JSON":"GET"==e.method?(s={request:s},l()):(e.headers["Content-Type"]="application/json",e.method="POST")}return e.body="string"==typeof e.body?e.body:JSON.stringify(e.body),e;function l(){Object.keys(s).forEach(e=>{let t=s[e];"object"==typeof t&&(t=JSON.stringify(t)),i.searchParams.append(e,t)}),delete e.body}}bindEvents(e,r){0!=e.length&&(e?.[0]instanceof Node&&(e=Array.isArray(e)?e:e.get()),query(e).each(s=>{let l=query(s).data();Object.keys(l).forEach(i=>{if(-1!=["click","dblclick","mouseenter","mouseleave","mouseover","mouseout","mousedown","mousemove","mouseup","contextmenu","focus","focusin","focusout","blur","input","change","keydown","keyup","keypress"].indexOf(String(i).toLowerCase())){let e=l[i],t=(e="string"==typeof e?e.split("|").map(e=>{"null"===(e="undefined"===(e="false"===(e="true"===e?!0:e)?!1:e)?void 0:e)&&(e=null);var t=["'",'"',"`"];return e="string"==typeof(e=parseFloat(e)==e?parseFloat(e):e)&&t.includes(e[0])&&t.includes(e[e.length-1])?e.substring(1,e.length-1):e}):e)[0];e=e.slice(1),query(s).off(i+".w2utils-bind").on(i+".w2utils-bind",function(i){switch(t){case"alert":alert(e[0]);break;case"stop":i.stopPropagation();break;case"prevent":i.preventDefault();break;case"stopPrevent":return i.stopPropagation(),i.preventDefault(),!1;default:if(null==r[t])throw new Error(`Cannot dispatch event as the method "${t}" does not exist.`);r[t].apply(r,e.map((e,t)=>{switch(String(e).toLowerCase()){case"event":return i;case"this":return this;default:return e}}))}})}})}))}debounce(t,i=250){let s;return(...e)=>{clearTimeout(s),s=setTimeout(()=>{t(...e)},i)}}}var w2utils=new Utils;class Dialog extends w2base{constructor(){super(),this.defaults={title:"",text:"",body:"",buttons:"",width:450,height:250,focus:null,actions:null,style:"",speed:.3,modal:!1,maximized:!1,keyboard:!0,showClose:!0,showMax:!1,transition:null,openMaximized:!1,moved:!1},this.name="popup",this.status="closed",this.onOpen=null,this.onClose=null,this.onMax=null,this.onMin=null,this.onToggle=null,this.onKeydown=null,this.onAction=null,this.onMove=null,this.tmp={},this.handleResize=e=>{this.options.moved||this.center(void 0,void 0,!0)}}open(s){let l=this;"closing"!=this.status&&!query("#w2ui-popup").hasClass("animating")||this.close(!0);var e=this.options;null!=(s=["string","number"].includes(typeof s)?w2utils.extend({title:"Notification",body:`<div class="w2ui-centered">${s}</div>`,actions:{Ok(){l.close()}},cancelAction:"ok"},arguments[1]??{}):s).text&&(s.body=`<div class="w2ui-centered w2ui-msg-text">${s.text}</div>`),s=Object.assign({},this.defaults,e,{title:"",body:""},s,{maximized:!1}),this.options=s,0===query("#w2ui-popup").length&&(this.off("*"),Object.keys(this).forEach(e=>{e.startsWith("on")&&"on"!=e&&(this[e]=null)})),Object.keys(s).forEach(e=>{e.startsWith("on")&&"on"!=e&&s[e]&&(this[e]=s[e])}),s.width=parseInt(s.width),s.height=parseInt(s.height);let r,t,i;var{top:n,left:a}=this.center();let o={self:this,action(e){return l.on("action.prom",e),o},close(e){return l.on("close.prom",e),o},then(e){return l.on("open:after.prom",e),o}};if(null==s.actions||s.buttons||(s.buttons="",Object.keys(s.actions).forEach(e=>{var t=s.actions[e];let i=e;"function"==typeof t&&(s.buttons+=`<button class="w2ui-btn w2ui-eaction" data-click='["action","${e}","event"]'>${e}</button>`),"object"==typeof t&&(s.buttons+=`<button class="w2ui-btn w2ui-eaction ${t.class||""}" name="${e}" data-click='["action","${e}","event"]'
style="${t.style}" ${t.attrs}>${t.text||e}</button>`,i=Array.isArray(s.actions)?t.text:e),"string"==typeof t&&(s.buttons+=`<button class="w2ui-btn w2ui-eaction" data-click='["action","${t}","event"]'>${t}</button>`,i=t),"string"==typeof i&&(i=i[0].toLowerCase()+i.substr(1).replace(/\s+/g,"")),o[i]=function(t){return l.on("action.buttons",e=>{e.detail.action[0].toLowerCase()+e.detail.action.substr(1).replace(/\s+/g,"")==i&&t(e)}),o}})),0===query("#w2ui-popup").length){if(!0===(r=this.trigger("open",{target:"popup",present:!1})).isCancelled)return;this.status="opening",w2utils.lock(document.body,{opacity:.3,onClick:s.modal?null:()=>{this.close()}});let e="";s.showClose&&(e+=`<div class="w2ui-popup-button w2ui-popup-close">
<span class="w2ui-icon w2ui-icon-cross w2ui-eaction" data-mousedown="stop" data-click="close"></span>
</div>`),s.showMax&&(e+=`<div class="w2ui-popup-button w2ui-popup-max">
<span class="w2ui-icon w2ui-icon-box w2ui-eaction" data-mousedown="stop" data-click="toggle"></span>
</div>`);a=`
left: ${a}px;
top: ${n}px;
width: ${parseInt(s.width)}px;
height: ${parseInt(s.height)}px;
transition: ${s.speed}s
`;t=`<div id="w2ui-popup" class="w2ui-popup w2ui-anim-open animating" style="${w2utils.stripSpaces(a)}"></div>`,query("body").append(t),query("#w2ui-popup")[0]._w2popup={self:this,created:new Promise(e=>{this._promCreated=e}),opened:new Promise(e=>{this._promOpened=e}),closing:new Promise(e=>{this._promClosing=e}),closed:new Promise(e=>{this._promClosed=e})},a=`${s.title?"":"top: 0px !important;"} `+(s.buttons?"":"bottom: 0px !important;"),t=`
<span name="hidden-first" tabindex="0" style="position: absolute; top: -100px"></span>
<div class="w2ui-popup-title-btns">${e}</div>
<div class="w2ui-popup-title" style="${s.title?"":"display: none"}"></div>
<div class="w2ui-box" style="${a}">
<div class="w2ui-popup-body ${!s.title||" w2ui-popup-no-title"}
${!s.buttons||" w2ui-popup-no-buttons"}" style="${s.style}">
</div>
</div>
<div class="w2ui-popup-buttons" style="${s.buttons?"":"display: none"}"></div>
<span name="hidden-last" tabindex="0" style="position: absolute; top: -100px"></span>
`,query("#w2ui-popup").html(t),s.title&&query("#w2ui-popup .w2ui-popup-title").append(w2utils.lang(s.title)),s.buttons&&query("#w2ui-popup .w2ui-popup-buttons").append(s.buttons),s.body&&query("#w2ui-popup .w2ui-popup-body").append(s.body),setTimeout(()=>{query("#w2ui-popup").css("transition",s.speed+"s").removeClass("w2ui-anim-open"),w2utils.bindEvents("#w2ui-popup .w2ui-eaction",this),query("#w2ui-popup").find(".w2ui-popup-body").show(),this._promCreated()},1),clearTimeout(this._timer),this._timer=setTimeout(()=>{this.status="open",l.setFocus(s.focus),r.finish(),this._promOpened(),query("#w2ui-popup").removeClass("animating")},1e3*s.speed)}else{if(!0===(r=this.trigger("open",{target:"popup",present:!0})).isCancelled)return;this.status="opening",null!=e&&(e.maximized||e.width==s.width&&e.height==s.height||this.resize(s.width,s.height),s.prevSize=s.width+"px:"+s.height+"px",s.maximized=e.maximized);n=query("#w2ui-popup .w2ui-box").get(0).cloneNode(!0);query(n).removeClass("w2ui-box").addClass("w2ui-box-temp").find(".w2ui-popup-body").empty().append(s.body),query("#w2ui-popup .w2ui-box").after(n),s.buttons?(query("#w2ui-popup .w2ui-popup-buttons").show().html("").append(s.buttons),query("#w2ui-popup .w2ui-popup-body").removeClass("w2ui-popup-no-buttons"),query("#w2ui-popup .w2ui-box, #w2ui-popup .w2ui-box-temp").css("bottom","")):(query("#w2ui-popup .w2ui-popup-buttons").hide().html(""),query("#w2ui-popup .w2ui-popup-body").addClass("w2ui-popup-no-buttons"),query("#w2ui-popup .w2ui-box, #w2ui-popup .w2ui-box-temp").css("bottom","0px")),s.title?(query("#w2ui-popup .w2ui-popup-title").show().html((s.showClose?`<div class="w2ui-popup-button w2ui-popup-close">
<span class="w2ui-icon w2ui-icon-cross w2ui-eaction" data-mousedown="stop" data-click="close"></span>
</div>`:"")+(s.showMax?`<div class="w2ui-popup-button w2ui-popup-max">
<span class="w2ui-icon w2ui-icon-box w2ui-eaction" data-mousedown="stop" data-click="toggle"></span>
</div>`:"")).append(s.title),query("#w2ui-popup .w2ui-popup-body").removeClass("w2ui-popup-no-title"),query("#w2ui-popup .w2ui-box, #w2ui-popup .w2ui-box-temp").css("top","")):(query("#w2ui-popup .w2ui-popup-title").hide().html(""),query("#w2ui-popup .w2ui-popup-body").addClass("w2ui-popup-no-title"),query("#w2ui-popup .w2ui-box, #w2ui-popup .w2ui-box-temp").css("top","0px"));let t=query("#w2ui-popup .w2ui-box")[0],i=query("#w2ui-popup .w2ui-box-temp")[0];query("#w2ui-popup").addClass("animating"),w2utils.transition(t,i,s.transition,()=>{query(t).remove(),query(i).removeClass("w2ui-box-temp").addClass("w2ui-box");var e=query(i).find(".w2ui-popup-body");1==e.length&&(e[0].style.cssText=s.style,e.show()),l.setFocus(s.focus),query("#w2ui-popup").removeClass("animating")}),this.status="open",r.finish(),w2utils.bindEvents("#w2ui-popup .w2ui-eaction",this),query("#w2ui-popup").find(".w2ui-popup-body").show()}return s.openMaximized&&this.max(),s._last_focus=document.activeElement,s.keyboard&&query(document.body).on("keydown",e=>{this.keydown(e)}),query(window).on("resize",this.handleResize),i={resizing:!1,mvMove:function(e){1==i.resizing&&(e=e||window.event,i.div_x=e.screenX-i.x,i.div_y=e.screenY-i.y,!0!==(e=l.trigger("move",{target:"popup",div_x:i.div_x,div_y:i.div_y,originalEvent:e})).isCancelled)&&(query("#w2ui-popup").css({transition:"none",transform:"translate3d("+i.div_x+"px, "+i.div_y+"px, 0px)"}),l.options.moved=!0,e.finish())},mvStop:function(e){1!=i.resizing||(e=e||window.event,l.status="open",i.div_x=e.screenX-i.x,i.div_y=e.screenY-i.y,query("#w2ui-popup").css({left:i.pos_x+i.div_x+"px",top:i.pos_y+i.div_y+"px"}).css({transition:"none",transform:"translate3d(0px, 0px, 0px)"}),i.resizing=!1,query(document.body).off(".w2ui-popup"),i.isLocked)||l.unlock()}},query("#w2ui-popup .w2ui-popup-title").on("mousedown",function(e){var t;l.options.maximized||(e=(e=e)||window.event,l.status="moving",t=query("#w2ui-popup").get(0).getBoundingClientRect(),Object.assign(i,{resizing:!0,isLocked:1==query("#w2ui-popup > .w2ui-lock").length,x:e.screenX,y:e.screenY,pos_x:t.x,pos_y:t.y}),i.isLocked||l.lock({opacity:0}),query(document.body).on("mousemove.w2ui-popup",i.mvMove).on("mouseup.w2ui-popup",i.mvStop),e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,e.preventDefault&&e.preventDefault())}),o}load(s){return new Promise((i,e)=>{if(null==(s="string"==typeof s?{url:s}:s).url)console.log("ERROR: The url is not defined."),e("The url is not defined");else{this.status="loading";let[e,t]=String(s.url).split("#");e&&fetch(e).then(e=>e.text()).then(e=>{i(this.template(e,t,s))})}})}template(t,e,i={}){let s;try{s=query(t)}catch(e){s=query.html(t)}return e&&(s=s.filter("#"+e)),Object.assign(i,{width:parseInt(query(s).css("width")),height:parseInt(query(s).css("height")),title:query(s).find("[rel=title]").html(),body:query(s).find("[rel=body]").html(),buttons:query(s).find("[rel=buttons]").html(),style:query(s).find("[rel=body]").get(0).style.cssText}),this.open(i)}action(e,t){let i=this.options.actions[e];i instanceof Object&&i.onClick&&(i=i.onClick);e=this.trigger("action",{action:e,target:"popup",self:this,originalEvent:t,value:this.input?this.input.value:null});!0!==e.isCancelled&&("function"==typeof i&&i.call(this,t),e.finish())}keydown(e){var t;this.options&&!this.options.keyboard||!0!==(t=this.trigger("keydown",{target:"popup",originalEvent:e})).isCancelled&&(27===e.keyCode&&(e.preventDefault(),0==query("#w2ui-popup .w2ui-message").length)&&(this.options.cancelAction?this.action(this.options.cancelAction):this.close()),t.finish())}close(e){let t=this.trigger("close",{target:"popup"});var i;!0!==t.isCancelled&&(i=()=>{query("#w2ui-popup").remove(),this.options._last_focus&&0<this.options._last_focus.length&&this.options._last_focus.focus(),this.status="closed",this.options={},t.finish(),this._promClosed()},0!==query("#w2ui-popup").length)&&"closed"!=this.status&&("opening"==this.status&&(e=!0),"closing"==this.status&&!0===e?(i(),clearTimeout(this.tmp.closingTimer),w2utils.unlock(document.body,0)):(this.status="closing",query("#w2ui-popup").css("transition",this.options.speed+"s").addClass("w2ui-anim-close animating"),w2utils.unlock(document.body,300),this._promClosing(),e?i():this.tmp.closingTimer=setTimeout(i,1e3*this.options.speed),this.options.keyboard&&query(document.body).off("keydown",this.keydown),query(window).off("resize",this.handleResize)))}toggle(){let e=this.trigger("toggle",{target:"popup"});!0!==e.isCancelled&&(!0===this.options.maximized?this.min():this.max(),setTimeout(()=>{e.finish()},1e3*this.options.speed+50))}max(){if(!0!==this.options.maximized){let e=this.trigger("max",{target:"popup"});var t;!0!==e.isCancelled&&(this.status="resizing",t=query("#w2ui-popup").get(0).getBoundingClientRect(),this.options.prevSize=t.width+":"+t.height,this.resize(1e4,1e4,()=>{this.status="open",this.options.maximized=!0,e.finish()}))}}min(){if(!0===this.options.maximized){var t=this.options.prevSize.split(":");let e=this.trigger("min",{target:"popup"});!0!==e.isCancelled&&(this.status="resizing",this.options.maximized=!1,this.resize(parseInt(t[0]),parseInt(t[1]),()=>{this.status="open",this.options.prevSize=null,e.finish()}))}}clear(){query("#w2ui-popup .w2ui-popup-title").html(""),query("#w2ui-popup .w2ui-popup-body").html(""),query("#w2ui-popup .w2ui-popup-buttons").html("")}reset(){this.open(this.defaults)}message(e){return w2utils.message({owner:this,box:query("#w2ui-popup").get(0),after:".w2ui-popup-title"},e)}confirm(e){return w2utils.confirm({owner:this,box:query("#w2ui-popup"),after:".w2ui-popup-title"},e)}setFocus(e){let s=query("#w2ui-popup"),l="input, button, select, textarea, [contentEditable], .w2ui-input";null!=e?(isNaN(e)?s.find(l).filter(e).get(0):s.find(l).get(e))?.focus():(e=s.find("[name=hidden-first]").get(0))&&e.focus(),query(s).find(l+",[name=hidden-first],[name=hidden-last]").off(".keep-focus").on("blur.keep-focus",function(e){setTimeout(()=>{var e=document.activeElement,t=0<query(s).find(l).filter(e).length,i=query(e).attr("name");!t&&e&&e!==document.body&&query(s).find(l).get(0)?.focus(),"hidden-last"==i&&query(s).find(l).get(0)?.focus(),"hidden-first"==i&&query(s).find(l).get(-1)?.focus()},1)})}lock(e,t){var i=Array.from(arguments);i.unshift(query("#w2ui-popup")),w2utils.lock(...i)}unlock(e){w2utils.unlock(query("#w2ui-popup"),e)}center(e,t,i){let s,l;l=null==window.innerHeight?(s=parseInt(document.documentElement.offsetWidth),parseInt(document.documentElement.offsetHeight)):(s=parseInt(window.innerWidth),parseInt(window.innerHeight)),e=parseInt(e??this.options.width),t=parseInt(t??this.options.height),!0===this.options.maximized&&(e=s,t=l),s-10<e&&(e=s-10),l-10<t&&(t=l-10);var r=(l-t)/2,n=(s-e)/2;return i&&(query("#w2ui-popup").css({transition:"none",top:r+"px",left:n+"px",width:e+"px",height:t+"px"}),this.resizeMessages()),{top:r,left:n,width:e,height:t}}resize(e,t,i){let s=this;null==this.options.speed&&(this.options.speed=0);var{top:e,left:t,width:l,height:r}=this.center(e,t),n=this.options.speed;query("#w2ui-popup").css({transition:n+`s width, ${n}s height, ${n}s left, ${n}s top`,top:e+"px",left:t+"px",width:l+"px",height:r+"px"});let a=setInterval(()=>{s.resizeMessages()},10);setTimeout(()=>{clearInterval(a),s.resizeMessages(),"function"==typeof i&&i()},1e3*this.options.speed+50)}resizeMessages(){query("#w2ui-popup .w2ui-message").each(e=>{var t=e._msg_options,i=query("#w2ui-popup"),s=(parseInt(t.width)<10&&(t.width=10),parseInt(t.height)<10&&(t.height=10),i[0].getBoundingClientRect()),i=parseInt(i.find(".w2ui-popup-title")[0].clientHeight),l=parseInt(s.width),s=parseInt(s.height);t.width=t.originalWidth,t.width>l-10&&(t.width=l-10),t.height=t.originalHeight,t.height>s-i-5&&(t.height=s-i-5),t.originalHeight<0&&(t.height=s+t.originalHeight-i),t.originalWidth<0&&(t.width=l+2*t.originalWidth),query(e).css({left:(l-t.width)/2+"px",width:t.width+"px",height:t.height+"px"})})}}function w2alert(e,t,i){let s;t={title:w2utils.lang(t??"Notification"),body:`<div class="w2ui-centered w2ui-msg-text">${e}</div>`,showClose:!1,actions:["Ok"],cancelAction:"ok"};return(s=0<query("#w2ui-popup").length&&"closing"!=w2popup.status?w2popup.message(t):w2popup.open(t)).ok(e=>{"function"==typeof e.detail.self?.close&&e.detail.self.close(),"function"==typeof i&&i()}),s}function w2confirm(e,t,i){let s,l=e;return(l=["string","number"].includes(typeof l)?{msg:l}:l).msg&&(l.body=`<div class="w2ui-centered w2ui-msg-text">${l.msg}</div>`,delete l.msg),w2utils.extend(l,{title:w2utils.lang(t??"Confirmation"),showClose:!1,modal:!0,cancelAction:"no"}),w2utils.normButtons(l,{yes:"Yes",no:"No"}),(s=0<query("#w2ui-popup").length&&"closing"!=w2popup.status?w2popup.message(l):w2popup.open(l)).self.off(".confirm").on("action:after.confirm",e=>{"function"==typeof e.detail.self?.close&&e.detail.self.close(),"function"==typeof i&&i(e.detail.action)}),s}function w2prompt(e,t,i){let s,l=e;return(l=["string","number"].includes(typeof l)?{label:l}:l).label&&(l.focus=0,l.body=l.textarea?`<div class="w2ui-prompt textarea">
<div>${l.label}</div>
<textarea id="w2prompt" class="w2ui-input" ${l.attrs??""}
data-keydown="keydown|event" data-keyup="change|event">${l.value??""}</textarea>
</div>`:`<div class="w2ui-prompt w2ui-centered">
<label>${l.label}</label>
<input id="w2prompt" class="w2ui-input" ${l.attrs??""}
data-keydown="keydown|event" data-keyup="change|event" value="${l.value??""}">
</div>`),w2utils.extend(l,{title:w2utils.lang(t??"Notification"),showClose:!1,modal:!0,cancelAction:"cancel"}),w2utils.normButtons(l,{ok:"Ok",cancel:"Cancel"}),(s=0<query("#w2ui-popup").length&&"closing"!=w2popup.status?w2popup.message(l):w2popup.open(l)).self.box?s.self.input=query(s.self.box).find("#w2prompt").get(0):s.self.input=query("#w2ui-popup .w2ui-popup-body #w2prompt").get(0),null!==l.value&&s.self.input.select(),s.change=function(e){return s.self.on("change",e),this},s.self.off(".prompt").on("open:after.prompt",e=>{e=e.detail.box||query("#w2ui-popup .w2ui-popup-body").get(0);w2utils.bindEvents(query(e).find("#w2prompt"),{keydown(e){27==e.keyCode&&e.stopPropagation()},change(e){var t=s.self.trigger("change",{target:"prompt",originalEvent:e});!0!==t.isCancelled&&(13==e.keyCode&&e.ctrlKey&&s.self.action("Ok",e),27==e.keyCode&&s.self.action("Cancel",e),t.finish())}}),query(e).find(".w2ui-eaction").trigger("keyup")}).on("action:after.prompt",e=>{"function"==typeof e.detail.self?.close&&e.detail.self.close(),"function"==typeof i&&i(e.detail.action)}),s}let w2popup=new Dialog;class Tooltip{static active={};constructor(){this.defaults={name:null,html:"",style:"",class:"",position:"top|bottom",align:"",anchor:null,anchorClass:"",anchorStyle:"",autoShow:!1,autoShowOn:null,autoHideOn:null,arrowSize:8,margin:0,margin:1,screenMargin:2,autoResize:!0,offsetX:0,offsetY:0,maxWidth:null,maxHeight:null,watchScroll:null,watchResize:null,hideOn:null,onThen:null,onShow:null,onHide:null,onUpdate:null,onMove:null}}static observeRemove=new MutationObserver(e=>{let t=0;Object.keys(Tooltip.active).forEach(e=>{e=Tooltip.active[e];e.displayed&&(e.anchor&&e.anchor.isConnected?t++:e.hide())}),0===t&&Tooltip.observeRemove.disconnect()});trigger(e,t){var i;if(2==arguments.length&&(i=e,(e=t).type=i),e.overlay)return e.overlay.trigger(e);console.log("ERROR: cannot find overlay where to trigger events")}get(e){return 0==arguments.length?Object.keys(Tooltip.active):!0===e?Tooltip.active:Tooltip.active[e.replace(/[\s\.#]/g,"_")]}attach(t,s){let l,r,n=this;if(0!=arguments.length){1==arguments.length&&t.anchor?t=(l=t).anchor:2===arguments.length&&"string"==typeof s?s=(l={anchor:t,html:s}).html:2===arguments.length&&null!=s&&"object"==typeof s&&(s=(l=s).html),l=w2utils.extend({},this.defaults,l||{}),!(s=!s&&l.text?l.text:s)&&l.html&&(s=l.html),delete l.anchor;let e=l.name||t.id;t!=document&&t!=document.body||(t=document.body,e="context-menu"),e||(e="noname-"+Object.keys(Tooltip.active).length,console.log("NOTICE: name property is not defined for tooltip, could lead to too many instances")),e=e.replace(/[\s\.#]/g,"_"),Tooltip.active[e]?((r=Tooltip.active[e]).prevOptions=r.options,r.options=l,r.anchor=t,r.prevOptions.html==r.options.html&&r.prevOptions.class==r.options.class&&r.prevOptions.style==r.options.style||(r.needsUpdate=!0),l=r.options):(r=new w2base,Object.assign(r,{id:"w2overlay-"+e,name:e,options:l,anchor:t,displayed:!1,tmp:{observeResize:new ResizeObserver(()=>{this.resize(r.name)})},hide(){n.hide(e)}}),Tooltip.active[e]=r),Object.keys(r.options).forEach(e=>{var t=r.options[e];e.startsWith("on")&&"function"==typeof t&&(r[e]=t,delete r.options[e])}),!0===l.autoShow&&(l.autoShowOn=l.autoShowOn??"mouseenter",l.autoHideOn=l.autoHideOn??"mouseleave",l.autoShow=!1),l.autoShowOn&&(s="autoShow-"+r.name,query(t).off("."+s).on(l.autoShowOn+"."+s,e=>{n.show(r.name),e.stopPropagation()}),delete l.autoShowOn),l.autoHideOn&&(s="autoHide-"+r.name,query(t).off("."+s).on(l.autoHideOn+"."+s,e=>{n.hide(r.name),e.stopPropagation()}),delete l.autoHideOn),r.off(".attach");let i={overlay:r,then:t=>(r.on("show:after.attach",e=>{t(e)}),i),show:t=>(r.on("show.attach",e=>{t(e)}),i),hide:t=>(r.on("hide.attach",e=>{t(e)}),i),update:t=>(r.on("update.attach",e=>{t(e)}),i),move:t=>(r.on("move.attach",e=>{t(e)}),i)};return i}}update(e,t){var i=Tooltip.active[e];i?(i.needsUpdate=!0,i.options.html=t,this.show(e)):console.log(`Tooltip "${e}" is not displayed. Cannot update it.`)}show(i){if(i instanceof HTMLElement||i instanceof Object){let e=i,t=(i instanceof HTMLElement&&((e=arguments[1]||{}).anchor=i),this.attach(e));return query(t.overlay.anchor).off(".autoShow-"+t.overlay.name).off(".autoHide-"+t.overlay.name),setTimeout(()=>{this.show(t.overlay.name),this.initControls&&this.initControls(t.overlay)},1),t}let t,r=this,n=Tooltip.active[i.replace(/[\s\.#]/g,"_")];if(n){let l=n.options;if(!n||n.displayed&&!n.needsUpdate)this.resize(n?.name);else{var s=l.position.split("|"),s=["top","bottom"].includes(s[0]);let e="both"==l.align&&s?"":"white-space: nowrap;";if(l.maxWidth&&w2utils.getStrWidth(l.html,"")>l.maxWidth&&(e="width: "+l.maxWidth+"px; white-space: inherit; overflow: auto;"),e+=" max-height: "+(l.maxHeight||window.innerHeight-40)+"px;",""!==l.html&&null!=l.html){if(n.box){if(!0===(t=this.trigger("update",{target:i,overlay:n})).isCancelled)return void(n.prevOptions&&(n.options=n.prevOptions,delete n.prevOptions));query(n.box).find(".w2ui-overlay-body").attr("style",(l.style||"")+"; "+e).removeClass().addClass("w2ui-overlay-body "+l.class).html(l.html)}else{if(!0===(t=this.trigger("show",{target:i,overlay:n})).isCancelled)return;query("body").append(`<div id="${n.id}" name="${i}" style="display: none; pointer-events: none" class="w2ui-overlay"
data-click="stop" data-focusin="stop">
<style></style>
<div class="w2ui-overlay-body ${l.class}" style="${l.style||""}; ${e}">
${l.html}
</div>
</div>`),n.box=query("#"+w2utils.escapeId(n.id))[0],n.displayed=!0;s=query(n.anchor).data("tooltipName")??[];s.push(i),query(n.anchor).data("tooltipName",s),w2utils.bindEvents(n.box,{}),n.tmp.originalCSS="",0<query(n.anchor).length&&(n.tmp.originalCSS=query(n.anchor)[0].style.cssText)}this.resize(n.name),l.anchorStyle&&(n.anchor.style.cssText+=";"+l.anchorStyle),!l.anchorClass||"w2ui-focus"==l.anchorClass&&n.anchor==document.body||query(n.anchor).addClass(l.anchorClass),"string"==typeof l.hideOn&&(l.hideOn=[l.hideOn]),Array.isArray(l.hideOn)||(l.hideOn=[]),Object.assign(n.tmp,{scrollLeft:document.body.scrollLeft,scrollTop:document.body.scrollTop});{let t=e=>{r.hide(n.name)},i=query(n.anchor),s="tooltip-"+n.name;query("body").off("."+s),l.hideOn.includes("doc-click")&&(["INPUT","TEXTAREA"].includes(n.anchor.tagName)&&i.off(`.${s}-doc`).on(`click.${s}-doc`,e=>{e.stopPropagation()}),query("body").on("click."+s,t));l.hideOn.includes("focus-change")&&query("body").on("focusin."+s,e=>{document.activeElement!=n.anchor&&r.hide(n.name)});["INPUT","TEXTAREA"].includes(n.anchor.tagName)&&(i.off("."+s),l.hideOn.forEach(e=>{-1==["doc-click","focus-change"].indexOf(e)&&i.on(e+"."+s,{once:!0},t)}))}{var a=document.body;let e="tooltip-"+n.name,t=a;"BODY"==a.tagName&&(t=a.ownerDocument);query(t).off("."+e).on("scroll."+e,e=>{Object.assign(n.tmp,{scrollLeft:a.scrollLeft,scrollTop:a.scrollTop}),r.resize(n.name)})}return query(n.box).show(),n.tmp.observeResize.observe(n.box),Tooltip.observeRemove.observe(document.body,{subtree:!0,childList:!0}),query(n.box).css("opacity",1).find(".w2ui-overlay-body").html(l.html),setTimeout(()=>{query(n.box).css({"pointer-events":"auto"}).data("ready","yes")},100),delete n.needsUpdate,n.box.overlay=n,t&&t.finish(),{overlay:n}}r.hide(i)}}}hide(e){let i;if(0==arguments.length)Object.keys(Tooltip.active).forEach(e=>{this.hide(e)});else if(e instanceof HTMLElement)(query(e).data("tooltipName")??[]).forEach(e=>{this.hide(e)});else if("string"==typeof e&&(e=e.replace(/[\s\.#]/g,"_"),i=Tooltip.active[e]),i&&i.box){delete Tooltip.active[e];e=this.trigger("hide",{target:e,overlay:i});if(!0!==e.isCancelled){var s="tooltip-"+i.name;i.tmp.observeResize?.disconnect(),i.options.watchScroll&&query(i.options.watchScroll).off(".w2scroll-"+i.name);let t=0;Object.keys(Tooltip.active).forEach(e=>{Tooltip.active[e].displayed&&t++}),0==t&&Tooltip.observeRemove.disconnect(),query("body").off("."+s),query(document).off("."+s),i.box.remove(),i.box=null,i.displayed=!1;var l=query(i.anchor).data("tooltipName")??[];-1!=l.indexOf(i.name)&&l.splice(l.indexOf(i.name),1),0==l.length?query(i.anchor).removeData("tooltipName"):query(i.anchor).data("tooltipName",l),i.anchor.style.cssText=i.tmp.originalCSS,query(i.anchor).off("."+s).removeClass(i.options.anchorClass),e.finish()}}}resize(i){if(0==arguments.length)Object.keys(Tooltip.active).forEach(e=>{e=Tooltip.active[e];e.displayed&&this.resize(e.name)});else{var s=Tooltip.active[i.replace(/[\s\.#]/g,"_")];let t=this.getPosition(s.name);var l=t.left+"x"+t.top;let e;s.tmp.lastPos!=l&&(e=this.trigger("move",{target:i,overlay:s,pos:t})),query(s.box).css({left:t.left+"px",top:t.top+"px"}).then(e=>{null!=t.width&&e.css("width",t.width+"px").find(".w2ui-overlay-body").css("width","100%"),null!=t.height&&e.css("height",t.height+"px").find(".w2ui-overlay-body").css("height","100%")}).find(".w2ui-overlay-body").removeClass("w2ui-arrow-right w2ui-arrow-left w2ui-arrow-top w2ui-arrow-bottom").addClass(t.arrow.class).closest(".w2ui-overlay").find("style").text(t.arrow.style),s.tmp.lastPos!=l&&e&&(s.tmp.lastPos=l,e.finish())}}getPosition(e){let g=Tooltip.active[e.replace(/[\s\.#]/g,"_")];if(g&&g.box){let t=g.options;(g.tmp.resizedY||g.tmp.resizedX)&&query(g.box).css({width:"",height:"",scroll:"auto"});var e=w2utils.scrollBarSize(),y=!(document.body.scrollWidth==document.body.clientWidth),w=!(document.body.scrollHeight==document.body.clientHeight);let i={width:window.innerWidth-(w?e:0),height:window.innerHeight-(y?e:0)};var b,v=("auto"==t.position?"top|bottom|right|left":t.position).split("|");let s=["top","bottom"].includes(v[0]),l=g.box.getBoundingClientRect(),r=g.anchor.getBoundingClientRect(),n=(g.anchor==document.body&&({x,y:_,width:q,height:C}=t.originalEvent,r={left:x-2,top:_-4,width:q,height:C,arrow:"none"}),t.arrowSize),a=("none"==r.arrow&&(n=0),{top:r.top,bottom:i.height-(r.top+r.height)-+(y?e:0),left:r.left,right:i.width-(r.left+r.width)+(w?e:0)});l.width<22&&(l.width=22),l.height<14&&(l.height=14);let o,h,d,u,c="",p={offset:0,class:"",style:`#${g.id} { --tip-size: ${n}px; }`},f={left:0,top:0},m={posX:"",x:0,posY:"",y:0};v.forEach(e=>{["top","bottom"].includes(e)&&(!c&&l.height+n/1.893<a[e]&&(c=e),a[e]>m.y)&&Object.assign(m,{posY:e,y:a[e]}),["left","right"].includes(e)&&(!c&&l.width+n/1.893<a[e]&&(c=e),a[e]>m.x)&&Object.assign(m,{posX:e,x:a[e]})}),c=c||(s?m.posY:m.posX),t.autoResize&&(["top","bottom"].includes(c)&&(l.height>a[c]?(u=a[c],g.tmp.resizedY=!0):g.tmp.resizedY=!1),["left","right"].includes(c))&&(l.width>a[c]?(d=a[c],g.tmp.resizedX=!0):g.tmp.resizedX=!1);var x=c;switch(p.class=r.arrow||"w2ui-arrow-"+x,x){case"top":o=r.left+(r.width-(d??l.width))/2,h=r.top-(u??l.height)-n/1.5+1;break;case"bottom":o=r.left+(r.width-(d??l.width))/2,h=r.top+r.height+n/1.25+1;break;case"left":o=r.left-(d??l.width)-n/1.2-1,h=r.top+(r.height-(u??l.height))/2;break;case"right":o=r.left+r.width+n/1.2+1,h=r.top+(r.height-(u??l.height))/2}if(s)"left"==t.align&&(f.left=r.left-o,o=r.left),"right"==t.align&&(f.left=r.left+r.width-(d??l.width)-o,o=r.left+r.width-(d??l.width)),["top","bottom"].includes(c)&&t.align.startsWith("both")&&(b=t.align.split(":")[1]??50,r.width>=b)&&(o=r.left,d=r.width),"top"==t.align&&(f.top=r.top-h,h=r.top),"bottom"==t.align&&(f.top=r.top+r.height-(u??l.height)-h,h=r.top+r.height-(u??l.height)),["left","right"].includes(c)&&t.align.startsWith("both")&&(b=t.align.split(":")[1]??50,r.height>=b)&&(h=r.top,u=r.height);{let e;(["left","right"].includes(t.align)&&r.width<(d??l.width)||["top","bottom"].includes(t.align)&&r.height<(u??l.height))&&(e=!0);var _="right"==c?n:t.screenMargin,q="bottom"==c?n:t.screenMargin,C=i.width-(d??l.width)-("left"==c?n:t.screenMargin),y=i.height-(u??l.height)-("top"==c?n:t.screenMargin)+3;(["top","bottom"].includes(c)||t.autoResize)&&(o<_&&(e=!0,f.left-=o,o=_),o>C)&&(e=!0,f.left-=o-C,o+=C-o);(["left","right"].includes(c)||t.autoResize)&&(h<q&&(e=!0,f.top-=h,h=q),h>y)&&(e=!0,f.top-=h-y,h+=y-h);e&&(_=s?"left":"top",C=s?"width":"height",p.offset=-f[_],q=l[C]/2-n,Math.abs(p.offset)>q+n&&(p.class=""),Math.abs(p.offset)>q&&(p.offset=p.offset<0?-q:q),p.style=w2utils.stripSpaces(`#${g.id} .w2ui-overlay-body:after,
#${g.id} .w2ui-overlay-body:before {
--tip-size: ${n}px;
margin-${_}: ${p.offset}px;
}`))}w="top"==c?-t.margin:"bottom"==c?t.margin:0,e="left"==c?-t.margin:"right"==c?t.margin:0;return h=Math.floor(100*(h+parseFloat(t.offsetY)+parseFloat(w)))/100,{left:o=Math.floor(100*(o+parseFloat(t.offsetX)+parseFloat(e)))/100,top:h,arrow:p,adjust:f,width:d,height:u,pos:c}}}}class ColorTooltip extends Tooltip{constructor(){super(),this.palette=[["000000","333333","555555","777777","888888","999999","AAAAAA","CCCCCC","DDDDDD","EEEEEE","F7F7F7","FFFFFF"],["FF011B","FF9838","FFC300","FFFD59","86FF14","14FF7A","2EFFFC","2693FF","006CE7","9B24F4","FF21F5","FF0099"],["FFEAEA","FCEFE1","FCF4DC","FFFECF","EBFFD9","D9FFE9","E0FFFF","E8F4FF","ECF4FC","EAE6F4","FFF5FE","FCF0F7"],["F4CCCC","FCE5CD","FFF1C2","FFFDA1","D5FCB1","B5F7D0","BFFFFF","D6ECFF","CFE2F3","D9D1E9","FFE3FD","FFD9F0"],["EA9899","F9CB9C","FFE48C","F7F56F","B9F77E","84F0B1","83F7F7","B5DAFF","9FC5E8","B4A7D6","FAB9F6","FFADDE"],["E06666","F6B26B","DEB737","E0DE51","8FDB48","52D189","4EDEDB","76ACE3","6FA8DC","8E7CC3","E07EDA","F26DBD"],["CC0814","E69138","AB8816","B5B20E","6BAB30","27A85F","1BA8A6","3C81C7","3D85C6","674EA7","A14F9D","BF4990"],["99050C","B45F17","80650E","737103","395E14","10783D","13615E","094785","0A5394","351C75","780172","782C5A"]],this.defaults=w2utils.extend({},this.defaults,{advanced:!1,transparent:!0,position:"top|bottom",class:"w2ui-white",color:"",liveUpdate:!0,arrowSize:12,autoResize:!1,anchorClass:"w2ui-focus",autoShowOn:"focus",hideOn:["doc-click","focus-change"],onSelect:null,onLiveUpdate:null})}attach(e,t){let i;1==arguments.length&&e.anchor?e=(i=e).anchor:2===arguments.length&&null!=t&&"object"==typeof t&&((i=t).anchor=e);t=i.hideOn;i=w2utils.extend({},this.defaults,i||{}),t&&(i.hideOn=t),i.style+="; padding: 0;",i.transparent&&"333333"==this.palette[0][1]&&(this.palette[0].splice(1,1),this.palette[0].push("")),i.transparent||"333333"==this.palette[0][1]||(this.palette[0].splice(1,0,"333333"),this.palette[0].pop()),i.color&&(i.color=String(i.color).toUpperCase()),"string"==typeof i.color&&"#"===i.color.substr(0,1)&&(i.color=i.color.substr(1)),this.index=[-1,-1];let s=super.attach(i),l=s.overlay;return l.options.html=this.getColorHTML(l.name,i),l.on("show.attach",e=>{var e=e.detail.overlay,t=e.anchor,i=e.options;["INPUT","TEXTAREA"].includes(t.tagName)&&!i.color&&t.value&&(e.tmp.initColor=t.value),delete e.newColor}),l.on("show:after.attach",e=>{var t;s.overlay?.box&&(t=query(s.overlay.box).find(".w2ui-eaction"),w2utils.bindEvents(t,this),this.initControls(s.overlay))}),l.on("update:after.attach",e=>{var t;s.overlay?.box&&(t=query(s.overlay.box).find(".w2ui-eaction"),w2utils.bindEvents(t,this),this.initControls(s.overlay))}),l.on("hide.attach",e=>{var e=e.detail.overlay,t=e.anchor,i=e.newColor??e.options.color??"",t=(["INPUT","TEXTAREA"].includes(t.tagName)&&t.value!=i&&(t.value=i),this.trigger("select",{color:i,target:e.name,overlay:e}));!0!==t.isCancelled&&t.finish()}),s.liveUpdate=t=>(l.on("liveUpdate.attach",e=>{t(e)}),s),s.select=t=>(l.on("select.attach",e=>{t(e)}),s),s}select(e,t){let i;this.index=[-1,-1],"string"!=typeof t&&(i=t.target,this.index=query(i).attr("index").split(":"),t=query(i).closest(".w2ui-overlay").attr("name"));var s=this.get(t),t=this.trigger("liveUpdate",{color:e,target:t,overlay:s,param:arguments[1]});!0!==t.isCancelled&&(["INPUT","TEXTAREA"].includes(s.anchor.tagName)&&s.options.liveUpdate&&query(s.anchor).val(e),s.newColor=e,query(s.box).find(".w2ui-selected").removeClass("w2ui-selected"),i&&query(i).addClass("w2ui-selected"),t.finish())}nextColor(e){var t=this.palette;switch(e){case"up":this.index[0]--;break;case"down":this.index[0]++;break;case"right":this.index[1]++;break;case"left":this.index[1]--}return this.index[0]<0&&(this.index[0]=0),this.index[0]>t.length-2&&(this.index[0]=t.length-2),this.index[1]<0&&(this.index[1]=0),this.index[1]>t[0].length-1&&(this.index[1]=t[0].length-1),t[this.index[0]][this.index[1]]}tabClick(e,t){"string"!=typeof t&&(t=query(t.target).closest(".w2ui-overlay").attr("name"));var t=this.get(t),i=query(t.box).find(`.w2ui-color-tab:nth-child(${e})`);query(t.box).find(".w2ui-color-tab").removeClass("w2ui-selected"),query(i).addClass("w2ui-selected"),query(t.box).find(".w2ui-tab-content").hide().closest(".w2ui-colors").find(".tab-"+e).show()}getColorHTML(s,l){let r=`
<div class="w2ui-colors">
<div class="w2ui-tab-content tab-1">`;for(let i=0;i<this.palette.length;i++){r+='<div class="w2ui-color-row">';for(let t=0;t<this.palette[i].length;t++){var n=this.palette[i][t];let e="FFFFFF"===n?"; border: 1px solid #efefef":"";r+=`
<div class="w2ui-color w2ui-eaction ${""===n?"w2ui-no-color":""} ${l.color==n?"w2ui-selected":""}"
style="background-color: #${n+e};" name="${n}" index="${i}:${t}"
data-mousedown="select|'${n}'|event" data-mouseup="hide|${s}">
</div>`}r+="</div>",i<2&&(r+='<div style="height: 8px"></div>')}return r=(r=(r+="</div>")+`
<div class="w2ui-tab-content tab-2" style="display: none">
<div class="color-info">
<div class="color-preview-bg"><div class="color-preview"></div><div class="color-original"></div></div>
<div class="color-part">
<span>H</span> <input class="w2ui-input" name="h" maxlength="3" max="360" tabindex="101">
<span>R</span> <input class="w2ui-input" name="r" maxlength="3" max="255" tabindex="104">
</div>
<div class="color-part">
<span>S</span> <input class="w2ui-input" name="s" maxlength="3" max="100" tabindex="102">
<span>G</span> <input class="w2ui-input" name="g" maxlength="3" max="255" tabindex="105">
</div>
<div class="color-part">
<span>V</span> <input class="w2ui-input" name="v" maxlength="3" max="100" tabindex="103">
<span>B</span> <input class="w2ui-input" name="b" maxlength="3" max="255" tabindex="106">
</div>
<div class="color-part opacity">
<span>${w2utils.lang("Opacity")}</span>
<input class="w2ui-input" name="a" maxlength="5" max="1" tabindex="107">
</div>
</div>
<div class="palette" name="palette">
<div class="palette-bg"></div>
<div class="value1 move-x move-y"></div>
</div>
<div class="rainbow" name="rainbow">
<div class="value2 move-x"></div>
</div>
<div class="alpha" name="alpha">
<div class="alpha-bg"></div>
<div class="value2 move-x"></div>
</div>
</div>`)+`
<div class="w2ui-color-tabs">
<div class="w2ui-color-tab selected w2ui-eaction" data-click="tabClick|1|event|this"><span class="w2ui-icon w2ui-icon-colors"></span></div>
<div class="w2ui-color-tab w2ui-eaction" data-click="tabClick|2|event|this"><span class="w2ui-icon w2ui-icon-settings"></span></div>
<div style="padding: 5px; width: 100%; text-align: right;">
${"string"==typeof l.html?l.html:""}
</div>
</div>`}initControls(a){let n,o=this;var e=a.options;let h=w2utils.parseColor(e.color||a.tmp.initColor),d=(null==h&&(h={r:140,g:150,b:160,a:1}),w2utils.rgb2hsv(h));!0===e.advanced&&this.tabClick(2,a.name),u(d,!0,!0),query(a.box).find("input").off(".w2color").on("change.w2color",e=>{e=query(e.target);let t=parseFloat(e.val());var i=parseFloat(e.attr("max")),i=(isNaN(t)&&(t=0,e.val(0)),1<i&&(t=parseInt(t)),0<i&&t>i&&(e.val(i),t=i),t<0&&(e.val(0),t=0),e.attr("name")),e={};-1!==["r","g","b","a"].indexOf(i)?(h[i]=t,d=w2utils.rgb2hsv(h)):-1!==["h","s","v"].indexOf(i)&&(e[i]=t),u(e,!0)}),query(a.box).find(".color-original").off(".w2color").on("click.w2color",e=>{e=w2utils.parseColor(query(e.target).css("background-color"));null!=e&&(h=e,u(d=w2utils.rgb2hsv(h),!0))});e=`${w2utils.isIOS?"touchstart":"mousedown"}.w2color`;let s=`${w2utils.isIOS?"touchend":"mouseup"}.w2color`,l=`${w2utils.isIOS?"touchmove":"mousemove"}.w2color`;function u(e,t,i){null!=e.h&&(d.h=e.h),null!=e.s&&(d.s=e.s),null!=e.v&&(d.v=e.v),null!=e.a&&(h.a=e.a,d.a=e.a);let s="rgba("+(h=w2utils.hsv2rgb(d)).r+","+h.g+","+h.b+","+h.a+")",l=[Number(h.r).toString(16).toUpperCase(),Number(h.g).toString(16).toUpperCase(),Number(h.b).toString(16).toUpperCase(),Math.round(255*Number(h.a)).toString(16).toUpperCase()];var r,n;l.forEach((e,t)=>{1===e.length&&(l[t]="0"+e)}),s=l[0]+l[1]+l[2]+l[3],1===h.a&&(s=l[0]+l[1]+l[2]),query(a.box).find(".color-preview").css("background-color","#"+s),query(a.box).find("input").each(e=>{e.name&&(null!=h[e.name]&&(e.value=h[e.name]),null!=d[e.name]&&(e.value=d[e.name]),"a"===e.name)&&(e.value=h.a)}),i?(e=a.tmp?.initColor||s,query(a.box).find(".color-original").css("background-color","#"+e),query(a.box).find(".w2ui-colors .w2ui-selected").removeClass("w2ui-selected"),query(a.box).find(`.w2ui-colors [name="${e}"]`).addClass("w2ui-selected"),8==s.length&&o.tabClick(2,a.name)):o.select(s,a.name),t&&(i=query(a.box).find(".palette .value1"),e=query(a.box).find(".rainbow .value2"),t=query(a.box).find(".alpha .value2"),r=parseInt(i[0].clientWidth)/2,n=parseInt(e[0].clientWidth)/2,i.css({left:150*d.s/100-r+"px",top:125*(100-d.v)/100-r+"px"}),e.css("left",d.h/2.4-n+"px"),t.css("left",150*h.a-n+"px"),c())}function c(){var e=w2utils.hsv2rgb(d.h,100,100),e=`${e.r},${e.g},`+e.b;query(a.box).find(".palette").css("background-image",`linear-gradient(90deg, rgba(${e},0) 0%, rgba(${e},1) 100%)`)}function r(e){query("body").off(".w2color")}function p(e){var t=n.el,i=e.pageX-n.x,e=e.pageY-n.y;let s=n.left+i,l=n.top+e;var i=parseInt(t.prop("clientWidth"))/2,e=(s<-i&&(s=-i),l<-i&&(l=-i),s>n.width-i&&(s=n.width-i),l>n.height-i&&(l=n.height-i),t.hasClass("move-x")&&t.css({left:s+"px"}),t.hasClass("move-y")&&t.css({top:l+"px"}),query(t.get(0).parentNode).attr("name")),r=parseInt(t.css("left"))+i,t=parseInt(t.css("top"))+i;"palette"===e&&u({s:Math.round(r/n.width*100),v:Math.round(100-t/n.height*100)}),"rainbow"===e&&(u({h:Math.round(2.4*r)}),c()),"alpha"===e&&u({a:parseFloat(Number(r/150).toFixed(2))})}query(a.box).find(".palette, .rainbow, .alpha").off(".w2color").on(e+".w2color",function(e){var t=query(this).find(".value1, .value2"),i=parseInt(t.prop("clientWidth"))/2;t.hasClass("move-x")&&t.css({left:e.offsetX-i+"px"});t.hasClass("move-y")&&t.css({top:e.offsetY-i+"px"});n={el:t,x:e.pageX,y:e.pageY,width:t.prop("parentNode").clientWidth,height:t.prop("parentNode").clientHeight,left:parseInt(t.css("left")),top:parseInt(t.css("top"))},p(e),query("body").off(".w2color").on(l,p).on(s,r)})}}class MenuTooltip extends Tooltip{constructor(){super(),this.defaults=w2utils.extend({},this.defaults,{type:"normal",items:[],index:null,render:null,spinner:!1,msgNoItems:w2utils.lang("No items found"),topHTML:"",menuStyle:"",filter:!1,markSearch:!1,match:"contains",search:!1,altRows:!1,arrowSize:10,align:"left",position:"bottom|top",class:"w2ui-white",anchorClass:"w2ui-focus",autoShowOn:"focus",hideOn:["doc-click","focus-change","select"],onSelect:null,onSubMenu:null,onRemove:null})}attach(e,t){let i;1==arguments.length&&e.anchor?e=(i=e).anchor:2===arguments.length&&null!=t&&"object"==typeof t&&((i=t).anchor=e);t=i.hideOn;i=w2utils.extend({},this.defaults,i||{}),t&&(i.hideOn=t),i.style+="; padding: 0;",null==i.items&&(i.items=[]),i.html=this.getMenuHTML(i);let s=super.attach(i),l=s.overlay;return l.on("show:after.attach, update:after.attach",e=>{if(s.overlay?.box){let e="";l.selected=null,l.options.items=w2utils.normMenu(l.options.items),["INPUT","TEXTAREA"].includes(l.anchor.tagName)&&(e=l.anchor.value,l.selected=l.anchor.dataset.selectedIndex);var t=query(s.overlay.box).find(".w2ui-eaction");w2utils.bindEvents(t,this),this.applyFilter(l.name,null,e).then(e=>{l.tmp.searchCount=e.count,l.tmp.search=e.search,this.refreshSearch(l.name),this.initControls(s.overlay),this.refreshIndex(l.name)})}}),l.on("hide:after.attach",e=>{w2tooltip.hide(l.name+"-tooltip")}),s.select=t=>(l.on("select.attach",e=>{t(e)}),s),s.remove=t=>(l.on("remove.attach",e=>{t(e)}),s),s.subMenu=t=>(l.on("subMenu.attach",e=>{t(e)}),s),s}update(e,t){var i,s=Tooltip.active[e];s?((i=s.options).items!=t&&(i.items=t),t=this.getMenuHTML(i),i.html!=t&&(i.html=t,s.needsUpdate=!0,this.show(e))):console.log(`Tooltip "${e}" is not displayed. Cannot update it.`)}initControls(i){query(i.box).find(".w2ui-menu:not(.w2ui-sub-menu)").off(".w2menu").on("mouseDown.w2menu",{delegate:".w2ui-menu-item"},e=>{var t=e.delegate.dataset;this.menuDown(i,e,t.index,t.parents)}).on((w2utils.isIOS?"touchStart":"click")+".w2menu",{delegate:".w2ui-menu-item"},e=>{var t=e.delegate.dataset;this.menuClick(i,e,parseInt(t.index),t.parents)}).find(".w2ui-menu-item").off(".w2menu").on("mouseEnter.w2menu",e=>{var t=e.target.dataset,t=i.options.items[t.index]?.tooltip;t&&w2tooltip.show({name:i.name+"-tooltip",anchor:e.target,html:t,position:"right|left",hideOn:["doc-click"]})}).on("mouseLeave.w2menu",e=>{w2tooltip.hide(i.name+"-tooltip")}),["INPUT","TEXTAREA"].includes(i.anchor.tagName)&&query(i.anchor).off(".w2menu").on("input.w2menu",e=>{}).on("keyup.w2menu",e=>{e._searchType="filter",this.keyUp(i,e)}),i.options.search&&query(i.box).find("#menu-search").off(".w2menu").on("keyup.w2menu",e=>{e._searchType="search",this.keyUp(i,e)})}getCurrent(e,t){var e=Tooltip.active[e.replace(/[\s\.#]/g,"_")],i=e.options;let s=(t||(e.selected??"")).split("-");var t=s.length-1,e=s[t],l=s.slice(0,s.length-1).join("-"),e=w2utils.isInt(e)?parseInt(e):0;let r=i.items;return s.forEach((e,t)=>{t<s.length-1&&(r=r[e].items)}),{last:t,index:e,items:r,item:r[e],parents:l}}getMenuHTML(h,e,d,u){if(h.spinner)return`
<div class="w2ui-menu">
<div class="w2ui-no-items">
<div class="w2ui-spinner"></div>
${w2utils.lang("Loading...")}
</div>
</div>`;u=u||[],null==e&&(e=h.items),Array.isArray(e)||(e=[]);let c=0,t=null,i="",p=(!d&&h.search&&(i+=`
<div class="w2ui-menu-search">
<span class="w2ui-icon w2ui-icon-search"></span>
<input id="menu-search" class="w2ui-input" type="text"/>
</div>`,e.forEach(e=>e.hidden=!1)),!d&&h.topHTML&&(i+=`<div class="w2ui-menu-top">${h.topHTML}</div>`),`
${i}
<div class="w2ui-menu ${d?"w2ui-sub-menu":""}" ${d?"":`style="${h.menuStyle}"`}
data-parent="${u}">
`);return e.forEach((r,n)=>{t=r.icon;var a=(0<u.length?u.join("-")+"-":"")+n;if(null==t&&(t=null),-1==["radio","check"].indexOf(h.type)||Array.isArray(r.items)||!1===r.group||(t=!0===r.checked?"w2ui-icon-check":"w2ui-icon-empty"),!0!==r.hidden){let i=r.text,s="",l="";if("function"==typeof(i="function"==typeof h.render?h.render(r,h):i)&&(i=i(r,h)),t&&("<"!==String(t).slice(0,1)&&(t=`<span class="w2ui-icon ${t}"></span>`),s=`<div class="menu-icon">${t}</span></div>`),"break"!==r.type&&null!=i&&""!==i&&"--"!=String(i).substr(0,2)){var o=["w2ui-menu-item"];1==h.altRows&&o.push(c%2==0?"w2ui-even":"w2ui-odd");let e=1,t=(""===s&&e++,null==r.count&&null==r.hotkey&&!0!==r.remove&&null==r.items&&e++,null==r.tooltip&&null!=r.hint&&(r.tooltip=r.hint),"");if(!0===r.remove)t='<span class="remove">x</span>';else if(null!=r.items){let e=[];"function"==typeof r.items?e=r.items(r):Array.isArray(r.items)&&(e=r.items),t="<span></span>",l=`
<div class="w2ui-sub-menu-box" style="${r.expanded?"":"display: none"}">
${this.getMenuHTML(h,e,!0,u.concat(n))}
</div>`}else null!=r.count&&(t+="<span>"+r.count+"</span>"),null!=r.hotkey&&(t+='<span class="hotkey">'+r.hotkey+"</span>");!0===r.disabled&&o.push("w2ui-disabled"),!0===r._noSearchInside&&o.push("w2ui-no-search-inside"),""!==l&&(o.push("has-sub-menu"),r.expanded?o.push("expanded"):o.push("collapsed")),p+=`
<div index="${a}" class="${o.join(" ")}" style="${r.style||""}"
data-index="${n}" data-parents="${u.join("-")}">
<div style="width: ${(d?20:0)+parseInt(r.indent??0)}px"></div>
${s}
<div class="menu-text" colspan="${e}">${w2utils.lang(i)}</div>
<div class="menu-extra">${t}</div>
</div>
`+l,c++}else{o=(i??"").replace(/^-+/g,"");p+=`
<div index="${a}" class="w2ui-menu-divider ${""!=o?"has-text":""}">
<div class="line"></div>
${o?`<div class="text">${o}</div>`:""}
</div>`}}e[n]=r}),0===c&&h.msgNoItems&&(p+=`
<div class="w2ui-no-items">
${w2utils.lang(h.msgNoItems)}
</div>`),p+="</div>"}refreshIndex(e){var t,i,e=Tooltip.active[e.replace(/[\s\.#]/g,"_")];e&&(e.displayed||this.show(e.name),t=query(e.box).find(".w2ui-overlay-body").get(0),i=query(e.box).find(".w2ui-menu-search, .w2ui-menu-top").get(0),query(e.box).find(".w2ui-menu-item.w2ui-selected").removeClass("w2ui-selected"),e=query(e.box).find(`.w2ui-menu-item[index="${e.selected}"]`).addClass("w2ui-selected").get(0))&&(e.offsetTop+e.clientHeight>t.clientHeight+t.scrollTop&&e.scrollIntoView({behavior:"smooth",block:"start",inline:"start"}),e.offsetTop<t.scrollTop+(i?i.clientHeight:0))&&e.scrollIntoView({behavior:"smooth",block:"end",inline:"end"})}refreshSearch(i){let s=Tooltip.active[i.replace(/[\s\.#]/g,"_")];s&&(s.displayed||this.show(s.name),query(s.box).find(".w2ui-no-items").hide(),query(s.box).find(".w2ui-menu-item, .w2ui-menu-divider").each(e=>{var t;this.getCurrent(i,e.getAttribute("index")).item?.hidden?query(e).hide():((t=s.tmp?.search)&&s.options.markSearch&&w2utils.marker(e,t,{onlyFirst:"begins"==s.options.match}),query(e).show())}),query(s.box).find(".w2ui-sub-menu").each(e=>{var t=query(e).find(".w2ui-menu-item").get().some(e=>"none"!=e.style.display);this.getCurrent(i,e.dataset.parent).item.expanded&&(t?query(e).parent().show():query(e).parent().hide())}),0!=s.tmp.searchCount&&0!=s.options?.items?.length||(0==query(s.box).find(".w2ui-no-items").length&&query(s.box).find(".w2ui-menu:not(.w2ui-sub-menu)").append(`
<div class="w2ui-no-items">
${w2utils.lang(s.options.msgNoItems)}
</div>`),query(s.box).find(".w2ui-no-items").show()))}applyFilter(s,t,l,i){let r=0;var n=Tooltip.active[s.replace(/[\s\.#]/g,"_")];let a=n.options,o,h;var d=new Promise((e,t)=>{o=e,h=t});null==l&&(l=["INPUT","TEXTAREA"].includes(n.anchor.tagName)?n.anchor.value:"");let u=[];a.selected&&(Array.isArray(a.selected)?u=a.selected.map(e=>e?.id??e):a.selected?.id&&(u=[a.selected.id])),n.tmp.activeChain=null;var c=n.tmp.remote??{hasMore:!0,emtpySet:!1,search:null,total:-1};if(null==t&&a.url&&c.hasMore&&c.search!==l){let e=!0,t=w2utils.lang("Loading...");l.length<a.minLength&&!0!==c.emptySet&&(t=w2utils.lang("${count} letters or more...",{count:a.minLength}),e=!1,""===l)&&(t=w2utils.lang(a.msgSearch)),query(n.box).find(".w2ui-no-items").html(t),c.search=l,a.items=[],n.tmp.remote=c,e&&this.request(n,l,i).then(e=>{this.update(s,e),this.applyFilter(s,null,l).then(e=>{o(e)})}).catch(e=>{console.log("Server Request error",e)})}else{let e;null==t&&!0===(e=this.trigger("search",{search:l,overlay:n,prom:d,resolve:o,reject:h})).isCancelled||(null==t&&(t=n.options.items),!1===a.filter?o({count:-1,search:l}):(t.forEach(t=>{let e="",i="";-1!==["is","begins","begins with"].indexOf(a.match)&&(e="^"),-1!==["is","ends","ends with"].indexOf(a.match)&&(i="$");try{new RegExp(e+l+i,"i").test(t.text)||"..."===t.text?t.hidden=!1:t.hidden=!0}catch(e){}a.hideSelected&&u.includes(t.id)&&(t.hidden=!0),Array.isArray(t.items)&&0<t.items.length&&(delete t._noSearchInside,this.applyFilter(s,t.items,l).then(e=>{e=e.count;0<e&&(r+=e,t.hidden&&(t._noSearchInside=!0),l&&(t.expanded=!0),t.hidden=!1)})),!0!==t.hidden&&r++}),o({count:r,search:l}),e?.finish()))}return d}request(l,r,e){let n=l.options,a=l.tmp.remote,o,h;return(0===n.items.length&&0!==a.total||a.total==n.cacheMax&&r.length>a.search.length||r.length>=a.search.length&&r.substr(0,a.search.length)!==a.search||r.length<a.search.length)&&(a.controller&&a.controller.abort(),a.loading=!0,clearTimeout(a.timeout),a.timeout=setTimeout(()=>{var e=n.url;let i={search:r,max:n.cacheMax};Object.assign(i,n.postData);var t,s=this.trigger("request",{search:r,overlay:l,url:e,postData:i,httpMethod:n.method??"GET",httpHeaders:{}});!0!==s.isCancelled&&(e=new URL(s.detail.url,location),t=w2utils.prepareParams(e,{method:s.detail.httpMethod,headers:s.detail.httpHeaders,body:s.detail.postData}),a.controller=new AbortController,t.signal=a.controller.signal,fetch(e,t).then(e=>e.json()).then(e=>{a.controller=null;var t=l.trigger("load",{search:i.search,overlay:l,data:e});!0!==t.isCancelled&&("string"==typeof(e=t.detail.data)&&(e=JSON.parse(e)),null==(e=Array.isArray(e)?{records:e}:e).records&&null!=e.items&&(e.records=e.items,delete e.items),e.error||null!=e.records||(e.records=[]),Array.isArray(e.records)?(e.records.length>=n.cacheMax?(e.records.splice(n.cacheMax,e.records.length),a.hasMore=!0):a.hasMore=!1,null==n.recId&&null!=n.recid&&(n.recId=n.recid),(n.recId||n.recText)&&e.records.forEach(e=>{"string"==typeof n.recId&&(e.id=e[n.recId]),"function"==typeof n.recId&&(e.id=n.recId(e)),"string"==typeof n.recText&&(e.text=e[n.recText]),"function"==typeof n.recText&&(e.text=n.recText(e))}),a.loading=!1,a.search=r,a.total=e.records.length,a.lastError="",a.emptySet=""===r&&0===e.records.length,t.finish(),o(w2utils.normMenu(e.records))):console.error("ERROR: server did not return proper data structure","\n"," - it should return",{records:[{id:1,text:"item"}]},"\n"," - or just an array ",[{id:1,text:"item"}],"\n"," - or if errorr ",{error:!0,message:"error message"}))}).catch(e=>{var t=this.trigger("error",{overlay:l,search:r,error:e});!0!==t.isCancelled&&("AbortError"!==e?.name&&console.error("ERROR: Server communication failed.","\n"," - it should return",{records:[{id:1,text:"item"}]},"\n"," - or just an array ",[{id:1,text:"item"}],"\n"," - or if errorr ",{error:!0,message:"error message"}),a.loading=!1,a.search="",a.total=-1,a.emptySet=!0,a.lastError=t.detail.error||"Server communication failed",n.items=[],t.finish(),h())}),s.finish())},e?n.debounce??350:0)),new Promise((e,t)=>{o=e,h=t})}getActiveChain(i,e,s=[],l=[],t){var r=Tooltip.active[i.replace(/[\s\.#]/g,"_")];return null!=r.tmp.activeChain?r.tmp.activeChain:((e=null==e?r.options.items:e).forEach((e,t)=>{e.hidden||e.disabled||e?.text?.startsWith("--")||(l.push(s.concat([t]).join("-")),Array.isArray(e.items)&&0<e.items.length&&e.expanded&&(s.push(t),this.getActiveChain(i,e.items,s,l,!0),s.pop()))}),null==t&&(r.tmp.activeChain=l),l)}menuDown(e,t,i,s){e=e.options;let l=e.items;var r=query(t.delegate).find(".w2ui-icon");let n=query(t.target).closest(".w2ui-menu:not(.w2ui-sub-menu)"),a=("string"==typeof s&&""!==s&&s.split("-").forEach(e=>{l=l[e].items}),l[i]);if(!a.disabled){let l=(i,s)=>{i.forEach((e,t)=>{e.id!=a.id&&(e.group===a.group&&e.checked&&(n.find(`.w2ui-menu-item[index="${(s?s+"-":"")+t}"] .w2ui-icon`).removeClass("w2ui-icon-check").addClass("w2ui-icon-empty"),i[t].checked=!1),Array.isArray(e.items))&&l(e.items,t)})};"check"!==e.type&&"radio"!==e.type||!1===a.group||query(t.target).hasClass("remove")||query(t.target).closest(".w2ui-menu-item").hasClass("has-sub-menu")||(a.checked="radio"==e.type||!a.checked,a.checked?("radio"===e.type&&query(t.target).closest(".w2ui-menu").find(".w2ui-icon").removeClass("w2ui-icon-check").addClass("w2ui-icon-empty"),"check"===e.type&&null!=a.group&&l(e.items),r.removeClass("w2ui-icon-empty").addClass("w2ui-icon-check")):"check"===e.type&&r.removeClass("w2ui-icon-check").addClass("w2ui-icon-empty")),query(t.target).hasClass("remove")||(n.find(".w2ui-menu-item").removeClass("w2ui-selected"),query(t.delegate).addClass("w2ui-selected"))}}menuClick(t,i,s,l){var r=t.options;let n=r.items;var a=query(i.delegate).closest(".w2ui-menu-item");let o=!r.hideOn.includes("select");(i.shiftKey||i.metaKey||i.ctrlKey)&&(o=!0),"string"==typeof l&&""!==l?l.split("-").forEach(e=>{n=n[e].items}):l=null;var h=(n="function"==typeof n?n({overlay:t,index:s,parentIndex:l,event:i}):n)[s];if(!h.disabled||query(i.target).hasClass("remove")){let e;if(query(i.target).hasClass("remove")){if(!0===(e=this.trigger("remove",{originalEvent:i,target:t.name,overlay:t,item:h,index:s,parentIndex:l,el:a[0]})).isCancelled)return;o=!r.hideOn.includes("item-remove"),a.remove()}else if(a.hasClass("has-sub-menu")){if(!0===(e=this.trigger("subMenu",{originalEvent:i,target:t.name,overlay:t,item:h,index:s,parentIndex:l,el:a[0]})).isCancelled)return;o=!0,a.hasClass("expanded")?(h.expanded=!1,a.removeClass("expanded").addClass("collapsed"),query(a.get(0).nextElementSibling).hide()):(h.expanded=!0,a.addClass("expanded").removeClass("collapsed"),query(a.get(0).nextElementSibling).show()),t.selected=parseInt(a.attr("index"))}else{r=this.findChecked(r.items);if(t.selected=parseInt(a.attr("index")),!0===(e=this.trigger("select",{originalEvent:i,target:t.name,overlay:t,item:h,index:s,parentIndex:l,selected:r,keepOpen:o,el:a[0]})).isCancelled)return;null!=h.keepOpen&&(o=h.keepOpen),["INPUT","TEXTAREA"].includes(t.anchor.tagName)&&(t.anchor.dataset.selected=h.id,t.anchor.dataset.selectedIndex=t.selected)}o||this.hide(t.name),e.finish()}}findChecked(e){let t=[];return e.forEach(e=>{e.checked&&t.push(e),Array.isArray(e.items)&&(t=t.concat(this.findChecked(e.items)))}),t}keyUp(s,l){var r=s.options,e=l.target.value;let n=!0,a=!1;switch(l.keyCode){case 46:case 8:""!==e||s.displayed||(n=!1);break;case 13:if(!s.displayed||!s.selected)return;var{index:t,parents:i}=this.getCurrent(s.name);l.delegate=query(s.box).find(".w2ui-selected").get(0),this.menuClick(s,l,parseInt(t),i),n=!1;break;case 27:n=!1,s.displayed?this.hide(s.name):(t=s.anchor,["INPUT","TEXTAREA"].includes(t.tagName)&&(t.value="",delete t.dataset.selected,delete t.dataset.selectedIndex));break;case 37:{if(!s.displayed)return;let{item:e,index:t,parents:i}=this.getCurrent(s.name);i&&(e=r.items[i],t=parseInt(i),i="",a=!0),Array.isArray(e?.items)&&0<e.items.length&&e.expanded&&(l.delegate=query(s.box).find(`.w2ui-menu-item[index="${t}"]`).get(0),s.selected=t,this.menuClick(s,l,parseInt(t),i)),n=!1;break}case 39:if(!s.displayed)return;var{item:i,index:t,parents:o}=this.getCurrent(s.name);Array.isArray(i?.items)&&0<i.items.length&&!i.expanded&&(l.delegate=query(s.box).find(".w2ui-selected").get(0),this.menuClick(s,l,parseInt(t),o)),n=!1;break;case 38:s.displayed&&(i=this.getActiveChain(s.name),null==s.selected||0==s.selected?.length?s.selected=i[i.length-1]:(-1==(t=i.indexOf(s.selected))&&(s.selected=i[i.length-1]),0<t&&(s.selected=i[t-1])),n=!1,a=!0,l.preventDefault());break;case 40:s.displayed&&(o=this.getActiveChain(s.name),null==s.selected||0==s.selected?.length?s.selected=o[0]:(-1==(i=o.indexOf(s.selected))&&(s.selected=o[0]),i<o.length-1&&(s.selected=o[i+1])),n=!1,a=!0,l.preventDefault())}n&&s.displayed&&(r.filter&&"filter"==l._searchType||r.search&&"search"==l._searchType)&&this.applyFilter(s.name,null,e,!0).then(e=>{s.tmp.searchCount=e.count,s.tmp.search=e.search,0!==e.count&&this.getActiveChain(s.name).includes(s.selected)||(s.selected=null),this.refreshSearch(s.name)}),a&&this.refreshIndex(s.name)}}class DateTooltip extends Tooltip{constructor(){super();var e=new Date;this.daysCount=[31,28,31,30,31,30,31,31,30,31,30,31],this.today=e.getFullYear()+"/"+(Number(e.getMonth())+1)+"/"+e.getDate(),this.defaults=w2utils.extend({},this.defaults,{position:"top|bottom",class:"w2ui-calendar",type:"date",format:"",value:"",start:null,end:null,blockDates:[],blockWeekdays:[],colored:{},arrowSize:12,autoResize:!1,anchorClass:"w2ui-focus",autoShowOn:"focus",hideOn:["doc-click","focus-change"],onSelect:null})}attach(e,t){let i;1==arguments.length&&e.anchor?e=(i=e).anchor:2===arguments.length&&null!=t&&"object"==typeof t&&((i=t).anchor=e);var t=i.hideOn,e=(i=w2utils.extend({},this.defaults,i||{}),t&&(i.hideOn=t),i.format||(e=w2utils.settings.dateFormat,t=w2utils.settings.timeFormat,"date"==i.type?i.format=e:"time"==i.type?i.format=t:i.format=e+"|"+t),"time"==i.type?this.getHourHTML(i):this.getMonthHTML(i));i.style+="; padding: 0;",i.html=e.html;let s=super.attach(i),l=s.overlay;return Object.assign(l.tmp,e),l.on("show.attach",e=>{var e=e.detail.overlay,t=e.anchor,i=e.options;["INPUT","TEXTAREA"].includes(t.tagName)&&!i.value&&t.value&&(e.tmp.initValue=t.value),delete e.newValue,delete e.newDate}),l.on("show:after.attach",e=>{s.overlay?.box&&this.initControls(s.overlay)}),l.on("update:after.attach",e=>{s.overlay?.box&&this.initControls(s.overlay)}),l.on("hide.attach",e=>{var e=e.detail.overlay,t=e.anchor;null!=e.newValue&&(e.newDate&&(e.newValue=e.newDate+" "+e.newValue),["INPUT","TEXTAREA"].includes(t.tagName)&&t.value!=e.newValue&&(t.value=e.newValue),!0!==(t=this.trigger("select",{date:e.newValue,target:e.name,overlay:e})).isCancelled)&&t.finish()}),s.select=t=>(l.on("select.attach",e=>{t(e)}),s),s}initControls(l){let r=l.options,t=e=>{let{month:t,year:i}=l.tmp;12<(t+=e)&&(t=1,i++),t<1&&(t=12,i--);e=this.getMonthHTML(r,t,i);Object.assign(l.tmp,e),query(l.box).find(".w2ui-overlay-body").html(e.html),this.initControls(l)},i=(e,t)=>{query(e.target).parent().find(".w2ui-jump-month, .w2ui-jump-year").removeClass("w2ui-selected"),query(e.target).addClass("w2ui-selected");e=new Date;let{jumpMonth:i,jumpYear:s}=l.tmp;(i=t&&(null==s&&(s=e.getFullYear()),null==i)?e.getMonth()+1:i)&&s&&(t=this.getMonthHTML(r,i,s),Object.assign(l.tmp,t),query(l.box).find(".w2ui-overlay-body").html(t.html),l.tmp.jump=!1,this.initControls(l))};query(l.box).find(".w2ui-cal-title").off(".calendar").on("click.calendar",e=>{var t,i;Object.assign(l.tmp,{jumpYear:null,jumpMonth:null}),l.tmp.jump?({month:t,year:i}=l.tmp,t=this.getMonthHTML(r,t,i),query(l.box).find(".w2ui-overlay-body").html(t.html),l.tmp.jump=!1):(query(l.box).find(".w2ui-overlay-body .w2ui-cal-days").replace(this.getYearHTML()),(i=query(l.box).find(`[name="${l.tmp.year}"]`).get(0))&&i.scrollIntoView(!0),l.tmp.jump=!0),this.initControls(l),e.stopPropagation()}).find(".w2ui-cal-previous").off(".calendar").on("click.calendar",e=>{t(-1),e.stopPropagation()}).parent().find(".w2ui-cal-next").off(".calendar").on("click.calendar",e=>{t(1),e.stopPropagation()}),query(l.box).find(".w2ui-cal-now").off(".calendar").on("click.calendar",e=>{"datetime"==r.type?l.newDate?l.newValue=w2utils.formatTime(new Date,r.format.split("|")[1]):l.newValue=w2utils.formatDateTime(new Date,r.format):"date"==r.type?l.newValue=w2utils.formatDate(new Date,r.format):"time"==r.type&&(l.newValue=w2utils.formatTime(new Date,r.format)),this.hide(l.name)}),query(l.box).off(".calendar").on("click.calendar",{delegate:".w2ui-day.w2ui-date"},e=>{"datetime"==r.type?(l.newDate=query(e.target).attr("date"),query(l.box).find(".w2ui-overlay-body").html(this.getHourHTML(l.options).html),this.initControls(l)):(l.newValue=query(e.target).attr("date"),this.hide(l.name))}).on("click.calendar",{delegate:".w2ui-jump-month"},e=>{l.tmp.jumpMonth=parseInt(query(e.target).attr("name")),i(e)}).on("dblclick.calendar",{delegate:".w2ui-jump-month"},e=>{l.tmp.jumpMonth=parseInt(query(e.target).attr("name")),i(e,!0)}).on("click.calendar",{delegate:".w2ui-jump-year"},e=>{l.tmp.jumpYear=parseInt(query(e.target).attr("name")),i(e)}).on("dblclick.calendar",{delegate:".w2ui-jump-year"},e=>{l.tmp.jumpYear=parseInt(query(e.target).attr("name")),i(e,!0)}).on("click.calendar",{delegate:".w2ui-time.hour"},e=>{var e=query(e.target).attr("hour");let t=this.str2min(r.value)%60;l.tmp.initValue&&!r.value&&(t=this.str2min(l.tmp.initValue)%60),r.noMinutes?(l.newValue=this.min2str(60*e,r.format),this.hide(l.name)):(l.newValue=e+":"+t,e=this.getMinHTML(e,r).html,query(l.box).find(".w2ui-overlay-body").html(e),this.initControls(l))}).on("click.calendar",{delegate:".w2ui-time.min"},e=>{e=60*Math.floor(this.str2min(l.newValue)/60)+parseInt(query(e.target).attr("min"));l.newValue=this.min2str(e,r.format),this.hide(l.name)})}getMonthHTML(l,r,e){var t=w2utils.settings.fulldays.slice(),i=w2utils.settings.shortdays.slice();"M"!==w2utils.settings.weekStarts&&(t.unshift(t.pop()),i.unshift(i.pop()));let s=new Date;var t="datetime"===l.type?w2utils.isDateTime(l.value,l.format,!0):w2utils.isDate(l.value,l.format,!0),n=w2utils.formatDate(t);null!=r&&null!=e||(e=(t||s).getFullYear(),r=t?t.getMonth()+1:s.getMonth()+1),12<r&&(r-=12,e++),(r<1||0===r)&&(r+=12,e--),e/4==Math.floor(e/4)?this.daysCount[1]=29:this.daysCount[1]=28,l.current=r+"/"+e;let a=(s=new Date(e,r-1,1)).getDay(),o="";var h=w2utils.settings.weekStarts;for(let e=0;e<i.length;e++){var d="M"==h&&5==e||"M"!=h&&6==e,u="M"==h&&6==e||"M"!=h&&0==e;o+=`<div class="w2ui-day w2ui-weekday ${d?"w2ui-sunday":""} ${u?"w2ui-saturday":""}">${i[e]}</div>`}let c=`
<div class="w2ui-cal-title">
<div class="w2ui-cal-previous">
<div></div>
</div>
<div class="w2ui-cal-next">
<div></div>
</div>
${w2utils.settings.fullmonths[r-1]}, ${e}
<span class="arrow-down"></span>
</div>
<div class="w2ui-cal-days">
${o}
`,p=new Date(e+`/${r}/1`);t=(p=new Date(p.getTime()+432e5)).getDay();"M"==w2utils.settings.weekStarts&&a--,0<t&&(p=new Date(p.getTime()-864e5*a));for(let e=0;e<42;e++){var f=[],m=`${p.getFullYear()}/${p.getMonth()+1}/`+p.getDate(),g=(6===p.getDay()&&f.push("w2ui-saturday"),0===p.getDay()&&f.push("w2ui-sunday"),p.getMonth()+1!==r&&f.push("outside"),m==this.today&&f.push("w2ui-today"),p.getDate());let e="",t="",i,s;s="datetime"===l.type?(i=w2utils.formatDateTime(m,l.format),w2utils.formatDate(m,w2utils.settings.dateFormat)):i=w2utils.formatDate(m,l.format),l.colored&&void 0!==l.colored[s]&&(m=l.colored[s].split("|"),t="background-color: "+m[0]+";",e="color: "+m[1]+";"),c+=`<div class="w2ui-day ${this.inRange(i,l,!0)?"w2ui-date "+(s==n?"w2ui-selected":""):"w2ui-blocked"} ${f.join(" ")}"
style="${e+t}" date="${s}" data-date="${p.getTime()}">
${g}
</div>`,p=new Date(p.getTime()+864e5)}return c+="</div>",l.btnNow&&(t=w2utils.lang("Today"+("datetime"==l.type?" & Now":"")),c+=`<div class="w2ui-cal-now">${t}</div>`),{html:c,month:r,year:e}}getYearHTML(){let t="",i="";for(let e=0;e<w2utils.settings.fullmonths.length;e++)t+=`<div class="w2ui-jump-month" name="${e+1}">${w2utils.settings.shortmonths[e]}</div>`;for(let e=w2utils.settings.dateStartYear;e<=w2utils.settings.dateEndYear;e++)i+=`<div class="w2ui-jump-year" name="${e}">${e}</div>`;return`<div class="w2ui-cal-jump">
<div id="w2ui-jump-month">${t}</div>
<div id="w2ui-jump-year">${i}</div>
</div>`}getHourHTML(l){(l=l??{}).format||(l.format=w2utils.settings.timeFormat);var r=-1<l.format.indexOf("h24"),n=l.value||(l.anchor?l.anchor.value:""),a=[];for(let s=0;s<24;s++){let e=(12<=s&&!r?s-12:s)+":00"+(r?"":s<12?" am":" pm"),t=(12!=s||r||(e="12:00 pm"),a[Math.floor(s/8)]||(a[Math.floor(s/8)]=""),this.min2str(this.str2min(e))),i=this.min2str(this.str2min(e)+59);"datetime"===l.type&&(h=w2utils.isDateTime(n,l.format,!0),o=l.format.split("|")[0].trim(),t=w2utils.formatDate(h,o)+" "+t,i=w2utils.formatDate(h,o)+" "+i);var o,h=this.inRange(t,l)||this.inRange(i,l);a[Math.floor(s/8)]+=`<span hour="${s}"
class="hour ${h?"w2ui-time ":"w2ui-blocked"}">${e}</span>`}return{html:`<div class="w2ui-calendar">
<div class="w2ui-time-title">${w2utils.lang("Select Hour")}</div>
<div class="w2ui-cal-time">
<div class="w2ui-cal-column">${a[0]}</div>
<div class="w2ui-cal-column">${a[1]}</div>
<div class="w2ui-cal-column">${a[2]}</div>
</div>
${l.btnNow?`<div class="w2ui-cal-now">${w2utils.lang("Now")}</div>`:""}
</div>`}}getMinHTML(i,s){null==i&&(i=0),(s=s??{}).format||(s.format=w2utils.settings.timeFormat);var l=-1<s.format.indexOf("h24"),r=s.value||(s.anchor?s.anchor.value:""),n=[];for(let t=0;t<60;t+=5){var a=(12<i&&!l?i-12:i)+":"+(t<10?0:"")+t+" "+(l?"":i<12?"am":"pm");let e=a;var o,h,d=t<20?0:t<40?1:2;n[d]||(n[d]=""),"datetime"===s.type&&(o=w2utils.isDateTime(r,s.format,!0),h=s.format.split("|")[0].trim(),e=w2utils.formatDate(o,h)+" "+e),n[d]+=`<span min="${t}" class="min ${this.inRange(e,s)?"w2ui-time ":"w2ui-blocked"}">${a}</span>`}return{html:`<div class="w2ui-calendar">
<div class="w2ui-time-title">${w2utils.lang("Select Minute")}</div>
<div class="w2ui-cal-time">
<div class="w2ui-cal-column">${n[0]}</div>
<div class="w2ui-cal-column">${n[1]}</div>
<div class="w2ui-cal-column">${n[2]}</div>
</div>
${s.btnNow?`<div class="w2ui-cal-now">${w2utils.lang("Now")}</div>`:""}
</div>`}}inRange(i,s,e){let l=!1;if("date"===s.type){var r=w2utils.isDate(i,s.format,!0);if(r){if(s.start||s.end){var n="string"==typeof s.start?s.start:query(s.start).val(),a="string"==typeof s.end?s.end:query(s.end).val();let e=w2utils.isDate(n,s.format,!0),t=w2utils.isDate(a,s.format,!0);n=new Date(r);e=e||n,t=t||n,n>=e&&n<=t&&(l=!0)}else l=!0;Array.isArray(s.blockDates)&&s.blockDates.includes(i)&&(l=!1),Array.isArray(s.blockWeekdays)&&s.blockWeekdays.includes(r.getDay())&&(l=!1)}}else if("time"===s.type)if(s.start||s.end){a=this.str2min(i);let e=this.str2min(s.start),t=this.str2min(s.end);e=e||a,t=t||a,a>=e&&a<=t&&(l=!0)}else l=!0;else"datetime"===s.type&&(n=w2utils.isDateTime(i,s.format,!0))&&(r=s.format.split("|").map(e=>e.trim()),e?(a=w2utils.formatDate(n,r[0]),i=w2utils.extend({},s,{type:"date",format:r[0]}),this.inRange(a,i)&&(l=!0)):(e=w2utils.formatTime(n,r[1]),a={type:"time",format:r[1],start:s.startTime,end:s.endTime},this.inRange(e,a)&&(l=!0)));return l}str2min(e){var t;return"string"!=typeof e||2!==(t=e.split(":")).length?null:(t[0]=parseInt(t[0]),t[1]=parseInt(t[1]),-1!==e.indexOf("pm")&&12!==t[0]&&(t[0]+=12),e.includes("am")&&12==t[0]&&(t[0]=0),60*t[0]+t[1])}min2str(e,t){let i="";1440<=e&&(e%=1440),e<0&&(e=1440+e);var s=Math.floor(e/60),e=(e%60<10?"0":"")+e%60;return t=t||w2utils.settings.timeFormat,i=-1!==t.indexOf("h24")?s+":"+e:(s<=12?s:s-12)+":"+e+" "+(12<=s?"pm":"am")}}let w2tooltip=new Tooltip,w2menu=new MenuTooltip,w2color=new ColorTooltip,w2date=new DateTooltip;class w2toolbar extends w2base{constructor(e){super(e.name),this.box=null,this.name=null,this.routeData={},this.items=[],this.right="",this.tooltip="top|left",this.onClick=null,this.onMouseDown=null,this.onMouseUp=null,this.onMouseEnter=null,this.onMouseLeave=null,this.onRender=null,this.onRefresh=null,this.onResize=null,this.onDestroy=null,this.item_template={id:null,type:"button",text:null,html:"",tooltip:null,count:null,hidden:!1,disabled:!1,checked:!1,icon:null,route:null,arrow:null,style:null,group:null,items:null,selected:null,color:null,overlay:{anchorClass:""},onClick:null,onRefresh:null},this.last={badge:{}};var t=e.items;delete e.items,Object.assign(this,e),Array.isArray(t)&&this.add(t,!0),e.items=t,"string"==typeof this.box&&(this.box=query(this.box).get(0)),this.box&&this.render(this.box)}add(e,t){this.insert(null,e,t)}insert(r,e,n){(e=Array.isArray(e)?e:[e]).forEach((e,t,i)=>{"string"==typeof e&&(e=i[t]={id:e,text:e});var l,s=["button","check","radio","drop","menu","menu-radio","menu-check","color","text-color","html","break","spacer","new-line"];if(s.includes(String(e.type)))if(null!=e.id||["break","spacer","new-line"].includes(e.type)){if(null==e.type)console.log('ERROR: The parameter "type" is required but not supplied.',e);else if(w2utils.checkUniqueId(e.id,this.items,"toolbar",this.name)){let s=w2utils.extend({},this.item_template,e);"menu-check"==s.type?(Array.isArray(s.selected)||(s.selected=[]),Array.isArray(s.items)&&s.items.forEach(e=>{(e="string"==typeof e?i[t]={id:e,text:e}:e).checked&&!s.selected.includes(e.id)&&s.selected.push(e.id),!e.checked&&s.selected.includes(e.id)&&(e.checked=!0),null==e.checked&&(e.checked=!1)})):"menu-radio"==s.type&&Array.isArray(s.items)&&s.items.forEach((e,t,i)=>{(e="string"==typeof e?i[t]={id:e,text:e}:e).checked&&null==s.selected?s.selected=e.id:e.checked=!1,e.checked||s.selected!=e.id||(e.checked=!0),null==e.checked&&(e.checked=!1)}),null==r?this.items.push(s):(l=this.get(r,!0),this.items=this.items.slice(0,l).concat([s],this.items.slice(l))),s.line=s.line??1,!0!==n&&this.refresh(s.id)}}else console.log('ERROR: The parameter "id" is required but not supplied.',e);else console.log('ERROR: The parameter "type" should be one of the following:',s,`, but ${e.type} is supplied.`,e)}),!0!==n&&this.resize()}remove(){let i=0;return Array.from(arguments).forEach(e=>{var t=this.get(e);t&&-1==String(e).indexOf(":")&&(i++,query(this.box).find("#tb_"+this.name+"_item_"+w2utils.escapeId(t.id)).remove(),null!=(e=this.get(t.id,!0)))&&this.items.splice(e,1)}),this.resize(),i}set(e,t){var i=this.get(e);return null!=i&&(Object.assign(i,t),this.refresh(String(e).split(":")[0]),!0)}get(e,i){if(0===arguments.length){var t=[];for(let e=0;e<this.items.length;e++)null!=this.items[e].id&&t.push(this.items[e].id);return t}var s=String(e).split(":");for(let e=0;e<this.items.length;e++){var l=this.items[e];if(["menu","menu-radio","menu-check"].includes(l.type)&&2==s.length&&l.id==s[0]){let e=l.items;"function"==typeof e&&(e=e(this));for(let t=0;t<e.length;t++){var r=e[t];if(r.id==s[1]||null==r.id&&r.text==s[1])return 1==i?t:r;if(Array.isArray(r.items))for(let e=0;e<r.items.length;e++)if(r.items[e].id==s[1]||null==r.items[e].id&&r.items[e].text==s[1])return 1==i?t:r.items[e]}}else if(l.id==s[0])return 1==i?e:l}return null}setCount(e,t,i,s){var l=query(this.box).find(`#tb_${this.name}_item_${w2utils.escapeId(e)} .w2ui-tb-count > span`);0<l.length?(l.removeClass().addClass(i??"").text(t).get(0).style.cssText=s??"",this.last.badge[e]={className:i??"",style:s??""},this.get(e).count=t):(this.set(e,{count:t}),this.setCount(...arguments))}show(){let i=[];return Array.from(arguments).forEach(e=>{var t=this.get(e);t&&(t.hidden=!1,i.push(String(e).split(":")[0]))}),setTimeout(()=>{i.forEach(e=>{this.refresh(e),this.resize()})},15),i}hide(){let i=[];return Array.from(arguments).forEach(e=>{var t=this.get(e);t&&(t.hidden=!0,i.push(String(e).split(":")[0]))}),setTimeout(()=>{i.forEach(e=>{this.refresh(e),this.tooltipHide(e),this.resize()})},15),i}enable(){let i=[];return Array.from(arguments).forEach(e=>{var t=this.get(e);t&&(t.disabled=!1,i.push(String(e).split(":")[0]))}),setTimeout(()=>{i.forEach(e=>{this.refresh(e)})},15),i}disable(){let i=[];return Array.from(arguments).forEach(e=>{var t=this.get(e);t&&(t.disabled=!0,i.push(String(e).split(":")[0]))}),setTimeout(()=>{i.forEach(e=>{this.refresh(e),this.tooltipHide(e)})},15),i}check(){let i=[];return Array.from(arguments).forEach(e=>{var t=this.get(e);t&&-1==String(e).indexOf(":")&&(t.checked=!0,i.push(String(e).split(":")[0]))}),setTimeout(()=>{i.forEach(e=>{this.refresh(e)})},15),i}uncheck(){let i=[];return Array.from(arguments).forEach(e=>{var t=this.get(e);t&&-1==String(e).indexOf(":")&&(["menu","menu-radio","menu-check","drop","color","text-color"].includes(t.type)&&t.checked&&w2tooltip.hide(this.name+"-drop"),t.checked=!1,i.push(String(e).split(":")[0]))}),setTimeout(()=>{i.forEach(e=>{this.refresh(e)})},15),i}click(e,t){var i=String(e).split(":");let l=this.get(i[0]),r=l&&l.items?w2utils.normMenu.call(this,l.items,l):[];if(1<i.length)(i=this.get(e))&&!i.disabled&&this.menuClick({name:this.name,item:l,subItem:i,originalEvent:t});else if(l&&!l.disabled){i=this.trigger("click",{target:null!=e?e:this.name,item:l,object:l,originalEvent:t});if(!0!==i.isCancelled){r=l&&l.items?w2utils.normMenu.call(this,l.items,l):[];let s="#tb_"+this.name+"_item_"+w2utils.escapeId(l.id);if(query(this.box).find(s).removeClass("down"),"radio"==l.type){for(let e=0;e<this.items.length;e++){var n=this.items[e];null!=n&&n.id!=l.id&&"radio"===n.type&&n.group==l.group&&n.checked&&(n.checked=!1,this.refresh(n.id))}l.checked=!0,query(this.box).find(s).addClass("checked")}if(["menu","menu-radio","menu-check","drop","color","text-color"].includes(l.type)){if(this.tooltipHide(e),l.checked)return void w2tooltip.hide(this.name+"-drop");setTimeout(()=>{var t=(e,t)=>{let i=this;return function(){i.set(e,{checked:!1})}},i=query(this.box).find("#tb_"+this.name+"_item_"+w2utils.escapeId(l.id));if(w2utils.isPlainObject(l.overlay)||(l.overlay={}),"drop"==l.type&&w2tooltip.show(w2utils.extend({html:l.html,class:"w2ui-white",hideOn:["doc-click"]},l.overlay,{anchor:i[0],name:this.name+"-drop",data:{item:l,btn:s}})).hide(t(l.id,s)),["menu","menu-radio","menu-check"].includes(l.type)){let e="normal";"menu-radio"==l.type&&(e="radio",r.forEach(e=>{l.selected==e.id?e.checked=!0:e.checked=!1})),"menu-check"==l.type&&(e="check",r.forEach(e=>{Array.isArray(l.selected)&&l.selected.includes(e.id)?e.checked=!0:e.checked=!1})),w2menu.show(w2utils.extend({items:r},l.overlay,{type:e,name:this.name+"-drop",anchor:i[0],data:{item:l,btn:s}})).hide(t(l.id,s)).remove(e=>{this.menuClick({name:this.name,remove:!0,item:l,subItem:e.detail.item,originalEvent:e})}).select(e=>{this.menuClick({name:this.name,item:l,subItem:e.detail.item,originalEvent:e})})}["color","text-color"].includes(l.type)&&w2color.show(w2utils.extend({color:l.color},l.overlay,{anchor:i[0],name:this.name+"-drop",data:{item:l,btn:s}})).hide(t(l.id,s)).select(e=>{null!=e.detail.color&&this.colorClick({name:this.name,item:l,color:e.detail.color})})},0)}if(["check","menu","menu-radio","menu-check","drop","color","text-color"].includes(l.type)&&(l.checked=!l.checked,l.checked?query(this.box).find(s).addClass("checked"):query(this.box).find(s).removeClass("checked")),l.route){let t=String("/"+l.route).replace(/\/{2,}/g,"/");var a=w2utils.parseRoute(t);if(0<a.keys.length)for(let e=0;e<a.keys.length;e++)t=t.replace(new RegExp(":"+a.keys[e].name,"g"),this.routeData[a.keys[e].name]);setTimeout(()=>{window.location.hash=t},1)}this.tooltipShow(e),i.finish()}}}scroll(a,o,h){return new Promise((e,t)=>{var i=query(this.box).find(`.w2ui-tb-line:nth-child(${o}) .w2ui-scroll-wrapper`),s=i.get(0).scrollLeft,l=i.find(".w2ui-tb-right").get(0),r=i.parent().get(0).getBoundingClientRect().width,n=s+parseInt(l.offsetLeft)+parseInt(l.clientWidth);switch(a){case"left":(scroll=s-r+50)<=0&&(scroll=0),i.get(0).scrollTo({top:0,left:scroll,behavior:h?"atuo":"smooth"});break;case"right":(scroll=s+r-50)>=n-r&&(scroll=n-r),i.get(0).scrollTo({top:0,left:scroll,behavior:h?"atuo":"smooth"})}setTimeout(()=>{this.resize(),e()},h?0:500)})}render(e){var s=Date.now(),l=("string"==typeof e&&(e=query(e).get(0)),this.trigger("render",{target:this.name,box:e??this.box}));if(!0!==l.isCancelled&&(null!=e&&(0<query(this.box).find(".w2ui-scroll-wrapper .w2ui-tb-right").length&&query(this.box).removeAttr("name").removeClass("w2ui-reset w2ui-toolbar").html(""),this.box=e),this.box)){Array.isArray(this.right)||(this.right=[this.right]);let t="",i=0;for(let e=0;e<this.items.length;e++){var r=this.items[e];null!=r&&(null==r.id&&(r.id="item_"+e),null!=r.caption&&console.log("NOTICE: toolbar item.caption property is deprecated, please use item.text. Item -> ",r),null!=r.hint&&console.log("NOTICE: toolbar item.hint property is deprecated, please use item.tooltip. Item -> ",r),0!==e&&"new-line"!=r.type||(i++,t+=`
<div class="w2ui-tb-line">
<div class="w2ui-scroll-wrapper w2ui-eaction" data-mousedown="resize">
<div class="w2ui-tb-right">${this.right[i-1]??""}</div>
</div>
<div class="w2ui-scroll-left w2ui-eaction" data-click='["scroll", "left", "${i}"]'></div>
<div class="w2ui-scroll-right w2ui-eaction" data-click='["scroll", "right", "${i}"]'></div>
</div>
`),r.line=i)}return query(this.box).attr("name",this.name).addClass("w2ui-reset w2ui-toolbar").html(t),0<query(this.box).length&&(query(this.box)[0].style.cssText+=this.style),w2utils.bindEvents(query(this.box).find(".w2ui-tb-line .w2ui-eaction"),this),this.last.observeResize=new ResizeObserver(()=>{this.resize()}),this.last.observeResize.observe(this.box),this.refresh(),this.resize(),l.finish(),Date.now()-s}}refresh(t){var i=Date.now(),l=this.trigger("refresh",{target:null!=t?t:this.name,item:this.get(t)});if(!0!==l.isCancelled){let e;if(null==t)for(let e=0;e<this.items.length;e++){var s=this.items[e];null==s.id&&(s.id="item_"+e),this.refresh(s.id)}else{var r=this.get(t);if(null==r)return!1;if("function"!=typeof r.onRefresh||!0!==(e=this.trigger("refresh",{target:t,item:r,object:r})).isCancelled){var n=`#tb_${this.name}_item_`+w2utils.escapeId(r.id);let s=query(this.box).find(n);var a=this.getItemHTML(r);if(this.tooltipHide(t),"spacer"==r.type&&query(this.box).find(".w2ui-tb-line:nth-child("+r.line).find(".w2ui-tb-right").css("width","auto"),0===s.length){t=parseInt(this.get(t,!0))+1;let e=query(this.box).find(`#tb_${this.name}_item_`+w2utils.escapeId(this.items[t]?this.items[t].id:""));0==e.length?e=query(this.box).find(".w2ui-tb-line:nth-child("+r.line).find(".w2ui-tb-right").before(a):e.after(a),w2utils.bindEvents(query(this.box).find(n),this)}else{query(this.box).find(n).replace(query.html(a));let t=query(this.box).find(n).get(0),i=(w2utils.bindEvents(t,this),w2tooltip.get(!0));Object.keys(i).forEach(e=>{i[e].anchor==s.get(0)&&(i[e].anchor=t)})}if(["menu","menu-radio","menu-check"].includes(r.type)&&r.checked){let t=Array.isArray(r.selected)?r.selected:[r.selected];r.items.forEach(e=>{t.includes(e.id)?e.checked=!0:e.checked=!1}),w2menu.update(this.name+"-drop",r.items)}return"function"==typeof r.onRefresh&&e.finish(),l.finish(),Date.now()-i}}}}resize(){var e=Date.now(),t=this.trigger("resize",{target:this.name});if(!0!==t.isCancelled)return query(this.box).find(".w2ui-tb-line").each(e=>{var e=query(e),t=(e.find(".w2ui-scroll-left, .w2ui-scroll-right").hide(),e.find(".w2ui-scroll-wrapper").get(0)),i=e.find(".w2ui-tb-right"),s=e.get(0).getBoundingClientRect().width,i=0<i.length?i[0].offsetLeft+i[0].clientWidth:0;s<i&&(0<t.scrollLeft&&e.find(".w2ui-scroll-left").show(),s<i-t.scrollLeft)&&e.find(".w2ui-scroll-right").show()}),t.finish(),Date.now()-e}destroy(){var e=this.trigger("destroy",{target:this.name});!0!==e.isCancelled&&(0<query(this.box).find(".w2ui-scroll-wrapper .w2ui-tb-right").length&&query(this.box).removeAttr("name").removeClass("w2ui-reset w2ui-toolbar").html(""),query(this.box).html(""),this.last.observeResize?.disconnect(),delete w2ui[this.name],e.finish())}getItemHTML(i){let e="",t=(null!=i.caption&&null==i.text&&(i.text=i.caption),null==i.text&&(i.text=""),null==i.tooltip&&null!=i.hint&&(i.tooltip=i.hint),null==i.tooltip&&(i.tooltip=""),"function"==typeof i.get||!Array.isArray(i.items)&&"function"!=typeof i.items||(i.get=function(t){let e=i.items;return(e="function"==typeof e?i.items(i):e).find(e=>e.id==t)}),""),s="function"==typeof i.text?i.text.call(this,i):i.text;i.icon&&(t=i.icon,"function"==typeof i.icon&&(t=i.icon.call(this,i)),t=`<div class="w2ui-tb-icon">${t="<"!==String(t).slice(0,1)?`<span class="${t}"></span>`:t}</div>`);var l=["w2ui-tb-button"];switch(i.checked&&l.push("checked"),i.disabled&&l.push("disabled"),i.hidden&&l.push("hidden"),t||l.push("no-icon"),i.type){case"color":case"text-color":"string"==typeof i.color&&("#"==i.color.slice(0,1)&&(i.color=i.color.slice(1)),[3,6,8].includes(i.color.length))&&(i.color="#"+i.color),"color"==i.type&&(s=`<span class="w2ui-tb-color-box" style="background-color: ${null!=i.color?i.color:"#fff"}"></span>
`+(i.text?`<div style="margin-left: 17px;">${w2utils.lang(i.text)}</div>`:"")),"text-color"==i.type&&(s='<span style="color: '+(null!=i.color?i.color:"#444")+';">'+(i.text?w2utils.lang(i.text):"<b>Aa</b>")+"</span>");case"menu":case"menu-check":case"menu-radio":case"button":case"check":case"radio":case"drop":var r=!0===i.arrow||!1!==i.arrow&&["menu","menu-radio","menu-check","drop","color","text-color"].includes(i.type);e=`
<div id="tb_${this.name}_item_${i.id}" style="${i.hidden?"display: none":""}"
class="${l.join(" ")} ${i.class||""}"
${i.disabled?"":`data-click='["click","${i.id}"]'
data-mouseenter='["mouseAction", "event", "this", "Enter", "${i.id}"]'
data-mouseleave='["mouseAction", "event", "this", "Leave", "${i.id}"]'
data-mousedown='["mouseAction", "event", "this", "Down", "${i.id}"]'
data-mouseup='["mouseAction", "event", "this", "Up", "${i.id}"]'`}
>
${t}
${""!=s?`<div class="w2ui-tb-text" style="${i.style||""}">
${w2utils.lang(s)}
${null!=i.count?w2utils.stripSpaces(`<span class="w2ui-tb-count">
<span class="${this.last.badge[i.id]?this.last.badge[i.id].className??"":""}"
style="${this.last.badge[i.id]?this.last.badge[i.id].style??"":""}"
>${i.count}</span>
</span>`):""}
${r?'<span class="w2ui-tb-down"><span></span></span>':""}
</div>`:""}
</div>
`;break;case"break":e=`<div id="tb_${this.name}_item_${i.id}" class="w2ui-tb-break"
style="${i.hidden?"display: none":""}; ${i.style||""}">
 
</div>`;break;case"spacer":e=`<div id="tb_${this.name}_item_${i.id}" class="w2ui-tb-spacer"
style="${i.hidden?"display: none":""}; ${i.style||""}">
</div>`;break;case"html":e=`<div id="tb_${this.name}_item_${i.id}" class="w2ui-tb-html ${l.join(" ")}"
style="${i.hidden?"display: none":""}; ${i.style||""}">
${"function"==typeof i.html?i.html.call(this,i):i.html}
</div>`}return e}tooltipShow(t){if(null!=this.tooltip){var i=query(this.box).find("#tb_"+this.name+"_item_"+w2utils.escapeId(t)).get(0),t=this.get(t),s=this.tooltip;let e=t.tooltip;"function"==typeof e&&(e=e.call(this,t)),["menu","menu-radio","menu-check","drop","color","text-color"].includes(t.type)&&1==t.checked||w2tooltip.show({anchor:i,name:this.name+"-tooltip",html:e,position:s})}}tooltipHide(e){null!=this.tooltip&&w2tooltip.hide(this.name+"-tooltip")}menuClick(t){if(t.item&&!t.item.disabled){var i=this.trigger(!0!==t.remove?"click":"remove",{target:t.item.id+":"+t.subItem.id,item:t.item,subItem:t.subItem,originalEvent:t.originalEvent});if(!0!==i.isCancelled){let l=t.subItem,r=this.get(t.item.id),e=r.items;if("function"==typeof e&&(e=r.items()),"menu"==r.type&&(r.selected=l.id),"menu-radio"==r.type&&(r.selected=l.id,Array.isArray(e)&&e.forEach(e=>{!0===e.checked&&delete e.checked,Array.isArray(e.items)&&e.items.forEach(e=>{!0===e.checked&&delete e.checked})}),l.checked=!0),"menu-check"==r.type)if(Array.isArray(r.selected)||(r.selected=[]),null==l.group){var n=r.selected.indexOf(l.id);-1==n?(r.selected.push(l.id),l.checked=!0):(r.selected.splice(n,1),l.checked=!1)}else if(!1!==l.group){let i=[];n=r.selected.indexOf(l.id);let s=e=>{e.forEach(e=>{var t;e.group===l.group&&-1!=(t=r.selected.indexOf(e.id))&&(e.id!=l.id&&i.push(e.id),r.selected.splice(t,1)),Array.isArray(e.items)&&s(e.items)})};s(e),-1==n&&(r.selected.push(l.id),l.checked=!0)}if("string"==typeof l.route){let t=""!==l.route?String("/"+l.route).replace(/\/{2,}/g,"/"):"";var s=w2utils.parseRoute(t);if(0<s.keys.length)for(let e=0;e<s.keys.length;e++)null!=this.routeData[s.keys[e].name]&&(t=t.replace(new RegExp(":"+s.keys[e].name,"g"),this.routeData[s.keys[e].name]));setTimeout(()=>{window.location.hash=t},1)}this.refresh(t.item.id),i.finish()}}}colorClick(e){var t;e.item&&!e.item.disabled&&!0!==(t=this.trigger("click",{target:e.item.id,item:e.item,color:e.color,final:e.final,originalEvent:e.originalEvent})).isCancelled&&(e.item.color=e.color,this.refresh(e.item.id),t.finish())}mouseAction(e,t,i,s){var l=this.get(s),e=this.trigger("mouse"+i,{target:s,item:l,object:l,originalEvent:e});if(!0!==e.isCancelled&&!l.disabled&&!l.hidden){switch(i){case"Enter":query(t).addClass("over"),this.tooltipShow(s);break;case"Leave":query(t).removeClass("over down"),this.tooltipHide(s);break;case"Down":query(t).addClass("down");break;case"Up":query(t).removeClass("down")}e.finish()}}}class w2sidebar extends w2base{constructor(e){super(e.name),this.name=null,this.box=null,this.sidebar=null,this.parent=null,this.nodes=[],this.menu=[],this.routeData={},this.selected=null,this.icon=null,this.style="",this.topHTML="",this.bottomHTML="",this.flatButton=!1,this.keyboard=!0,this.flat=!1,this.hasFocus=!1,this.levelPadding=12,this.skipRefresh=!1,this.tabIndex=null,this.handle={size:0,style:"",html:"",tooltip:""},this.onClick=null,this.onDblClick=null,this.onMouseEnter=null,this.onMouseLeave=null,this.onContextMenu=null,this.onMenuClick=null,this.onExpand=null,this.onCollapse=null,this.onKeydown=null,this.onRender=null,this.onRefresh=null,this.onResize=null,this.onDestroy=null,this.onFocus=null,this.onBlur=null,this.onFlat=null,this.node_template={id:null,text:"",order:null,count:null,icon:null,nodes:[],style:"",route:null,selected:!1,expanded:!1,hidden:!1,disabled:!1,group:!1,groupShowHide:!0,collapsible:!1,plus:!1,onClick:null,onDblClick:null,onContextMenu:null,onExpand:null,onCollapse:null,parent:null,sidebar:null},this.last={badge:{}};var t=e.nodes;delete e.nodes,Object.assign(this,e),Array.isArray(t)&&this.add(t),e.nodes=t,"string"==typeof this.box&&(this.box=query(this.box).get(0)),this.box&&this.render(this.box)}add(e,t){return 1==arguments.length&&(t=arguments[0],e=this),"string"==typeof e&&(e=this.get(e)),this.insert(e=null!=e&&""!=e?e:this,null,t)}insert(t,i,s){let l,r,n,a,o;if(2==arguments.length&&"string"==typeof t)if(s=arguments[1],null!=(i=arguments[0])){if(null==(r=this.get(i)))return null!=(s=Array.isArray(s)?s:[s])[0].caption&&null==s[0].text&&(console.log("NOTICE: sidebar node.caption property is deprecated, please use node.text. Node -> ",s[0]),s[0].text=s[0].caption),l=s[0].text,console.log('ERROR: Cannot insert node "'+l+'" because cannot find node "'+i+'" to insert before.'),null;t=this.get(i).parent}else t=this;null!=(t="string"==typeof t?this.get(t):t)&&""!=t||(t=this),Array.isArray(s)||(s=[s]);for(let e=0;e<s.length;e++)if(null!=(a=s[e]).caption&&null==a.text&&(console.log("NOTICE: sidebar node.caption property is deprecated, please use node.text"),a.text=a.caption),null==typeof a.id)l=a.text,console.log('ERROR: Cannot insert node "'+l+'" because it has no id.');else if(null!=this.get(this,a.id))console.log("ERROR: Cannot insert node with id="+a.id+" (text: "+a.text+") because another node with the same id already exists.");else{if((n=Object.assign({},this.node_template,a)).sidebar=this,n.parent=t,o=n.nodes||[],n.nodes=[],null==i)t.nodes.push(n);else{if(null==(r=this.get(t,i,!0)))return console.log('ERROR: Cannot insert node "'+a.text+'" because cannot find node "'+i+'" to insert before.'),null;t.nodes.splice(r,0,n)}0<o.length&&this.insert(n,null,o)}return this.skipRefresh||this.refresh(t.id),n}remove(){let t=0,i;return Array.from(arguments).forEach(e=>{null!=(i=this.get(e))&&(null!=this.selected&&this.selected===i.id&&(this.selected=null),null!=(e=this.get(i.parent,e,!0)))&&(i.parent.nodes[e].selected&&i.sidebar.unselect(i.id),i.parent.nodes.splice(e,1),i.parent.collapsible=0<i.parent.nodes.length,t++)}),this.skipRefresh||(0<t&&1==arguments.length?this.refresh(i.parent.id):this.refresh()),t}set(t,i,s){if(2==arguments.length&&(s=i,i=t,t=this),null==(t="string"==typeof t?this.get(t):t).nodes)return null;for(let e=0;e<t.nodes.length;e++){var l;if(t.nodes[e].id===i)return l=this.update(i,s),0!=Object.keys(l).length&&(l=s.nodes,w2utils.extend(t.nodes[e],s,{nodes:[]}),null!=l&&this.add(t.nodes[e],l),this.skipRefresh||this.refresh(i)),!0;if(this.set(t.nodes[e],i,s))return!0}return!1}get(t,i,s){if(0===arguments.length){var l=[],r=this.find({});for(let e=0;e<r.length;e++)null!=r[e].id&&l.push(r[e].id);return l}if((1==arguments.length||2==arguments.length&&!0===i)&&(s=i,i=t,t=this),null!=(t="string"==typeof t?this.get(t):t).nodes)for(let e=0;e<t.nodes.length;e++){if(t.nodes[e].id==i)return!0===s?e:t.nodes[e];var n=this.get(t.nodes[e],i,s);if(n||0===n)return n}return null}setCount(e,t,i,s){var l=query(this.box).find(`#node_${w2utils.escapeId(e)} .w2ui-node-count`);0<l.length?(l.removeClass().addClass("w2ui-node-count "+(i||"")).text(t).get(0).style.cssText=s||"",this.last.badge[e]={className:i||"",style:s||""},this.get(e).count=t):(this.set(e,{count:t}),this.setCount(...arguments))}find(i,s,l){if(1==arguments.length&&(s=i,i=this),l=l||[],null!=(i="string"==typeof i?this.get(i):i).nodes)for(let t=0;t<i.nodes.length;t++){let e=!0;for(var r in s)i.nodes[t][r]!=s[r]&&(e=!1);e&&l.push(i.nodes[t]),0<i.nodes[t].nodes.length&&(l=this.find(i.nodes[t],s,l))}return l}sort(l,e){null==(l=l&&"object"==typeof l?l:{}).foldersFirst&&(l.foldersFirst=!0),null==l.caseSensitive&&(l.caseSensitive=!1),null==l.reverse&&(l.reverse=!1),(e=null==e?this.nodes:e).sort((i,s)=>{var e=i.nodes&&0<i.nodes.length,t=s.nodes&&0<s.nodes.length;if(!1===l.foldersFirst||!e&&!t||e&&t){let e=i.text,t=s.text;l.caseSensitive||(e=e.toLowerCase(),t=t.toLowerCase()),null!=i.order&&(e=i.order),null!=s.order&&(t=s.order);i=w2utils.naturalCompare(e,t);return(1===i||-1===i)&l.reverse?-i:i}return e&&!t?l.reverse?1:-1:!e&&t?l.reverse?-1:1:void 0}),e.forEach(e=>{e.nodes&&0<e.nodes.length&&this.sort(l,e.nodes)})}each(t,e){(e=null==e?this.nodes:e).forEach(e=>{t.call(this,e),e.nodes&&0<e.nodes.length&&this.each(t,e.nodes)})}search(e){let t=0,i=e.toLowerCase();return this.each(e=>{-1===e.text.toLowerCase().indexOf(i)?e.hidden=!0:(t++,function e(t){t.parent&&(t.parent.hidden=!1,e(t.parent))}(e),e.hidden=!1)}),this.refresh(),t}show(){let t=[];return Array.from(arguments).forEach(e=>{e=this.get(e);null!=e&&!1!==e.hidden&&(e.hidden=!1,t.push(e.id))}),0<t.length&&(1==arguments.length?this.refresh(arguments[0]):this.refresh()),t}hide(){let t=[];return Array.from(arguments).forEach(e=>{e=this.get(e);null!=e&&!0!==e.hidden&&(e.hidden=!0,t.push(e.id))}),0<t.length&&(1==arguments.length?this.refresh(arguments[0]):this.refresh()),t}enable(){let t=[];return Array.from(arguments).forEach(e=>{e=this.get(e);null!=e&&!1!==e.disabled&&(e.disabled=!1,t.push(e.id))}),0<t.length&&(1==arguments.length?this.refresh(arguments[0]):this.refresh()),t}disable(){let t=[];return Array.from(arguments).forEach(e=>{e=this.get(e);null!=e&&!0!==e.disabled&&(e.disabled=!0,e.selected&&this.unselect(e.id),t.push(e.id))}),0<t.length&&(1==arguments.length?this.refresh(arguments[0]):this.refresh()),t}select(e){var t=this.get(e);if(!t)return!1;if(this.selected==e&&t.selected)return!1;this.unselect(this.selected);var i=query(this.box).find("#node_"+w2utils.escapeId(e));return i.addClass("w2ui-selected").find(".w2ui-icon").addClass("w2ui-icon-selected"),0<i.length&&(this.inView(e)||this.scrollIntoView(e)),t.selected=!0,this.selected=e,!0}unselect(e){0===arguments.length&&(e=this.selected);var t=this.get(e);return!!t&&(t.selected=!1,query(this.box).find("#node_"+w2utils.escapeId(e)).removeClass("w2ui-selected").find(".w2ui-icon").removeClass("w2ui-icon-selected"),this.selected==e&&(this.selected=null),!0)}toggle(e){var t=this.get(e);return null!=t&&(t.plus?(this.set(e,{plus:!1}),this.expand(e),void this.refresh(e)):0!==t.nodes.length&&!!t.collapsible&&(this.get(e).expanded?this.collapse(e):this.expand(e)))}collapse(e){let t=this;var i,s=this.get(e);return null!=s&&(!0!==(i=this.trigger("collapse",{target:e,object:s})).isCancelled?(query(this.box).find("#node_"+w2utils.escapeId(e)+"_sub").hide(),query(this.box).find("#node_"+w2utils.escapeId(e)+" .w2ui-expanded").removeClass("w2ui-expanded").addClass("w2ui-collapsed"),s.expanded=!1,i.finish(),setTimeout(()=>{t.refresh(e)},0),!0):void 0)}expand(e){var t=this.get(e),i=this.trigger("expand",{target:e,object:t});if(!0!==i.isCancelled)return query(this.box).find("#node_"+w2utils.escapeId(e)+"_sub").show(),query(this.box).find("#node_"+w2utils.escapeId(e)+" .w2ui-collapsed").removeClass("w2ui-collapsed").addClass("w2ui-expanded"),t.expanded=!0,i.finish(),this.refresh(e),!0}collapseAll(t){if(null==(t="string"==typeof(t=null==t?this:t)?this.get(t):t).nodes)return!1;for(let e=0;e<t.nodes.length;e++)!0===t.nodes[e].expanded&&(t.nodes[e].expanded=!1),t.nodes[e].nodes&&0<t.nodes[e].nodes.length&&this.collapseAll(t.nodes[e]);return this.refresh(t.id),!0}expandAll(t){if(null==(t="string"==typeof(t=null==t?this:t)?this.get(t):t).nodes)return!1;for(let e=0;e<t.nodes.length;e++)!1===t.nodes[e].expanded&&(t.nodes[e].expanded=!0),t.nodes[e].nodes&&0<t.nodes[e].nodes.length&&this.expandAll(t.nodes[e]);this.refresh(t.id)}expandParents(e){e=this.get(e);return null!=e&&(e.parent&&(e.parent.expanded||(e.parent.expanded=!0,this.refresh(e.parent.id)),this.expandParents(e.parent.id)),!0)}click(l,r){let n=this,a=this.get(l);if(null!=a&&!a.disabled&&!a.group){query(n.box).find(".w2ui-node.w2ui-selected").each(e=>{var t=query(e).attr("id").replace("node_",""),t=n.get(t);null!=t&&(t.selected=!1),query(e).removeClass("w2ui-selected").find(".w2ui-icon").removeClass("w2ui-icon-selected")});let t=query(n.box).find("#node_"+w2utils.escapeId(l)),s=query(n.box).find("#node_"+w2utils.escapeId(n.selected));t.addClass("w2ui-selected").find(".w2ui-icon").addClass("w2ui-icon-selected"),setTimeout(()=>{var e=n.trigger("click",{target:l,originalEvent:r,node:a,object:a});if(!0===e.isCancelled)t.removeClass("w2ui-selected").find(".w2ui-icon").removeClass("w2ui-icon-selected"),s.addClass("w2ui-selected").find(".w2ui-icon").addClass("w2ui-icon-selected");else{if(null!=s&&(s.selected=!1),n.get(l).selected=!0,n.selected=l,"string"==typeof a.route){let t=""!==a.route?String("/"+a.route).replace(/\/{2,}/g,"/"):"";var i=w2utils.parseRoute(t);if(0<i.keys.length)for(let e=0;e<i.keys.length;e++)null!=n.routeData[i.keys[e].name]&&(t=t.replace(new RegExp(":"+i.keys[e].name,"g"),n.routeData[i.keys[e].name]));setTimeout(()=>{window.location.hash=t},1)}e.finish()}},1)}}focus(e){let t=this;e=this.trigger("focus",{target:this.name,originalEvent:e});if(!0===e.isCancelled)return!1;this.hasFocus=!0,query(this.box).find(".w2ui-sidebar-body").addClass("w2ui-focus"),setTimeout(()=>{var e=query(t.box).find("#sidebar_"+t.name+"_focus").get(0);document.activeElement!=e&&e.focus()},10),e.finish()}blur(e){e=this.trigger("blur",{target:this.name,originalEvent:e});if(!0===e.isCancelled)return!1;this.hasFocus=!1,query(this.box).find(".w2ui-sidebar-body").removeClass("w2ui-focus"),e.finish()}keydown(e){let n=this,t=n.get(n.selected);var i;function s(e,t){null==e||e.hidden||e.disabled||e.group||(n.click(e.id,t),n.inView(e.id))||n.scrollIntoView(e.id)}function l(e,t){for(e=t(e);null!=e&&(e.hidden||e.disabled)&&!e.group;)e=t(e);return e}function r(e){if(null==e)return null;var t=e.parent,e=n.get(e.id,!0);let i=0<e?function t(i){if(i.expanded&&0<i.nodes.length){let e=i.nodes[i.nodes.length-1];return(e.hidden||e.disabled||e.group?r:t)(e)}return i}(t.nodes[e-1]):t;return i=null!=i&&(i.hidden||i.disabled||i.group)?r(i):i}!0===n.keyboard&&(t=t||n.nodes[0],!0!==(i=n.trigger("keydown",{target:n.name,originalEvent:e})).isCancelled)&&(13!=e.keyCode&&32!=e.keyCode||0<t.nodes.length&&n.toggle(n.selected),37==e.keyCode&&(0<t.nodes.length&&t.expanded?n.collapse(n.selected):(s(t.parent),t.parent.group||n.collapse(t.parent.id))),39==e.keyCode&&(0<t.nodes.length||t.plus)&&!t.expanded&&n.expand(n.selected),38==e.keyCode&&(null==n.get(n.selected)?s(this.nodes[0]||null):s(l(t,r))),40==e.keyCode&&(null==n.get(n.selected)?s(this.nodes[0]||null):s(l(t,function t(i,e){if(null==i)return null;let s=i.parent;let l=n.get(i.id,!0);let r=null;if(i.expanded&&0<i.nodes.length&&!0!==e){let e=i.nodes[0];r=e.hidden||e.disabled||e.group?t(e):e}else r=s&&l+1<s.nodes.length?s.nodes[l+1]:t(s,!0);null!=r&&(r.hidden||r.disabled||r.group)&&(r=t(r));return r}))),[13,32,37,38,39,40].includes(e.keyCode)&&(e.preventDefault&&e.preventDefault(),e.stopPropagation)&&e.stopPropagation(),i.finish())}inView(e){var t,e=query(this.box).find("#node_"+w2utils.escapeId(e)).get(0);return!(!e||(t=query(this.box).find(".w2ui-sidebar-body").get(0),e.offsetTop<t.scrollTop)||e.offsetTop+e.clientHeight>t.clientHeight+t.scrollTop)}scrollIntoView(i,s){return new Promise((e,t)=>{null==i&&(i=this.selected),null!=this.get(i)&&(query(this.box).find("#node_"+w2utils.escapeId(i)).get(0).scrollIntoView({block:"center",inline:"center",behavior:s?"atuo":"smooth"}),setTimeout(()=>{this.resize(),e()},s?0:500))})}dblClick(e,t){var i=this.get(e),t=this.trigger("dblClick",{target:e,originalEvent:t,object:i});!0!==t.isCancelled&&(this.toggle(e),t.finish())}contextMenu(t,i){var e=this.get(t),s=(t!=this.selected&&this.click(t),this.trigger("contextMenu",{target:t,originalEvent:i,object:e,allowOnDisabled:!1}));!0===s.isCancelled||e.disabled&&!s.allowOnDisabled||(0<this.menu.length&&w2menu.show({name:this.name+"_menu",anchor:document.body,items:this.menu,originalEvent:i}).select(e=>{this.menuClick(t,parseInt(e.detail.index),i)}),i.preventDefault&&i.preventDefault(),s.finish())}menuClick(e,t,i){e=this.trigger("menuClick",{target:e,originalEvent:i,menuIndex:t,menuItem:this.menu[t]});!0!==e.isCancelled&&e.finish()}goFlat(){var e=this.trigger("flat",{goFlat:!this.flat});!0!==e.isCancelled&&(this.flat=!this.flat,this.refresh(),e.finish())}render(e){var i=Date.now();let s=this;"string"==typeof e&&(e=query(e).get(0));var l=this.trigger("render",{target:this.name,box:e??this.box});if(!0!==l.isCancelled&&(null!=e&&(0<query(this.box).find(".w2ui-sidebar-body").length&&query(this.box).removeAttr("name").removeClass("w2ui-reset w2ui-sidebar").html(""),this.box=e),this.box)){query(this.box).attr("name",this.name).addClass("w2ui-reset w2ui-sidebar").html(`<div>
<div class="w2ui-sidebar-top"></div>
<input id="sidebar_${this.name}_focus" ${this.tabIndex?'tabindex="'+this.tabIndex+'"':""}
style="position: absolute; top: 0; right: 0; width: 1px; z-index: -1; opacity: 0"
${w2utils.isIOS?"readonly":""}/>
<div class="w2ui-sidebar-body"></div>
<div class="w2ui-sidebar-bottom"></div>
</div>`);e=query(this.box).get(0).getBoundingClientRect();query(this.box).find(":scope > div").css({width:e.width+"px",height:e.height+"px"}),query(this.box).get(0).style.cssText+=this.style;let t;return query(this.box).find("#sidebar_"+this.name+"_focus").on("focus",function(e){clearTimeout(t),s.hasFocus||s.focus(e)}).on("blur",function(e){t=setTimeout(()=>{s.hasFocus&&s.blur(e)},100)}).on("keydown",function(e){9!=e.keyCode&&w2ui[s.name].keydown.call(w2ui[s.name],e)}),query(this.box).off("mousedown").on("mousedown",function(t){setTimeout(()=>{var e;-1==["INPUT","TEXTAREA","SELECT"].indexOf(t.target.tagName.toUpperCase())&&(e=query(s.box).find("#sidebar_"+s.name+"_focus"),document.activeElement!=e.get(0))&&e.get(0).focus()},1)}),this.last.observeResize=new ResizeObserver(()=>{this.resize()}),this.last.observeResize.observe(this.box),l.finish(),this.refresh(),Date.now()-i}}update(e,t){var i,s,e=this.get(e);let l;return e&&(i=query(this.box).find("#node_"+w2utils.escapeId(e.id)),e.group?(t.text&&(e.text=t.text,i.find(".w2ui-group-text").replace("function"==typeof e.text?e.text.call(this,e):'<span class="w2ui-group-text">'+e.text+"</span>"),delete t.text),t.class&&(e.class=t.class,l=i.data("level"),i.get(0).className="w2ui-node-group w2ui-level-"+l+(e.class?" "+e.class:""),delete t.class),t.style&&(e.style=t.style,i.get(0).nextElementSibling.style=e.style+";"+(!e.hidden&&e.expanded?"":"display: none;"),delete t.style)):(t.icon&&0<(s=i.find(".w2ui-node-image > span")).length&&(e.icon=t.icon,s[0].className="function"==typeof e.icon?e.icon.call(this,e):e.icon,delete t.icon),t.count&&(e.count=t.count,i.find(".w2ui-node-count").html(e.count),0<i.find(".w2ui-node-count").length)&&delete t.count,t.class&&0<i.length&&(e.class=t.class,l=i.data("level"),i[0].className="w2ui-node w2ui-level-"+l+(e.selected?" w2ui-selected":"")+(e.disabled?" w2ui-disabled":"")+(e.class?" "+e.class:""),delete t.class),t.text&&(e.text=t.text,i.find(".w2ui-node-text").html("function"==typeof e.text?e.text.call(this,e):e.text),delete t.text),t.style&&0<i.length&&(s=i.find(".w2ui-node-text"),e.style=t.style,s[0].style=e.style,delete t.style))),t}refresh(l,r){if(null!=this.box){var n=Date.now(),a=this.trigger("refresh",{target:null!=l?l:this.name,nodeId:null!=l?l:null,fullRefresh:null==l});if(!0!==a.isCancelled){let e="";1==this.flatButton&&(e=`<div class="w2ui-flat w2ui-flat-${this.flat?"right":"left"}"></div>`),null!=l||""===this.topHTML&&""===e||(query(this.box).find(".w2ui-sidebar-top").html(this.topHTML+e),query(this.box).find(".w2ui-sidebar-body").css("top",query(this.box).find(".w2ui-sidebar-top").get(0)?.clientHeight+"px"),query(this.box).find(".w2ui-flat").off("click").on("click",e=>{this.goFlat()})),null!=l&&""!==this.bottomHTML&&(query(this.box).find(".w2ui-sidebar-bottom").html(this.bottomHTML),query(this.box).find(".w2ui-sidebar-body").css("bottom",query(this.box).find(".w2ui-sidebar-bottom").get(0)?.clientHeight+"px")),query(this.box).find(":scope > div").removeClass("w2ui-sidebar-flat").addClass(this.flat?"w2ui-sidebar-flat":"").css({width:query(this.box).get(0)?.clientWidth+"px",height:query(this.box).get(0)?.clientHeight+"px"}),0<this.nodes.length&&null==this.nodes[0].parent&&(o=this.nodes,this.nodes=[],this.add(this,o));let h=this,t,i;if(null==l)t=this,i=".w2ui-sidebar-body";else{if(null==(t=this.get(l)))return;i="#node_"+w2utils.escapeId(t.id)+"_sub"}var o="#node_"+w2utils.escapeId(t.id);let s;t!==this&&(s=c(t),query(this.box).find(o).before('<div id="sidebar_'+this.name+'_tmp"></div>'),query(this.box).find(o).remove(),query(this.box).find(i).remove(),query(this.box).find("#sidebar_"+this.name+"_tmp").before(s),query(this.box).find("#sidebar_"+this.name+"_tmp").remove());var l=query(this.box).find(":scope > div").get(0),d={top:l?.scrollTop,left:l?.scrollLeft};query(this.box).find(i).html("");for(let e=0;e<t.nodes.length;e++){var u=t.nodes[e];if(s=c(u),query(this.box).find(i).append(s),0!==u.nodes.length)this.refresh(u.id,!0);else{u=this.trigger("refresh",{target:u.id});if(!0===u.isCancelled)return;u.finish()}}return l&&(l.scrollTop=d.top,l.scrollLeft=d.left),r||(l=query(this.box).find(o+`.w2ui-eaction, ${i} .w2ui-eaction`),w2utils.bindEvents(l,this)),a.finish(),Date.now()-n;function c(t){let i="",s=t.icon,l=(null==s&&(s=h.icon),t.parent),r=0;for(;l&&null!=l.parent;)l=l.parent,r++;if(null!=t.caption&&null==t.text&&(t.text=t.caption),null!=t.caption&&(console.log("NOTICE: sidebar node.caption property is deprecated, please use node.text. Node -> ",t),t.text=t.caption),Array.isArray(t.nodes)&&0<t.nodes.length&&(t.collapsible=!0),t.group){let e=w2utils.lang("function"==typeof t.text?t.text.call(h,t):t.text);"<span"!=String(e).substr(0,5)&&(e=`<span class="w2ui-group-text">${e}</span>`),i=`
<div id="node_${t.id}" data-level="${r}" style="${t.hidden?"display: none":""}"
class="w2ui-node-group w2ui-level-${r} ${t.class||""} w2ui-eaction"
data-click="toggle|${t.id}"
data-contextmenu="contextMenu|${t.id}|event"
data-mouseenter="showPlus|this|inherit"
data-mouseleave="showPlus|this|transparent">
${t.groupShowHide&&t.collapsible?`<span>${!t.hidden&&t.expanded?w2utils.lang("Hide"):w2utils.lang("Show")}</span>`:"<span></span>"} ${e}
</div>
<div class="w2ui-node-sub" id="node_${t.id}_sub" style="${t.style}; ${!t.hidden&&t.expanded?"":"display: none;"}">
</div>`,h.flat&&(i=`
<div class="w2ui-node-group" id="node_${t.id}"><span> </span></div>
<div id="node_${t.id}_sub" style="${t.style}; ${!t.hidden&&t.expanded?"":"display: none;"}"></div>`)}else{t.selected&&!t.disabled&&(h.selected=t.id),l="",s&&(l=`
<div class="w2ui-node-image">
<span class="${"function"==typeof s?s.call(h,t):s}"></span>
</div>`);let e="";var n=null!=t.count?`<div class="w2ui-node-count ${h.last.badge[t.id]&&h.last.badge[t.id].className||""}"
style="${h.last.badge[t.id]&&h.last.badge[t.id].style||""}">
${t.count}
</div>`:"",a=(!0===t.collapsible&&(e=`<div class="w2ui-${t.expanded?"expanded":"collapsed"}"><span></span></div>`),w2utils.lang("function"==typeof t.text?t.text.call(h,t):t.text)),o=["w2ui-node","w2ui-level-"+r,"w2ui-eaction"];t.selected&&o.push("w2ui-selected"),t.disabled&&o.push("w2ui-disabled"),t.class&&o.push(t.class),i=`
<div id="node_${t.id}" class="${o.join(" ")}" data-level="${r}"
style="position: relative; ${t.hidden?"display: none;":""}"
data-click="click|${t.id}|event"
data-dblclick="dblClick|${t.id}|event"
data-contextmenu="contextMenu|${t.id}|event"
data-mouseEnter="mouseAction|Enter|this|${t.id}|event"
data-mouseLeave="mouseAction|Leave|this|${t.id}|event"
>
${h.handle.html?`<div class="w2ui-node-handle w2ui-eaction" style="width: ${h.handle.size}px; ${h.handle.style}"
data-mouseEnter="mouseAction|Enter|this|${t.id}|event|handle"
data-mouseLeave="mouseAction|Leave|this|${t.id}|event|handle"
>
${"function"==typeof h.handle.html?h.handle.html.call(h,t):h.handle.html}
</div>`:""}
<div class="w2ui-node-data" style="margin-left: ${r*h.levelPadding+h.handle.size}px">
${e} ${l} ${n}
<div class="w2ui-node-text w2ui-node-caption" style="${t.style||""}">${a}</div>
</div>
</div>
<div class="w2ui-node-sub" id="node_${t.id}_sub" style="${t.style}; ${!t.hidden&&t.expanded?"":"display: none;"}"></div>`,h.flat&&(i=`
<div id="node_${t.id}" class="${o.join(" ")}" style="${t.hidden?"display: none;":""}"
data-click="click|${t.id}|event"
data-dblclick="dblClick|${t.id}|event"
data-contextmenu="contextMenu|${t.id}|event"
data-mouseEnter="mouseAction|Enter|this|${t.id}|event|tooltip"
data-mouseLeave="mouseAction|Leave|this|${t.id}|event|tooltip"
>
<div class="w2ui-node-data w2ui-node-flat">${l}</div>
</div>
<div class="w2ui-node-sub" id="node_${t.id}_sub" style="${t.style}; ${!t.hidden&&t.expanded?"":"display: none;"}"></div>`)}return i}}}}mouseAction(e,t,i,s,l){var r=this.get(i),n=w2utils.lang("function"==typeof r.text?r.text.call(this,r):r.text)+(r.count||0===r.count?' - <span class="w2ui-node-count">'+r.count+"</span>":""),e=this.trigger("mouse"+e,{target:i,node:r,tooltip:n,originalEvent:s});"tooltip"==l&&this.tooltip(t,n,i),"handle"==l&&this.handleTooltip(t,i),e.finish()}tooltip(e,t,i){e=query(e).find(".w2ui-node-data");""!==t?w2tooltip.show({anchor:e.get(0),name:this.name+"_tooltip",html:t,position:"right|left"}):w2tooltip.hide(this.name+"_tooltip")}handleTooltip(e,t){let i=this.handle.tooltip;""!==(i="function"==typeof i?i(t):i)&&null!=t?w2tooltip.show({anchor:e,name:this.name+"_tooltip",html:i,position:"top|bottom"}):w2tooltip.hide(this.name+"_tooltip")}showPlus(e,t){query(e).find("span:nth-child(1)").css("color",t)}resize(){var e,t=Date.now(),i=this.trigger("resize",{target:this.name});if(!0!==i.isCancelled)return e=query(this.box).get(0).getBoundingClientRect(),query(this.box).css("overflow","hidden"),query(this.box).find(":scope > div").css({width:e.width+"px",height:e.height+"px"}),i.finish(),Date.now()-t}destroy(){var e=this.trigger("destroy",{target:this.name});!0!==e.isCancelled&&(0<query(this.box).find(".w2ui-sidebar-body").length&&query(this.box).removeAttr("name").removeClass("w2ui-reset w2ui-sidebar").html(""),this.last.observeResize?.disconnect(),delete w2ui[this.name],e.finish())}lock(e,t){var i=Array.from(arguments);i.unshift(this.box),w2utils.lock(...i)}unlock(e){w2utils.unlock(this.box,e)}}class w2tabs extends w2base{constructor(e){super(e.name),this.box=null,this.name=null,this.active=null,this.reorder=!1,this.flow="down",this.tooltip="top|left",this.tabs=[],this.routeData={},this.last={},this.right="",this.style="",this.onClick=null,this.onMouseEnter=null,this.onMouseLeave=null,this.onMouseDown=null,this.onMouseUp=null,this.onClose=null,this.onRender=null,this.onRefresh=null,this.onResize=null,this.onDestroy=null,this.tab_template={id:null,text:null,route:null,hidden:!1,disabled:!1,closable:!1,tooltip:null,style:"",onClick:null,onRefresh:null,onClose:null};var t=e.tabs;delete e.tabs,Object.assign(this,e),Array.isArray(t)&&this.add(t),e.tabs=t,"string"==typeof this.box&&(this.box=query(this.box).get(0)),this.box&&this.render(this.box)}add(e){return this.insert(null,e)}insert(s,e){Array.isArray(e)||(e=[e]);let l=[];return e.forEach(e=>{var t,i;null==e.id?console.log(`ERROR: The parameter "id" is required but not supplied. (obj: ${this.name})`):w2utils.checkUniqueId(e.id,this.tabs,"tabs",this.name)&&(e=Object.assign({},this.tab_template,e),null==s?(this.tabs.push(e),l.push(this.animateInsert(null,e))):(t=this.get(s,!0),i=this.tabs[t].id,this.tabs.splice(t,0,e),l.push(this.animateInsert(i,e))))}),Promise.all(l)}remove(){let t=0;return Array.from(arguments).forEach(e=>{e=this.get(e);e&&(t++,this.tabs.splice(this.get(e.id,!0),1),query(this.box).find(`#tabs_${this.name}_tab_`+w2utils.escapeId(e.id)).remove())}),this.resize(),t}select(e){return this.active!=e&&null!=this.get(e)&&(this.active=e,this.refresh(),!0)}set(e,t){var i=this.get(e,!0);return null!=i&&(w2utils.extend(this.tabs[i],t),this.refresh(e),!0)}get(t,i){if(0===arguments.length){var s=[];for(let e=0;e<this.tabs.length;e++)null!=this.tabs[e].id&&s.push(this.tabs[e].id);return s}for(let e=0;e<this.tabs.length;e++)if(this.tabs[e].id==t)return!0===i?e:this.tabs[e];return null}show(){let t=[];return Array.from(arguments).forEach(e=>{e=this.get(e);e&&!1!==e.hidden&&(e.hidden=!1,t.push(e.id))}),setTimeout(()=>{t.forEach(e=>{this.refresh(e),this.resize()})},15),t}hide(){let t=[];return Array.from(arguments).forEach(e=>{e=this.get(e);e&&!0!==e.hidden&&(e.hidden=!0,t.push(e.id))}),setTimeout(()=>{t.forEach(e=>{this.refresh(e),this.resize()})},15),t}enable(){let t=[];return Array.from(arguments).forEach(e=>{e=this.get(e);e&&!1!==e.disabled&&(e.disabled=!1,t.push(e.id))}),setTimeout(()=>{t.forEach(e=>{this.refresh(e)})},15),t}disable(){let t=[];return Array.from(arguments).forEach(e=>{e=this.get(e);e&&!0!==e.disabled&&(e.disabled=!0,t.push(e.id))}),setTimeout(()=>{t.forEach(e=>{this.refresh(e)})},15),t}dragMove(i){if(this.last.reordering){let s=this;var l=this.last.moving,r=this.tabs[l.index],n=h(l.index,1),a=h(l.index,-1),r=query(this.box).find("#tabs_"+this.name+"_tab_"+w2utils.escapeId(r.id));if(0<l.divX&&n){var o=query(this.box).find("#tabs_"+this.name+"_tab_"+w2utils.escapeId(n.id));let e=parseInt(r.get(0).clientWidth),t=parseInt(o.get(0).clientWidth);if(e=e<t?Math.floor(e/3):Math.floor(t/3),t-=e,l.divX>t)return n=this.tabs.indexOf(n),this.tabs.splice(l.index,0,this.tabs.splice(n,1)[0]),l.$tab.before(o.get(0)),l.$tab.css("opacity",0),void Object.assign(this.last.moving,{index:n,divX:-e,x:i.pageX+e,left:l.left+l.divX+e})}if(l.divX<0&&a){o=query(this.box).find("#tabs_"+this.name+"_tab_"+w2utils.escapeId(a.id));let e=parseInt(r.get(0).clientWidth),t=parseInt(o.get(0).clientWidth);e=e<t?Math.floor(e/3):Math.floor(t/3),t-=e,Math.abs(l.divX)>t&&(n=this.tabs.indexOf(a),this.tabs.splice(l.index,0,this.tabs.splice(n,1)[0]),o.before(l.$tab),l.$tab.css("opacity",0),Object.assign(l,{index:n,divX:e,x:i.pageX-e,left:l.left+l.divX-e}))}function h(e,t){e+=t;let i=s.tabs[e];return i=i&&i.hidden?h(e,t):i}}}mouseAction(e,t,i){var s=this.get(t),l=this.trigger("mouse"+e,{target:t,tab:s,object:s,originalEvent:i});if(!0!==l.isCancelled&&!s.disabled&&!s.hidden){switch(e){case"Enter":this.tooltipShow(t);break;case"Leave":this.tooltipHide(t);break;case"Down":this.initReorder(t,i)}l.finish()}}tooltipShow(t){var i=this.get(t),t=query(this.box).find("#tabs_"+this.name+"_tab_"+w2utils.escapeId(t)).get(0);if(null!=this.tooltip&&!i.disabled&&!this.last.reordering){var s=this.tooltip;let e=i.tooltip;"function"==typeof e&&(e=e.call(this,i)),w2tooltip.show({anchor:t,name:this.name+"_tooltip",html:e,position:s})}}tooltipHide(e){null!=this.tooltip&&w2tooltip.hide(this.name+"_tooltip")}getTabHTML(e){e=this.get(e,!0),e=this.tabs[e];if(null==e)return!1;null==e.text&&null!=e.caption&&(e.text=e.caption),null==e.tooltip&&null!=e.hint&&(e.tooltip=e.hint),null!=e.caption&&console.log("NOTICE: tabs tab.caption property is deprecated, please use tab.text. Tab -> ",e),null!=e.hint&&console.log("NOTICE: tabs tab.hint property is deprecated, please use tab.tooltip. Tab -> ",e);let t=e.text,i=(null==(t="function"==typeof t?t.call(this,e):t)&&(t=""),""),s="";return e.hidden&&(s+="display: none;"),e.disabled&&(s+="opacity: 0.2;"),e.closable&&!e.disabled&&(i=`<div class="w2ui-tab-close w2ui-eaction ${this.active===e.id?"active":""}"
data-mousedown="stop" data-mouseup="clickClose|${e.id}|event">
</div>`),`
<div id="tabs_${this.name}_tab_${e.id}" style="${s} ${e.style}"
class="w2ui-tab w2ui-eaction ${this.active===e.id?"active":""} ${e.closable?"closable":""} ${e.class||""}"
data-mouseenter="mouseAction|Enter|${e.id}|event]"
data-mouseleave="mouseAction|Leave|${e.id}|event]"
data-mousedown="mouseAction|Down|${e.id}|event"
data-mouseup="mouseAction|Up|${e.id}|event"
data-click="click|${e.id}|event"
>
${w2utils.lang(t)+i}
</div>`}refresh(e){var t=Date.now(),i=("up"==this.flow?query(this.box).addClass("w2ui-tabs-up"):query(this.box).removeClass("w2ui-tabs-up"),this.trigger("refresh",{target:null!=e?e:this.name,object:this.get(e)}));if(!0!==i.isCancelled){if(null==e)for(let e=0;e<this.tabs.length;e++)this.refresh(this.tabs[e].id);else{var s="#tabs_"+this.name+"_tab_"+w2utils.escapeId(e),l=query(this.box).find(s),e=this.getTabHTML(e);0===l.length?query(this.box).find("#tabs_"+this.name+"_right").before(e):0==query(this.box).find(".tab-animate-insert").length&&l.replace(e),w2utils.bindEvents(query(this.box).find(s+`, ${s} .w2ui-eaction`),this)}return query(this.box).find("#tabs_"+this.name+"_right").html(this.right),i.finish(),Date.now()-t}}render(e){var t=Date.now(),i=("string"==typeof e&&(e=query(e).get(0)),this.trigger("render",{target:this.name,box:e??this.box}));if(!0!==i.isCancelled)return null!=e&&(0<query(this.box).find("#tabs_"+this.name+"_right").length&&query(this.box).removeAttr("name").removeClass("w2ui-reset w2ui-tabs").html(""),this.box=e),!!this.box&&(e=`
<div class="w2ui-tabs-line"></div>
<div class="w2ui-scroll-wrapper w2ui-eaction" data-mousedown="resize">
<div id="tabs_${this.name}_right" class="w2ui-tabs-right">${this.right}</div>
</div>
<div class="w2ui-scroll-left w2ui-eaction" data-click='["scroll","left"]'></div>
<div class="w2ui-scroll-right w2ui-eaction" data-click='["scroll","right"]'></div>`,query(this.box).attr("name",this.name).addClass("w2ui-reset w2ui-tabs").html(e),0<query(this.box).length&&(query(this.box)[0].style.cssText+=this.style),w2utils.bindEvents(query(this.box).find(".w2ui-eaction"),this),this.last.observeResize=new ResizeObserver(()=>{this.resize()}),this.last.observeResize.observe(this.box),i.finish(),this.refresh(),this.resize(),Date.now()-t)}initReorder(e,n){if(this.reorder){let t=this,i=query(this.box).find("#tabs_"+this.name+"_tab_"+w2utils.escapeId(e)),s=this.get(e,!0),l=query(i.get(0).cloneNode(!0)),r;l.attr("id","#tabs_"+this.name+"_tab_ghost"),this.last.moving={index:s,indexFrom:s,$tab:i,$ghost:l,divX:0,left:i.get(0).getBoundingClientRect().left,parentX:query(this.box).get(0).getBoundingClientRect().left,x:n.pageX,opacity:i.css("opacity")},query(document).off(".w2uiTabReorder").on("mousemove.w2uiTabReorder",function(e){if(!t.last.reordering){if(!0===(r=t.trigger("reorder",{target:t.tabs[s].id,indexFrom:s,tab:t.tabs[s]})).isCancelled)return;w2tooltip.hide(this.name+"_tooltip"),t.last.reordering=!0,l.addClass("moving"),l.css({"pointer-events":"none",position:"absolute",left:i.get(0).getBoundingClientRect().left}),i.css("opacity",0),query(t.box).find(".w2ui-scroll-wrapper").append(l.get(0)),query(t.box).find(".w2ui-tab-close").hide()}t.last.moving.divX=e.pageX-t.last.moving.x,l.css("left",t.last.moving.left-t.last.moving.parentX+t.last.moving.divX+"px"),t.dragMove(e)}).on("mouseup.w2uiTabReorder",function(){query(document).off(".w2uiTabReorder"),l.css({transition:"0.1s",left:t.last.moving.$tab.get(0).getBoundingClientRect().left-t.last.moving.parentX}),query(t.box).find(".w2ui-tab-close").show(),setTimeout(()=>{l.remove(),i.css({opacity:t.last.moving.opacity}),t.last.reordering&&r.finish({indexTo:t.last.moving.index}),t.last.reordering=!1},100)})}}scroll(a,o){return new Promise((e,t)=>{var i=query(this.box).find(".w2ui-scroll-wrapper"),s=i.get(0).scrollLeft,l=i.find(".w2ui-tabs-right").get(0),r=i.parent().get(0).getBoundingClientRect().width,n=s+parseInt(l.offsetLeft)+parseInt(l.clientWidth);switch(a){case"left":{let e=s-r+50;e<=0&&(e=0),i.get(0).scrollTo({top:0,left:e,behavior:o?"atuo":"smooth"});break}case"right":{let e=s+r-50;e>=n-r&&(e=n-r),i.get(0).scrollTo({top:0,left:e,behavior:o?"atuo":"smooth"});break}}setTimeout(()=>{this.resize(),e()},o?0:350)})}scrollIntoView(i,s){return new Promise((e,t)=>{null==i&&(i=this.active),null!=this.get(i)&&(query(this.box).find("#tabs_"+this.name+"_tab_"+w2utils.escapeId(i)).get(0).scrollIntoView({block:"start",inline:"center",behavior:s?"atuo":"smooth"}),setTimeout(()=>{this.resize(),e()},s?0:500))})}resize(){var e=Date.now();if(null!=this.box){var t,i,s,l,r=this.trigger("resize",{target:this.name});if(!0!==r.isCancelled)return(t=query(this.box)).find(".w2ui-scroll-left, .w2ui-scroll-right").hide(),i=t.find(".w2ui-scroll-wrapper").get(0),l=t.find(".w2ui-tabs-right"),(s=t.get(0).getBoundingClientRect().width)<(l=0<l.length?l[0].offsetLeft+l[0].clientWidth:0)&&(0<i.scrollLeft&&t.find(".w2ui-scroll-left").show(),s<l-i.scrollLeft)&&t.find(".w2ui-scroll-right").show(),r.finish(),Date.now()-e}}destroy(){var e=this.trigger("destroy",{target:this.name});!0!==e.isCancelled&&(0<query(this.box).find("#tabs_"+this.name+"_right").length&&query(this.box).removeAttr("name").removeClass("w2ui-reset w2ui-tabs").html(""),this.last.observeResize?.disconnect(),delete w2ui[this.name],e.finish())}click(e,t){var i=this.get(e);if(null==i||i.disabled||this.last.reordering)return!1;e=this.trigger("click",{target:e,tab:i,object:i,originalEvent:t});if(!0!==e.isCancelled){if(query(this.box).find("#tabs_"+this.name+"_tab_"+w2utils.escapeId(this.active)).removeClass("active"),this.active=i.id,query(this.box).find("#tabs_"+this.name+"_tab_"+w2utils.escapeId(this.active)).addClass("active"),"string"==typeof i.route){let t=""!==i.route?String("/"+i.route).replace(/\/{2,}/g,"/"):"";var s=w2utils.parseRoute(t);if(0<s.keys.length)for(let e=0;e<s.keys.length;e++)null!=this.routeData[s.keys[e].name]&&(t=t.replace(new RegExp(":"+s.keys[e].name,"g"),this.routeData[s.keys[e].name]));setTimeout(()=>{window.location.hash=t},1)}e.finish()}}clickClose(e,t){var i=this.get(e);if(null==i||i.disabled)return!1;let s=this.trigger("close",{target:e,object:i,tab:i,originalEvent:t});!0!==s.isCancelled&&(this.animateClose(e).then(()=>{this.remove(e),s.finish(),this.refresh()}),t)&&t.stopPropagation()}animateClose(r){return new Promise((e,t)=>{var i=query(this.box).find("#tabs_"+this.name+"_tab_"+w2utils.escapeId(r)),s=parseInt(i.get(0).clientWidth||0);let l=i.replace(`<div class="tab-animate-close" style="display: inline-block; flex-shrink: 0; width: ${s}px; transition: width 0.25s"></div>`);setTimeout(()=>{l.css({width:"0px"})},1),setTimeout(()=>{l.remove(),this.resize(),e()},500)})}animateInsert(t,r){return new Promise((i,e)=>{let s=query(this.box).find("#tabs_"+this.name+"_tab_"+w2utils.escapeId(t)),l=query.html(this.getTabHTML(r.id));if(0==s.length)(s=query(this.box).find("#tabs_tabs_right")).before(l),this.resize();else{l.css({opacity:0}),query(this.box).find("#tabs_tabs_right").before(l.get(0));let e=query(this.box).find("#"+l.attr("id")).get(0).clientWidth??0,t=query.html('<div class="tab-animate-insert" style="flex-shrink: 0; width: 0; transition: width 0.25s"></div>');s.before(t),l.hide(),t.before(l[0]),setTimeout(()=>{t.css({width:e+"px"})},1),setTimeout(()=>{t.remove(),l.css({opacity:1}).show(),this.refresh(r.id),this.resize(),i()},500)}})}}let w2panels=["top","left","main","preview","right","bottom"];class w2layout extends w2base{constructor(e){super(e.name),this.box=null,this.name=null,this.panels=[],this.last={},this.padding=1,this.resizer=4,this.style="",this.onShow=null,this.onHide=null,this.onResizing=null,this.onResizerClick=null,this.onRender=null,this.onRefresh=null,this.onChange=null,this.onResize=null,this.onDestroy=null,this.panel_template={type:null,title:"",size:100,minSize:20,maxSize:!1,hidden:!1,resizable:!1,overflow:"auto",style:"",html:"",tabs:null,toolbar:null,width:null,height:null,show:{toolbar:!1,tabs:!1},removed:null,onRefresh:null,onShow:null,onHide:null},Object.assign(this,e),Array.isArray(this.panels)||(this.panels=[]),this.panels.forEach((e,t)=>{var i,s,l;this.panels[t]=w2utils.extend({},this.panel_template,e),(w2utils.isPlainObject(e.tabs)||Array.isArray(e.tabs))&&function(e,t,i){var s=e.get(t);null!=s&&null==i&&(i=s.tabs);if(null==s||null==i)return;Array.isArray(i)&&(i={tabs:i});var l=e.name+"_"+t+"_tabs";w2ui[l]&&w2ui[l].destroy();s.tabs=new w2tabs(w2utils.extend({},i,{owner:e,name:e.name+"_"+t+"_tabs"})),s.show.tabs=!0}(this,e.type),(w2utils.isPlainObject(e.toolbar)||Array.isArray(e.toolbar))&&(t=this,e=e.type,i=void 0,null!=(s=t.get(e))&&null==i&&(i=s.toolbar),null!=s)&&null!=i&&(Array.isArray(i)&&(i={items:i}),l=t.name+"_"+e+"_toolbar",w2ui[l]&&w2ui[l].destroy(),s.toolbar=new w2toolbar(w2utils.extend({},i,{owner:t,name:t.name+"_"+e+"_toolbar"})),s.show.toolbar=!0)}),w2panels.forEach(e=>{null==this.get(e)&&this.panels.push(w2utils.extend({},this.panel_template,{type:e,hidden:"main"!==e,size:50}))}),"string"==typeof this.box&&(this.box=query(this.box).get(0)),this.box&&this.render(this.box)}html(l,r,n){let a=this.get(l);var e={panel:l,html:a.html,error:!1,cancelled:!1,removed(e){"function"==typeof e&&(a.removed=e)}};if("function"==typeof a.removed&&(a.removed({panel:l,html:a.html,html_new:r,transition:n||"none"}),a.removed=null),"css"==l)query(this.box).find("#layout_"+this.name+"_panel_css").html("<style>"+r+"</style>"),e.status=!0;else if(null==a)console.log("ERROR: incorrect panel name. Panel name can be main, left, right, top, bottom, preview or css"),e.error=!0;else if(null!=r){var t=this.trigger("change",{target:l,panel:a,html_new:r,transition:n});if(!0===t.isCancelled)e.cancelled=!0;else{let i="#layout_"+this.name+"_panel_"+a.type;var o=query(this.box).find(i+"> .w2ui-panel-content");let s=0;if(0<o.length&&(query(this.box).find(i).get(0).scrollTop=0,s=query(o).css("top")),""===a.html)a.html=r,this.refresh(l);else if(a.html=r,!a.hidden)if(null!=n&&""!==n){query(this.box).addClass("animating");let e=query(this.box).find(i+"> .w2ui-panel-content"),t=(e.after('<div class="w2ui-panel-content new-panel" style="'+e[0].style.cssText+'"></div>'),query(this.box).find(i+"> .w2ui-panel-content.new-panel"));e.css("top",s),t.css("top",s),"object"==typeof r?(r.box=t[0],r.render()):t.hide().html(r),w2utils.transition(e[0],t[0],n,()=>{e.remove(),t.removeClass("new-panel"),t.css("overflow",a.overflow),query(query(this.box).find(i+"> .w2ui-panel-content").get(1)).remove(),query(this.box).removeClass("animating"),this.refresh(l)})}else this.refresh(l);t.finish()}}return e}message(e,t){var i=this.get(e);let s=query(this.box).find("#layout_"+this.name+"_panel_"+i.type),l=s.css("overflow");s.css("overflow","hidden");i=w2utils.message({owner:this,box:s.get(0),after:".w2ui-panel-title",param:e},t);return i&&i.self.on("close:after",()=>{s.css("overflow",l)}),i}confirm(e,t){var i=this.get(e);let s=query(this.box).find("#layout_"+this.name+"_panel_"+i.type),l=s.css("overflow");s.css("overflow","hidden");i=w2utils.confirm({owner:this,box:s.get(0),after:".w2ui-panel-title",param:e},t);return i&&i.self.on("close:after",()=>{s.css("overflow",l)}),i}load(i,s,l){return new Promise((t,e)=>{"css"!=i&&null==this.get(i)||null==s?e():fetch(s).then(e=>e.text()).then(e=>{this.resize(),t(this.html(i,e,l))})})}sizeTo(e,t,i){return null!=this.get(e)&&(query(this.box).find(":scope > div > .w2ui-panel").css("transition",!0!==i?".2s":"0s"),setTimeout(()=>{this.set(e,{size:t})},1),setTimeout(()=>{query(this.box).find(":scope > div > .w2ui-panel").css("transition","0s"),this.resize()},300),!0)}show(e,t){let i=this.trigger("show",{target:e,thisect:this.get(e),immediate:t});var s;if(!0!==i.isCancelled)return null!=(s=this.get(e))&&(!(s.hidden=!1)===t?(query(this.box).find("#layout_"+this.name+"_panel_"+e).css({opacity:"1"}),i.finish(),this.resize()):(query(this.box).addClass("animating"),query(this.box).find("#layout_"+this.name+"_panel_"+e).css({opacity:"0"}),query(this.box).find(":scope > div > .w2ui-panel").css("transition",".2s"),setTimeout(()=>{this.resize()},1),setTimeout(()=>{query(this.box).find("#layout_"+this.name+"_panel_"+e).css({opacity:"1"})},250),setTimeout(()=>{query(this.box).find(":scope > div > .w2ui-panel").css("transition","0s"),query(this.box).removeClass("animating"),i.finish(),this.resize()},300)),!0)}hide(e,t){let i=this.trigger("hide",{target:e,object:this.get(e),immediate:t});var s;if(!0!==i.isCancelled)return null!=(s=this.get(e))&&((s.hidden=!0)===t?(query(this.box).find("#layout_"+this.name+"_panel_"+e).css({opacity:"0"}),i.finish(),this.resize()):(query(this.box).addClass("animating"),query(this.box).find(":scope > div > .w2ui-panel").css("transition",".2s"),query(this.box).find("#layout_"+this.name+"_panel_"+e).css({opacity:"0"}),setTimeout(()=>{this.resize()},1),setTimeout(()=>{query(this.box).find(":scope > div > .w2ui-panel").css("transition","0s"),query(this.box).removeClass("animating"),i.finish(),this.resize()},300)),!0)}toggle(e,t){var i=this.get(e);return null!=i&&(i.hidden?this.show(e,t):this.hide(e,t))}set(e,t){var i=this.get(e,!0);return null!=i&&(w2utils.extend(this.panels[i],t),null==t.html&&null==t.resizable||this.refresh(e),this.resize(),!0)}get(t,i){for(let e=0;e<this.panels.length;e++)if(this.panels[e].type==t)return!0===i?e:this.panels[e];return null}el(e){e=query(this.box).find("#layout_"+this.name+"_panel_"+e+"> .w2ui-panel-content");return 1!=e.length?null:e[0]}hideToolbar(e){var t=this.get(e);t&&(t.show.toolbar=!1,query(this.box).find("#layout_"+this.name+"_panel_"+e+"> .w2ui-panel-toolbar").hide(),this.resize())}showToolbar(e){var t=this.get(e);t&&(t.show.toolbar=!0,query(this.box).find("#layout_"+this.name+"_panel_"+e+"> .w2ui-panel-toolbar").show(),this.resize())}toggleToolbar(e){var t=this.get(e);t&&(t.show.toolbar?this.hideToolbar(e):this.showToolbar(e))}assignToolbar(e,t){"string"==typeof t&&null!=w2ui[t]&&(t=w2ui[t]);var i=this.get(e),s=(i.toolbar=t,query(this.box).find(e+"> .w2ui-panel-toolbar"));null!=i.toolbar?(0===s.find("[name="+i.toolbar.name+"]").length?i.toolbar.render(s.get(0)):null!=i.toolbar&&i.toolbar.refresh(),(t.owner=this).showToolbar(e),this.refresh(e)):(s.html(""),this.hideToolbar(e))}hideTabs(e){var t=this.get(e);t&&(t.show.tabs=!1,query(this.box).find("#layout_"+this.name+"_panel_"+e+"> .w2ui-panel-tabs").hide(),this.resize())}showTabs(e){var t=this.get(e);t&&(t.show.tabs=!0,query(this.box).find("#layout_"+this.name+"_panel_"+e+"> .w2ui-panel-tabs").show(),this.resize())}toggleTabs(e){var t=this.get(e);t&&(t.show.tabs?this.hideTabs(e):this.showTabs(e))}render(e){var t=Date.now();let o=this;"string"==typeof e&&(e=query(e).get(0));var i=this.trigger("render",{target:this.name,box:e??this.box});if(!0!==i.isCancelled){if(null!=e&&(0<query(this.box).find("#layout_"+this.name+"_panel_main").length&&query(this.box).removeAttr("name").removeClass("w2ui-layout").html(""),this.box=e),!this.box)return!1;query(this.box).attr("name",this.name).addClass("w2ui-layout").html("<div></div>"),0<query(this.box).length&&(query(this.box)[0].style.cssText+=this.style);for(let e=0;e<w2panels.length;e++){var s='<div id="layout_'+this.name+"_panel_"+w2panels[e]+'" class="w2ui-panel"> <div class="w2ui-panel-title"></div> <div class="w2ui-panel-tabs"></div> <div class="w2ui-panel-toolbar"></div> <div class="w2ui-panel-content"></div></div><div id="layout_'+this.name+"_resizer_"+w2panels[e]+'" class="w2ui-resizer"></div>';query(this.box).find(":scope > div").append(s)}return query(this.box).find(":scope > div").append('<div id="layout_'+this.name+'_panel_css" style="position: absolute; top: 10000px;"></div>'),this.refresh(),this.last.observeResize=new ResizeObserver(()=>{this.resize()}),this.last.observeResize.observe(this.box),i.finish(),setTimeout(()=>{o.last.events={resizeStart:l,mouseMove:n,mouseUp:r},this.resize()},0),Date.now()-t}function l(e,t){o.box&&(t=t||window.event,query(document).off("mousemove",o.last.events.mouseMove).on("mousemove",o.last.events.mouseMove),query(document).off("mouseup",o.last.events.mouseUp).on("mouseup",o.last.events.mouseUp),o.last.resize={type:e,x:t.screenX,y:t.screenY,diff_x:0,diff_y:0,value:0},w2panels.forEach(e=>{var t=query(o.el(e)).find(".w2ui-lock");0<t.length?t.data("locked","yes"):o.lock(e,{opacity:0})}),t=query(o.box).find("#layout_"+o.name+"_resizer_"+e).get(0),"left"!=e&&"right"!=e||(o.last.resize.value=parseInt(t.style.left)),"top"!=e&&"preview"!=e&&"bottom"!=e||(o.last.resize.value=parseInt(t.style.top)))}function r(i){if(o.box&&(i=i||window.event,query(document).off("mousemove",o.last.events.mouseMove),query(document).off("mouseup",o.last.events.mouseUp),null!=o.last.resize)){if(w2panels.forEach(e=>{var t=query(o.el(e)).find(".w2ui-lock");"yes"==t.data("locked")?t.removeData("locked"):o.unlock(e)}),0!==o.last.diff_x||0!==o.last.resize.diff_y){var s=o.get("top"),l=o.get("bottom"),r=o.get(o.last.resize.type),i=w2utils.getSize(query(o.box),"width"),n=w2utils.getSize(query(o.box),"height"),a=String(r.size);let e,t;switch(o.last.resize.type){case"top":e=parseInt(r.sizeCalculated)+o.last.resize.diff_y,t=0;break;case"bottom":e=parseInt(r.sizeCalculated)-o.last.resize.diff_y,t=0;break;case"preview":e=parseInt(r.sizeCalculated)-o.last.resize.diff_y,t=(s&&!s.hidden?s.sizeCalculated:0)+(l&&!l.hidden?l.sizeCalculated:0);break;case"left":e=parseInt(r.sizeCalculated)+o.last.resize.diff_x,t=0;break;case"right":e=parseInt(r.sizeCalculated)-o.last.resize.diff_x,t=0}"%"==a.substr(a.length-1)?r.size=Math.floor(100*e/("left"==r.type||"right"==r.type?i:n-t)*100)/100+"%":"-"==String(r.size).substr(0,1)?r.size=parseInt(r.size)-r.sizeCalculated+e:r.size=e,o.resize()}query(o.box).find("#layout_"+o.name+"_resizer_"+o.last.resize.type).removeClass("active"),delete o.last.resize}}function n(i){if(o.box&&(i=i||window.event,null!=o.last.resize)){var s=o.get(o.last.resize.type),l=o.last.resize,r=o.trigger("resizing",{target:o.name,object:s,originalEvent:i,panel:l?l.type:"all",diff_x:l?l.diff_x:0,diff_y:l?l.diff_y:0});if(!0!==r.isCancelled){var n=query(o.box).find("#layout_"+o.name+"_resizer_"+l.type);let e=i.screenX-l.x,t=i.screenY-l.y;var a=o.get("main");switch(n.hasClass("active")||n.addClass("active"),l.type){case"left":s.minSize-e>s.width&&(e=s.minSize-s.width),s.maxSize&&s.width+e>s.maxSize&&(e=s.maxSize-s.width),a.minSize+e>a.width&&(e=a.width-a.minSize);break;case"right":s.minSize+e>s.width&&(e=s.width-s.minSize),s.maxSize&&s.width-e>s.maxSize&&(e=s.width-s.maxSize),a.minSize-e>a.width&&(e=a.minSize-a.width);break;case"top":s.minSize-t>s.height&&(t=s.minSize-s.height),s.maxSize&&s.height+t>s.maxSize&&(t=s.maxSize-s.height),a.minSize+t>a.height&&(t=a.height-a.minSize);break;case"preview":case"bottom":s.minSize+t>s.height&&(t=s.height-s.minSize),s.maxSize&&s.height-t>s.maxSize&&(t=s.height-s.maxSize),a.minSize-t>a.height&&(t=a.minSize-a.height)}switch(l.diff_x=e,l.diff_y=t,l.type){case"top":case"preview":case"bottom":(l.diff_x=0)<n.length&&(n[0].style.top=l.value+l.diff_y+"px");break;case"left":case"right":(l.diff_y=0)<n.length&&(n[0].style.left=l.value+l.diff_x+"px")}r.finish()}}}}refresh(s){let l=this;null==s&&(s=null);var e=Date.now(),t=l.trigger("refresh",{target:null!=s?s:l.name,object:l.get(s)});if(!0!==t.isCancelled){if("string"==typeof s){let e=l.get(s);if(null==e)return;let t="#layout_"+l.name+"_panel_"+e.type;s="#layout_"+l.name+"_resizer_"+e.type;query(l.box).find(t).css({display:e.hidden?"none":"block"}),e.resizable?query(l.box).find(s).show():query(l.box).find(s).hide(),"object"==typeof e.html&&"function"==typeof e.html.render?(e.html.box=query(l.box).find(t+"> .w2ui-panel-content")[0],setTimeout(()=>{0<query(l.box).find(t+"> .w2ui-panel-content").length&&(query(l.box).find(t+"> .w2ui-panel-content").removeClass().removeAttr("name").addClass("w2ui-panel-content").css("overflow",e.overflow)[0].style.cssText+=";"+e.style),e.html&&"function"==typeof e.html.render&&e.html.render()},1)):0<query(l.box).find(t+"> .w2ui-panel-content").length&&(query(l.box).find(t+"> .w2ui-panel-content").removeClass().removeAttr("name").addClass("w2ui-panel-content").html(e.html).css("overflow",e.overflow)[0].style.cssText+=";"+e.style);let i=query(l.box).find(t+"> .w2ui-panel-tabs");e.show.tabs?0===i.find("[name="+e.tabs.name+"]").length&&null!=e.tabs?e.tabs.render(i.get(0)):e.tabs.refresh():i.html("").removeClass("w2ui-tabs").hide(),i=query(l.box).find(t+"> .w2ui-panel-toolbar"),e.show.toolbar?0===i.find("[name="+e.toolbar.name+"]").length&&null!=e.toolbar?e.toolbar.render(i.get(0)):e.toolbar.refresh():i.html("").removeClass("w2ui-toolbar").hide(),i=query(l.box).find(t+"> .w2ui-panel-title"),e.title?i.html(e.title).show():i.html("").hide()}else{if(0===query(l.box).find("#layout_"+l.name+"_panel_main").length)return void l.render();l.resize();for(let e=0;e<this.panels.length;e++)l.refresh(this.panels[e].type)}return t.finish(),Date.now()-e}}resize(){if(!this.box)return!1;var r=Date.now();let n=this.last.resize;var a=this.trigger("resize",{target:this.name,panel:n?n.type:"all",diff_x:n?n.diff_x:0,diff_y:n?n.diff_y:0});if(!0!==a.isCancelled){this.padding<0&&(this.padding=0);var o=w2utils.getSize(query(this.box),"width"),h=w2utils.getSize(query(this.box),"height");let i=this;var d=this.get("main"),u=this.get("preview"),c=this.get("left"),p=this.get("right"),f=this.get("top"),m=this.get("bottom"),g=null!=u&&!0!==u.hidden,y=null!=c&&!0!==c.hidden,w=null!=p&&!0!==p.hidden,b=null!=f&&!0!==f.hidden,v=null!=m&&!0!==m.hidden;let e,t,s,l;for(let e=0;e<w2panels.length;e++)if("main"!==w2panels[e]&&(n=this.get(w2panels[e]))){var x=String(n.size||0);if("%"==x.substr(x.length-1)){let e=h;"preview"==n.type&&(e=e-(f&&!f.hidden?f.sizeCalculated:0)-(m&&!m.hidden?m.sizeCalculated:0)),n.sizeCalculated=parseInt(("left"==n.type||"right"==n.type?o:e)*parseFloat(n.size)/100)}else n.sizeCalculated=parseInt(n.size);n.sizeCalculated=Math.max(n.sizeCalculated,parseInt(n.minSize))}"-"==String(p.size).substr(0,1)&&(y&&"-"==String(c.size).substr(0,1)?console.log("ERROR: you cannot have both left panel.size and right panel.size be negative."):p.sizeCalculated=o-(y?c.sizeCalculated:0)+parseInt(p.size)),"-"==String(c.size).substr(0,1)&&(w&&"-"==String(p.size).substr(0,1)?console.log("ERROR: you cannot have both left panel.size and right panel.size be negative."):c.sizeCalculated=o-(w?p.sizeCalculated:0)+parseInt(c.size)),null!=f&&!0!==f.hidden?(e=0,t=0,s=o,l=f.sizeCalculated,query(this.box).find("#layout_"+this.name+"_panel_top").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px"}),f.width=s,f.height=l,f.resizable&&(t=f.sizeCalculated-(0===this.padding?this.resizer:0),l=this.resizer>this.padding?this.resizer:this.padding,query(this.box).find("#layout_"+this.name+"_resizer_top").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px",cursor:"ns-resize"}).off("mousedown").on("mousedown",function(e){e.preventDefault();var t=i.trigger("resizerClick",{target:"top",originalEvent:e});if(!0!==t.isCancelled)return w2ui[i.name].last.events.resizeStart("top",e),t.finish(),!1}))):(query(this.box).find("#layout_"+this.name+"_panel_top").hide(),query(this.box).find("#layout_"+this.name+"_resizer_top").hide()),null!=c&&!0!==c.hidden?(e=0,t=0+(b?f.sizeCalculated+this.padding:0),s=c.sizeCalculated,l=h-(b?f.sizeCalculated+this.padding:0)-(v?m.sizeCalculated+this.padding:0),query(this.box).find("#layout_"+this.name+"_panel_left").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px"}),c.width=s,c.height=l,c.resizable&&(e=c.sizeCalculated-(0===this.padding?this.resizer:0),s=this.resizer>this.padding?this.resizer:this.padding,query(this.box).find("#layout_"+this.name+"_resizer_left").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px",cursor:"ew-resize"}).off("mousedown").on("mousedown",function(e){e.preventDefault();var t=i.trigger("resizerClick",{target:"left",originalEvent:e});if(!0!==t.isCancelled)return w2ui[i.name].last.events.resizeStart("left",e),t.finish(),!1}))):(query(this.box).find("#layout_"+this.name+"_panel_left").hide(),query(this.box).find("#layout_"+this.name+"_resizer_left").hide()),null!=p&&!0!==p.hidden?(e=o-p.sizeCalculated,t=0+(b?f.sizeCalculated+this.padding:0),s=p.sizeCalculated,l=h-(b?f.sizeCalculated+this.padding:0)-(v?m.sizeCalculated+this.padding:0),query(this.box).find("#layout_"+this.name+"_panel_right").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px"}),p.width=s,p.height=l,p.resizable&&(e-=this.padding,s=this.resizer>this.padding?this.resizer:this.padding,query(this.box).find("#layout_"+this.name+"_resizer_right").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px",cursor:"ew-resize"}).off("mousedown").on("mousedown",function(e){e.preventDefault();var t=i.trigger("resizerClick",{target:"right",originalEvent:e});if(!0!==t.isCancelled)return w2ui[i.name].last.events.resizeStart("right",e),t.finish(),!1}))):(query(this.box).find("#layout_"+this.name+"_panel_right").hide(),query(this.box).find("#layout_"+this.name+"_resizer_right").hide()),null!=m&&!0!==m.hidden?(e=0,t=h-m.sizeCalculated,s=o,l=m.sizeCalculated,query(this.box).find("#layout_"+this.name+"_panel_bottom").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px"}),m.width=s,m.height=l,m.resizable&&(t-=0===this.padding?0:this.padding,l=this.resizer>this.padding?this.resizer:this.padding,query(this.box).find("#layout_"+this.name+"_resizer_bottom").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px",cursor:"ns-resize"}).off("mousedown").on("mousedown",function(e){e.preventDefault();var t=i.trigger("resizerClick",{target:"bottom",originalEvent:e});if(!0!==t.isCancelled)return w2ui[i.name].last.events.resizeStart("bottom",e),t.finish(),!1}))):(query(this.box).find("#layout_"+this.name+"_panel_bottom").hide(),query(this.box).find("#layout_"+this.name+"_resizer_bottom").hide()),e=0+(y?c.sizeCalculated+this.padding:0),t=0+(b?f.sizeCalculated+this.padding:0),s=o-(y?c.sizeCalculated+this.padding:0)-(w?p.sizeCalculated+this.padding:0),l=h-(b?f.sizeCalculated+this.padding:0)-(v?m.sizeCalculated+this.padding:0)-(g?u.sizeCalculated+this.padding:0),query(this.box).find("#layout_"+this.name+"_panel_main").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px"}),d.width=s,d.height=l,null!=u&&!0!==u.hidden?(e=0+(y?c.sizeCalculated+this.padding:0),t=h-(v?m.sizeCalculated+this.padding:0)-u.sizeCalculated,s=o-(y?c.sizeCalculated+this.padding:0)-(w?p.sizeCalculated+this.padding:0),l=u.sizeCalculated,query(this.box).find("#layout_"+this.name+"_panel_preview").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px"}),u.width=s,u.height=l,u.resizable&&(t-=0===this.padding?0:this.padding,l=this.resizer>this.padding?this.resizer:this.padding,query(this.box).find("#layout_"+this.name+"_resizer_preview").css({display:"block",left:e+"px",top:t+"px",width:s+"px",height:l+"px",cursor:"ns-resize"}).off("mousedown").on("mousedown",function(e){e.preventDefault();var t=i.trigger("resizerClick",{target:"preview",originalEvent:e});if(!0!==t.isCancelled)return w2ui[i.name].last.events.resizeStart("preview",e),t.finish(),!1}))):(query(this.box).find("#layout_"+this.name+"_panel_preview").hide(),query(this.box).find("#layout_"+this.name+"_resizer_preview").hide());for(let t=0;t<w2panels.length;t++){var _,q=this.get(w2panels[t]),C="#layout_"+this.name+"_panel_"+w2panels[t]+" > .w2ui-panel-";let e=0;q&&(q.title&&(_=query(this.box).find(C+"title").css({top:e+"px",display:"block"}),e+=w2utils.getSize(_,"height")),q.show.tabs&&(_=query(this.box).find(C+"tabs").css({top:e+"px",display:"block"}),e+=w2utils.getSize(_,"height")),q.show.toolbar)&&(q=query(this.box).find(C+"toolbar").css({top:e+"px",display:"block"}),e+=w2utils.getSize(q,"height")),query(this.box).find(C+"content").css({display:"block"}).css({top:e+"px"})}return a.finish(),Date.now()-r}}destroy(){var e=this.trigger("destroy",{target:this.name});if(!0!==e.isCancelled)return null!=w2ui[this.name]&&(0<query(this.box).find("#layout_"+this.name+"_panel_main").length&&query(this.box).removeAttr("name").removeClass("w2ui-layout").html(""),this.last.observeResize?.disconnect(),delete w2ui[this.name],e.finish(),this.last.events&&this.last.events.resize&&query(window).off("resize",this.last.events.resize),!0)}lock(e,t,i){var s;-1==w2panels.indexOf(e)?console.log("ERROR: First parameter needs to be the a valid panel name."):((s=Array.from(arguments))[0]="#layout_"+this.name+"_panel_"+e,w2utils.lock(...s))}unlock(e,t){-1==w2panels.indexOf(e)?console.log("ERROR: First parameter needs to be the a valid panel name."):(e="#layout_"+this.name+"_panel_"+e,w2utils.unlock(e,t))}}class w2grid extends w2base{constructor(e){if(super(e.name),this.name=null,this.box=null,this.columns=[],this.columnGroups=[],this.records=[],this.summary=[],this.searches=[],this.toolbar={},this.ranges=[],this.contextMenu=[],this.searchMap={},this.searchData=[],this.sortMap={},this.sortData=[],this.savedSearches=[],this.defaultSearches=[],this.total=0,this.recid=null,this.last={field:"",label:"",logic:"AND",search:"",searchIds:[],selection:{indexes:[],columns:{}},saved_sel:null,multi:!1,scrollTop:0,scrollLeft:0,colStart:0,colEnd:0,fetch:{action:"",offset:null,start:0,response:0,options:null,controller:null,loaded:!1,hasMore:!1},pull_more:!1,pull_refresh:!0,range_start:null,range_end:null,sel_ind:null,sel_col:null,sel_type:null,sel_recid:null,idCache:{},move:null,cancelClick:null,inEditMode:!1,_edit:null,kbd_timer:null,marker_timer:null,click_time:null,click_recid:null,bubbleEl:null,colResizing:!1,tmp:null,copy_event:null,userSelect:"",columnDrag:!1,state:null,show_extra:0,toolbar_height:0},this.header="",this.url="",this.limit=100,this.offset=0,this.postData={},this.routeData={},this.httpHeaders={},this.show={header:!1,toolbar:!1,footer:!1,columnMenu:!0,columnHeaders:!0,lineNumbers:!1,expandColumn:!1,selectColumn:!1,emptyRecords:!0,toolbarReload:!0,toolbarColumns:!1,toolbarSearch:!0,toolbarAdd:!1,toolbarEdit:!1,toolbarDelete:!1,toolbarSave:!1,searchAll:!0,searchLogic:!0,searchHiddenMsg:!1,searchSave:!0,statusRange:!0,statusBuffered:!1,statusRecordID:!0,statusSelection:!0,statusResponse:!0,statusSort:!1,statusSearch:!1,recordTitles:!1,selectionBorder:!0,skipRecords:!0,saveRestoreState:!0},this.stateId=null,this.hasFocus=!1,this.autoLoad=!0,this.fixedBody=!0,this.recordHeight=32,this.lineNumberWidth=34,this.keyboard=!0,this.selectType="row",this.liveSearch=!1,this.multiSearch=!0,this.multiSelect=!0,this.multiSort=!0,this.reorderColumns=!1,this.reorderRows=!1,this.showExtraOnSearch=0,this.markSearch=!0,this.columnTooltip="top|bottom",this.disableCVS=!1,this.nestedFields=!0,this.vs_start=150,this.vs_extra=5,this.style="",this.tabIndex=null,this.dataType=null,this.parser=null,this.advanceOnEdit=!0,this.useLocalStorage=!0,this.colTemplate={text:"",field:"",size:null,min:20,max:null,gridMinWidth:null,sizeCorrected:null,sizeCalculated:null,sizeOriginal:null,sizeType:null,hidden:!1,sortable:!1,sortMode:null,searchable:!1,resizable:!0,hideable:!0,autoResize:null,attr:"",style:"",render:null,title:null,tooltip:null,editable:{},frozen:!1,info:null,clipboardCopy:!1},this.stateColProps={text:!1,field:!0,size:!0,min:!1,max:!1,gridMinWidth:!1,sizeCorrected:!1,sizeCalculated:!0,sizeOriginal:!0,sizeType:!0,hidden:!0,sortable:!1,sortMode:!0,searchable:!1,resizable:!1,hideable:!1,autoResize:!1,attr:!1,style:!1,render:!1,title:!1,tooltip:!1,editable:!1,frozen:!0,info:!1,clipboardCopy:!1},this.msgDelete="Are you sure you want to delete ${count} ${records}?",this.msgNotJSON="Returned data is not in valid JSON format.",this.msgHTTPError="HTTP error. See console for more details.",this.msgServerError="Server error",this.msgRefresh="Refreshing...",this.msgNeedReload="Your remote data source record count has changed, reloading from the first record.",this.msgEmpty="",this.buttons={reload:{type:"button",id:"w2ui-reload",icon:"w2ui-icon-reload",tooltip:"Reload data in the list"},columns:{type:"menu-check",id:"w2ui-column-on-off",icon:"w2ui-icon-columns",tooltip:"Show/hide columns",overlay:{align:"none"}},search:{type:"html",id:"w2ui-search",html:'<div class="w2ui-icon w2ui-icon-search w2ui-search-down w2ui-action" data-click="searchShowFields"></div>'},add:{type:"button",id:"w2ui-add",text:"Add New",tooltip:"Add new record",icon:"w2ui-icon-plus"},edit:{type:"button",id:"w2ui-edit",text:"Edit",tooltip:"Edit selected record",icon:"w2ui-icon-pencil",batch:1,disabled:!0},delete:{type:"button",id:"w2ui-delete",text:"Delete",tooltip:"Delete selected records",icon:"w2ui-icon-cross",batch:!0,disabled:!0},save:{type:"button",id:"w2ui-save",text:"Save",tooltip:"Save changed records",icon:"w2ui-icon-check"}},this.operators={text:["is","begins","contains","ends"],number:["=","between",">","<",">=","<="],date:["is",{oper:"less",text:"before"},{oper:"more",text:"since"},"between"],list:["is"],hex:["is","between"],color:["is","begins","contains","ends"],enum:["in","not in"]},this.defaultOperator={text:"begins",number:"=",date:"is",list:"is",enum:"in",hex:"begins",color:"begins"},this.operatorsMap={text:"text",int:"number",float:"number",money:"number",currency:"number",percent:"number",hex:"hex",alphanumeric:"text",color:"color",date:"date",time:"date",datetime:"date",list:"list",combo:"text",enum:"enum",file:"enum",select:"list",radio:"list",checkbox:"list",toggle:"list"},this.onAdd=null,this.onEdit=null,this.onRequest=null,this.onLoad=null,this.onDelete=null,this.onSave=null,this.onSelect=null,this.onClick=null,this.onDblClick=null,this.onContextMenu=null,this.onContextMenuClick=null,this.onColumnClick=null,this.onColumnDblClick=null,this.onColumnContextMenu=null,this.onColumnResize=null,this.onColumnAutoResize=null,this.onSort=null,this.onSearch=null,this.onSearchOpen=null,this.onChange=null,this.onRestore=null,this.onExpand=null,this.onCollapse=null,this.onError=null,this.onKeydown=null,this.onToolbar=null,this.onColumnOnOff=null,this.onCopy=null,this.onPaste=null,this.onSelectionExtend=null,this.onEditField=null,this.onRender=null,this.onRefresh=null,this.onReload=null,this.onResize=null,this.onDestroy=null,this.onStateSave=null,this.onStateRestore=null,this.onFocus=null,this.onBlur=null,this.onReorderRow=null,this.onSearchSave=null,this.onSearchRemove=null,this.onSearchSelect=null,this.onColumnSelect=null,this.onColumnDragStart=null,this.onColumnDragEnd=null,this.onResizerDblClick=null,this.onMouseEnter=null,this.onMouseLeave=null,w2utils.extend(this,e),Array.isArray(this.records)){let i=[];this.records.forEach((e,t)=>{null!=e[this.recid]&&(e.recid=e[this.recid]),null==e.recid&&console.log("ERROR: Cannot add records without recid. (obj: "+this.name+")"),!0===e.w2ui?.summary&&(this.summary.push(e),i.push(t))}),i.sort();for(let e=i.length-1;0<=e;e--)this.records.splice(i[e],1)}Array.isArray(this.columns)&&this.columns.forEach((i,e)=>{i=w2utils.extend({},this.colTemplate,i);e=(this.columns[e]=i).searchable;if(null!=e&&!1!==e&&null==this.getSearch(i.field))if(w2utils.isPlainObject(e))this.addSearch(w2utils.extend({field:i.field,label:i.text,type:"text"},e));else{let e=i.searchable,t="";!0===i.searchable&&(e="text",t='size="20"'),this.addSearch({field:i.field,label:i.text,type:e,attr:t})}}),Array.isArray(this.defaultSearches)&&this.defaultSearches.forEach((e,t)=>{e.id="default-"+t,e.icon??="w2ui-icon-search"});e=this.cache("searches");Array.isArray(e)&&e.forEach(e=>{this.savedSearches.push({id:e.id??"none",text:e.text??"none",icon:"w2ui-icon-search",remove:!0,logic:e.logic??"AND",data:e.data??[]})}),"string"==typeof this.box&&(this.box=query(this.box).get(0)),this.box&&this.render(this.box)}add(t,i){Array.isArray(t)||(t=[t]);let s=0;for(let e=0;e<t.length;e++){var l=t[e];null!=l[this.recid]&&(l.recid=l[this.recid]),null==l.recid?console.log("ERROR: Cannot add record without recid. (obj: "+this.name+")"):(!0===l.w2ui?.summary?i?this.summary.unshift(l):this.summary.push(l):i?this.records.unshift(l):this.records.push(l),s++)}return(this.url?.get??this.url)||(this.total=this.records.length,this.localSort(!1,!0),this.localSearch()),this.refresh(),s}find(s,e,t){var i,l=[];let r=!1;for(i in s=null==s?{}:s)-1!=String(i).indexOf(".")&&(r=!0);var n=t?this.last.range_start:0;let a=t?this.last.range_end+1:this.records.length;a>this.records.length&&(a=this.records.length);for(let i=n;i<a;i++){let t=!0;for(var o in s){let e=this.records[i][o];r&&-1!=String(o).indexOf(".")&&(e=this.parseField(this.records[i],o)),"not-null"==s[o]?null!=e&&""!==e||(t=!1):s[o]!=e&&(t=!1)}t&&!0!==e&&l.push(this.records[i].recid),t&&!0===e&&l.push(i)}return l}set(e,t,i){if("object"==typeof e&&null!==e&&(i=t,t=e,e=null),null==e){for(let e=0;e<this.records.length;e++)w2utils.extend(this.records[e],t);!0!==i&&this.refresh()}else{var s=this.get(e,!0);if(null==s)return!1;!this.records[s]||this.records[s].recid!=e?w2utils.extend(this.summary[s],t):w2utils.extend(this.records[s],t),!0!==i&&this.refreshRow(e,s)}return!0}get(i,s){if(Array.isArray(i)){var t=[];for(let e=0;e<i.length;e++){var l=this.get(i[e],s);null!==l&&t.push(l)}return t}{let t=this.last.idCache;t||(this.last.idCache=t={});var e=t[i];if("number"==typeof e){if(0<=e&&e<this.records.length&&this.records[e].recid==i)return!0===s?e:this.records[e];if(0<=(e=~e)&&e<this.summary.length&&this.summary[e].recid==i)return!0===s?e:this.summary[e];this.last.idCache=t={}}for(let e=0;e<this.records.length;e++)if(this.records[e].recid==i)return t[i]=e,!0===s?e:this.records[e];for(let e=0;e<this.summary.length;e++)if(this.summary[e].recid==i)return t[i]=~e,!0===s?e:this.summary[e];return null}}getFirst(e){if(0==this.records.length)return null;let t=this.records[0];var i=this.last.searchIds;return t=0<this.searchData.length?Array.isArray(i)&&0<i.length?this.records[i[e||0]]:null:t}remove(){let i=0;for(let t=0;t<arguments.length;t++){for(let e=this.records.length-1;0<=e;e--)this.records[e].recid==arguments[t]&&(this.records.splice(e,1),i++);for(let e=this.summary.length-1;0<=e;e--)this.summary[e].recid==arguments[t]&&(this.summary.splice(e,1),i++)}return(this.url?.get??this.url)||(this.localSort(!1,!0),this.localSearch()),this.refresh(),i}addColumn(e,s){let t=0;1==arguments.length?(s=e,e=this.columns.length):null==(e="string"==typeof e?this.getColumn(e,!0):e)&&(e=this.columns.length),Array.isArray(s)||(s=[s]);for(let i=0;i<s.length;i++){var l=w2utils.extend({},this.colTemplate,s[i]);if(this.columns.splice(e,0,l),s[i].searchable){let e=s[i].searchable,t="";!0===s[i].searchable&&(e="text",t='size="20"'),this.addSearch({field:s[i].field,label:s[i].text,type:e,attr:t})}e++,t++}return this.refresh(),t}removeColumn(){let i=0;for(let t=0;t<arguments.length;t++)for(let e=this.columns.length-1;0<=e;e--)this.columns[e].field==arguments[t]&&(this.columns[e].searchable&&this.removeSearch(arguments[t]),this.columns.splice(e,1),i++);return this.refresh(),i}getColumn(t,i){if(0===arguments.length){var s=[];for(let e=0;e<this.columns.length;e++)s.push(this.columns[e].field);return s}for(let e=0;e<this.columns.length;e++)if(this.columns[e].field==t)return!0===i?e:this.columns[e];return null}updateColumn(e,s){let l=0;return(e=Array.isArray(e)?e:[e]).forEach(e=>{this.columns.forEach(i=>{if(i.field==e){let t=w2utils.clone(s);Object.keys(t).forEach(e=>{"function"==typeof t[e]&&(t[e]=t[e](i)),i[e]!=t[e]&&l++}),w2utils.extend(i,t)}})}),0<l&&this.refresh(),l}toggleColumn(){return this.updateColumn(Array.from(arguments),{hidden(e){return!e.hidden}})}showColumn(){return this.updateColumn(Array.from(arguments),{hidden:!1})}hideColumn(){return this.updateColumn(Array.from(arguments),{hidden:!0})}addSearch(t,i){let s=0;1==arguments.length?(i=t,t=this.searches.length):null==(t="string"==typeof t?this.getSearch(t,!0):t)&&(t=this.searches.length),Array.isArray(i)||(i=[i]);for(let e=0;e<i.length;e++)this.searches.splice(t,0,i[e]),t++,s++;return this.searchClose(),s}removeSearch(){let i=0;for(let t=0;t<arguments.length;t++)for(let e=this.searches.length-1;0<=e;e--)this.searches[e].field==arguments[t]&&(this.searches.splice(e,1),i++);return this.searchClose(),i}getSearch(t,i){if(0===arguments.length){var s=[];for(let e=0;e<this.searches.length;e++)s.push(this.searches[e].field);return s}for(let e=0;e<this.searches.length;e++)if(this.searches[e].field==t)return!0===i?e:this.searches[e];return null}toggleSearch(){let i=0;for(let t=0;t<arguments.length;t++)for(let e=this.searches.length-1;0<=e;e--)this.searches[e].field==arguments[t]&&(this.searches[e].hidden=!this.searches[e].hidden,i++);return this.searchClose(),i}showSearch(){let i=0;for(let t=0;t<arguments.length;t++)for(let e=this.searches.length-1;0<=e;e--)this.searches[e].field==arguments[t]&&!1!==this.searches[e].hidden&&(this.searches[e].hidden=!1,i++);return this.searchClose(),i}hideSearch(){let i=0;for(let t=0;t<arguments.length;t++)for(let e=this.searches.length-1;0<=e;e--)this.searches[e].field==arguments[t]&&!0!==this.searches[e].hidden&&(this.searches[e].hidden=!0,i++);return this.searchClose(),i}getSearchData(t){for(let e=0;e<this.searchData.length;e++)if(this.searchData[e].field==t)return this.searchData[e];return null}localSort(t,i){let a=this;if(this.url?.get??this.url)console.log("ERROR: grid.localSort can only be used on local data source, grid.url should be empty.");else if(0!==Object.keys(this.sortData).length){let e=Date.now();this.selectionSave(),this.prepareData(),i||this.reset();for(let e=0;e<this.sortData.length;e++){var s=this.getColumn(this.sortData[e].field);if(!s)return;"string"==typeof s.render&&(-1!=["date","age"].indexOf(s.render.split(":")[0])&&(this.sortData[e].field_=s.field+"_"),-1!=["time"].indexOf(s.render.split(":")[0]))&&(this.sortData[e].field_=s.field+"_")}for(let e=0;e<a.records.length;e++){var l=a.records[e];null!=l.w2ui?.parent_recid&&(l.w2ui._path=n(l))}this.records.sort((e,t)=>{if(!(e.w2ui&&null!=e.w2ui.parent_recid||t.w2ui&&null!=t.w2ui.parent_recid))return o(e,t);var i=n(e),s=n(t);for(let e=0;e<Math.min(i.length,s.length);e++){var l=o(i[e],s[e]);if(0!==l)return l}return i.length>s.length?1:i.length<s.length?-1:(console.log("ERROR: two paths should not be equal."),0)});for(let e=0;e<a.records.length;e++){var r=a.records[e];null!=r.w2ui?.parent_recid&&(r.w2ui._path=null)}return this.selectionRestore(i),e=Date.now()-e,!0!==t&&this.show.statusSort&&setTimeout(()=>{this.status(w2utils.lang("Sorting took ${count} seconds",{count:e/1e3}))},10),e;function n(e){var t;return e.w2ui&&null!=e.w2ui.parent_recid?e.w2ui._path||((t=a.get(e.w2ui.parent_recid))?n(t).concat(e):(console.log("ERROR: no parent record: "+e.w2ui.parent_recid),[e])):[e]}function o(s,l){if(s===l)return 0;for(let i=0;i<a.sortData.length;i++){var r=a.sortData[i].field,n=a.sortData[i].field_||r;let e=s[n],t=l[n];-1!=String(r).indexOf(".")&&(e=a.parseField(s,n),t=a.parseField(l,n));n=a.getColumn(r),r=(n&&0<Object.keys(n.editable).length&&(w2utils.isPlainObject(e)&&e.text&&(e=e.text),w2utils.isPlainObject(t))&&t.text&&(t=t.text),h(e,t,i,a.sortData[i].direction,n.sortMode||"default"));if(0!==r)return r}return h(s.recid,l.recid,0,"asc")}function h(e,t,i,s,l){if(e===t)return 0;if((null==e||""===e)&&null!=t&&""!==t)return 1;if(null!=e&&""!==e&&(null==t||""===t))return-1;s="asc"===s.toLowerCase()?1:-1;if(typeof e!=typeof t)return typeof t<typeof e?s:-s;if(e.constructor.name!=t.constructor.name)return e.constructor.name>t.constructor.name?s:-s;e&&"object"==typeof e&&(e=e.valueOf()),t&&"object"==typeof t&&(t=t.valueOf());var r={}.toString;switch(e&&"object"==typeof e&&e.toString!=r&&(e=String(e)),t&&"object"==typeof t&&t.toString!=r&&(t=String(t)),"string"==typeof e&&(e=e.toLowerCase().trim()),"string"==typeof t&&(t=t.toLowerCase().trim()),l){case"natural":l=w2utils.naturalCompare;break;case"i18n":l=w2utils.i18nCompare}return"function"==typeof l?l(e,t)*s:t<e?s:e<t?-s:0}}}localSearch(t){let c=this;var i=this.url?.get??this.url;if(i)console.log("ERROR: grid.localSearch can only be used on local data source, grid.url should be empty.");else{let e=Date.now(),u={}.toString,l={};if(this.total=this.records.length,this.last.searchIds=[],this.prepareData(),0<this.searchData.length&&!i){for(let s=this.total=0;s<this.records.length;s++){var r=this.records[s];if(function i(l){let r=0,n,a,o,h;let d=!1;for(let e=0;e<c.searchData.length;e++){let i=c.searchData[e],s=c.getSearch(i.field);if(null!=i){null==s&&(s={field:i.field,type:i.type});let t=c.parseField(l,s.field);switch(n=null===t||void 0===t||"object"==typeof t&&t.toString==u?"":String(t).toLowerCase(),null!=i.value&&(Array.isArray(i.value)?(a=i.value[0],o=i.value[1]):a=String(i.value).toLowerCase()),i.operator){case"=":case"is":c.parseField(l,s.field)==i.value?r++:"date"==s.type?(h=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),n=w2utils.formatDate(h,"yyyy-mm-dd"),a=w2utils.formatDate(w2utils.isDate(a,w2utils.settings.dateFormat,!0),"yyyy-mm-dd"),n==a&&r++):"time"==s.type?(h=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),n=w2utils.formatTime(h,"hh24:mi"),a=w2utils.formatTime(a,"hh24:mi"),n==a&&r++):"datetime"==s.type&&(h=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),n=w2utils.formatDateTime(h,"yyyy-mm-dd|hh24:mm:ss"),a=w2utils.formatDateTime(w2utils.isDateTime(a,w2utils.settings.datetimeFormat,!0),"yyyy-mm-dd|hh24:mm:ss"),n==a)&&r++;break;case"between":-1!=["int","float","money","currency","percent"].indexOf(s.type)?parseFloat(c.parseField(l,s.field))>=parseFloat(a)&&parseFloat(c.parseField(l,s.field))<=parseFloat(o)&&r++:"date"==s.type?(h=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),n=w2utils.isDate(h,w2utils.settings.dateFormat,!0),a=w2utils.isDate(a,w2utils.settings.dateFormat,!0),null!=(o=w2utils.isDate(o,w2utils.settings.dateFormat,!0))&&(o=new Date(o.getTime()+864e5)),n>=a&&n<o&&r++):"time"==s.type?(n=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),a=w2utils.isTime(a,!0),o=w2utils.isTime(o,!0),a=(new Date).setHours(a.hours,a.minutes,a.seconds||0,0),o=(new Date).setHours(o.hours,o.minutes,o.seconds||0,0),n>=a&&n<o&&r++):"datetime"==s.type&&(n=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),a=w2utils.isDateTime(a,w2utils.settings.datetimeFormat,!0),o=(o=w2utils.isDateTime(o,w2utils.settings.datetimeFormat,!0))&&new Date(o.getTime()+864e5),n>=a)&&n<o&&r++;break;case"<=":d=!0;case"<":case"less":-1!=["int","float","money","currency","percent"].indexOf(s.type)?(n=parseFloat(c.parseField(l,s.field)),a=parseFloat(i.value),(n<a||d&&n===a)&&r++):"date"==s.type?(h=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),n=w2utils.isDate(h,w2utils.settings.dateFormat,!0),a=w2utils.isDate(a,w2utils.settings.dateFormat,!0),(n<a||d&&n===a)&&r++):"time"==s.type?(h=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),n=w2utils.formatTime(h,"hh24:mi"),a=w2utils.formatTime(a,"hh24:mi"),(n<a||d&&n===a)&&r++):"datetime"==s.type&&(h=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),n=w2utils.formatDateTime(h,"yyyy-mm-dd|hh24:mm:ss"),a=w2utils.formatDateTime(w2utils.isDateTime(a,w2utils.settings.datetimeFormat,!0),"yyyy-mm-dd|hh24:mm:ss"),n.length==a.length)&&(n<a||d&&n===a)&&r++;break;case">=":d=!0;case">":case"more":-1!=["int","float","money","currency","percent"].indexOf(s.type)?(n=parseFloat(c.parseField(l,s.field)),a=parseFloat(i.value),(n>a||d&&n===a)&&r++):"date"==s.type?(h=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),n=w2utils.isDate(h,w2utils.settings.dateFormat,!0),a=w2utils.isDate(a,w2utils.settings.dateFormat,!0),(n>a||d&&n===a)&&r++):"time"==s.type?(h=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),n=w2utils.formatTime(h,"hh24:mi"),a=w2utils.formatTime(a,"hh24:mi"),(n>a||d&&n===a)&&r++):"datetime"==s.type&&(h=c.parseField(l,s.field+"_")instanceof Date?c.parseField(l,s.field+"_"):c.parseField(l,s.field),n=w2utils.formatDateTime(h,"yyyy-mm-dd|hh24:mm:ss"),a=w2utils.formatDateTime(w2utils.isDateTime(a,w2utils.settings.datetimeFormat,!0),"yyyy-mm-dd|hh24:mm:ss"),n.length==a.length)&&(n>a||d&&n===a)&&r++;break;case"in":h=i.value,-1===(h=i.svalue?i.svalue:h).indexOf(w2utils.isFloat(t)?parseFloat(t):t)&&-1===h.indexOf(n)||r++;break;case"not in":h=i.value,-1===(h=i.svalue?i.svalue:h).indexOf(w2utils.isFloat(t)?parseFloat(t):t)&&-1===h.indexOf(n)&&r++;break;case"begins":case"begins with":0===n.indexOf(a)&&r++;break;case"contains":0<=n.indexOf(a)&&r++;break;case"null":null==c.parseField(l,s.field)&&r++;break;case"not null":null!=c.parseField(l,s.field)&&r++;break;case"ends":case"ends with":let e=n.lastIndexOf(a);-1!==e&&e==n.length-a.length&&r++}}}if("OR"==c.last.logic&&0!==r||"AND"==c.last.logic&&r==c.searchData.length)return!0;if(l.w2ui?.children&&!0!==l.w2ui?.expanded)for(let t=0;t<l.w2ui.children.length;t++){let e=l.w2ui.children[t];if(i(e))return!0}return!1}(r))if(r?.w2ui&&!function e(t){let i=c.get(t,!0);if(null==i||null==t||l[t]||c.last.searchIds.includes(i))return;l[t]=!0;let s=c.records[i];s?.w2ui&&e(s.w2ui.parent_recid);c.last.searchIds.push(i)}(r.w2ui.parent_recid),0<this.showExtraOnSearch){let t=this.showExtraOnSearch,i=this.showExtraOnSearch;if(s<t&&(t=s),s+i>this.records.length&&(i=this.records.length-s),0<t)for(let e=s-t;e<s;e++)this.last.searchIds.indexOf(e)<0&&this.last.searchIds.push(e);if(this.last.searchIds.indexOf(s)<0&&this.last.searchIds.push(s),0<i)for(let e=s+1;e<=s+i;e++)this.last.searchIds.indexOf(e)<0&&this.last.searchIds.push(e)}else this.last.searchIds.push(s)}this.total=this.last.searchIds.length}return e=Date.now()-e,!0!==t&&this.show.statusSearch&&setTimeout(()=>{this.status(w2utils.lang("Search took ${count} seconds",{count:e/1e3}))},10),e}}getRangeData(e,i){var s=this.get(e[0].recid,!0),l=this.get(e[1].recid,!0),r=e[0].column,n=e[1].column,a=[];if(r==n)for(let e=s;e<=l;e++){var t=this.records[e],o=t[this.columns[r].field]||null;a.push(!0!==i?o:{data:o,column:r,index:e,record:t})}else if(s==l){var h=this.records[s];for(let e=r;e<=n;e++){var d=h[this.columns[e].field]||null;a.push(!0!==i?d:{data:d,column:e,index:s,record:h})}}else for(let t=s;t<=l;t++){var u=this.records[t];a.push([]);for(let e=r;e<=n;e++){var c=u[this.columns[e].field];!0!==i?a[a.length-1].push(c):a[a.length-1].push({data:c,column:e,index:t,record:u})}}return a}addRange(s){let e=0,l,r;if("row"!=this.selectType){Array.isArray(s)||(s=[s]);for(let i=0;i<s.length;i++){if("object"!=typeof s[i]&&(s[i]={name:"selection"}),"selection"==s[i].name){if(!1===this.show.selectionBorder)continue;var n=this.getSelection();if(0===n.length){this.removeRange("selection");continue}l=n[0],r=n[n.length-1]}else l=s[i].range[0],r=s[i].range[1];if(l){n={name:s[i].name,range:[{recid:l.recid,column:l.column},{recid:r.recid,column:r.column}],style:s[i].style||""};let t=!1;for(let e=0;e<this.ranges.length;e++)if(this.ranges[e].name==s[i].name){t=e;break}!1!==t?this.ranges[t]=n:this.ranges.push(n),e++}}this.refreshRanges()}return e}removeRange(){let t=0;for(let e=0;e<arguments.length;e++){var i=arguments[e];query(this.box).find("#grid_"+this.name+"_"+i).remove(),query(this.box).find("#grid_"+this.name+"_f"+i).remove();for(let e=this.ranges.length-1;0<=e;e--)this.ranges[e].name==i&&(this.ranges.splice(e,1),t++)}return t}refreshRanges(){if(0!==this.ranges.length){let r=this,n;var e=Date.now(),o=query(this.box).find(`#grid_${this.name}_frecords`),h=query(this.box).find(`#grid_${this.name}_records`);for(let r=0;r<this.ranges.length;r++){var d=this.ranges[r],u=d.range[0],c=d.range[1];null==u.index&&(u.index=this.get(u.recid,!0)),null==c.index&&(c.index=this.get(c.recid,!0));let e=query(this.box).find("#grid_"+this.name+"_rec_"+w2utils.escapeId(u.recid)+' td[col="'+u.column+'"]'),t=query(this.box).find("#grid_"+this.name+"_rec_"+w2utils.escapeId(c.recid)+' td[col="'+c.column+'"]'),i=query(this.box).find("#grid_"+this.name+"_frec_"+w2utils.escapeId(u.recid)+' td[col="'+u.column+'"]'),s=query(this.box).find("#grid_"+this.name+"_frec_"+w2utils.escapeId(c.recid)+' td[col="'+c.column+'"]'),l=c.column;u.column<this.last.colStart&&c.column>this.last.colStart&&(e=query(this.box).find("#grid_"+this.name+"_rec_"+w2utils.escapeId(u.recid)+' td[col="start"]')),u.column<this.last.colEnd&&c.column>this.last.colEnd&&(t=query(this.box).find("#grid_"+this.name+"_rec_"+w2utils.escapeId(c.recid)+' td[col="end"]'),l='"end"');var p=parseInt(query(this.box).find("#grid_"+this.name+"_rec_top").next().attr("index")),f=parseInt(query(this.box).find("#grid_"+this.name+"_rec_bottom").prev().attr("index")),m=parseInt(query(this.box).find("#grid_"+this.name+"_frec_top").next().attr("index")),g=parseInt(query(this.box).find("#grid_"+this.name+"_frec_bottom").prev().attr("index"));0===e.length&&u.index<p&&c.index>p&&(e=query(this.box).find("#grid_"+this.name+"_rec_top").next().find('td[col="'+u.column+'"]')),0===t.length&&c.index>f&&u.index<f&&(t=query(this.box).find("#grid_"+this.name+"_rec_bottom").prev().find('td[col="'+l+'"]')),0===i.length&&u.index<m&&c.index>m&&(i=query(this.box).find("#grid_"+this.name+"_frec_top").next().find('td[col="'+u.column+'"]')),0===s.length&&c.index>g&&u.index<g&&(s=query(this.box).find("#grid_"+this.name+"_frec_bottom").prev().find('td[col="'+c.column+'"]'));var y,p=query(this.box).find("#grid_"+this.name+"_editable").find(".w2ui-input"),f=p.attr("recid"),m=p.attr("column");"selection"==d.name&&d.range[0].recid==f&&d.range[0].column==m||(n=query(this.box).find("#grid_"+this.name+"_f"+d.name),(0<i.length||0<s.length)&&(0===n.length?(o.append('<div id="grid_'+this.name+"_f"+d.name+'" class="w2ui-selection" style="'+d.style+'">'+("selection"==d.name?'<div id="grid_'+this.name+'_resizer" class="w2ui-selection-resizer"></div>':"")+"</div>"),n=query(this.box).find("#grid_"+this.name+"_f"+d.name)):(n.attr("style",d.style),n.find(".w2ui-selection-resizer").show()),0===s.length&&(0===(s=query(this.box).find("#grid_"+this.name+"_frec_"+w2utils.escapeId(c.recid)+" td:last-child")).length&&(s=query(this.box).find("#grid_"+this.name+"_frec_bottom td:first-child")),n.css("border-right","0px"),n.find(".w2ui-selection-resizer").hide()),null!=u.recid)&&null!=c.recid&&0<i.length&&0<s.length?(g=getComputedStyle(s[0]),p=i.prop("offsetTop")-i.prop("scrollTop"),f=i.prop("offsetLeft")+i.prop("scrollLeft"),m=s.prop("offsetTop")-s.prop("scrollTop"),y=s.prop("offsetLeft")+s.prop("scrollLeft"),n.show().css({top:(0<p?p:0)+"px",left:(0<f?f:0)+"px",width:y-f+parseFloat(g.width)+2+"px",height:m-p+parseFloat(g.height)+1+"px"})):n.hide(),n=query(this.box).find("#grid_"+this.name+"_"+d.name),(0<e.length||0<t.length)&&(0===n.length?(h.append('<div id="grid_'+this.name+"_"+d.name+'" class="w2ui-selection" style="'+d.style+'">'+("selection"==d.name?'<div id="grid_'+this.name+'_resizer" class="w2ui-selection-resizer"></div>':"")+"</div>"),n=query(this.box).find("#grid_"+this.name+"_"+d.name)):n.attr("style",d.style),0===e.length&&0===(e=query(this.box).find("#grid_"+this.name+"_rec_"+w2utils.escapeId(u.recid)+" td:first-child")).length&&(e=query(this.box).find("#grid_"+this.name+"_rec_top td:first-child")),0!==s.length&&n.css("border-left","0px"),null!=u.recid)&&null!=c.recid&&0<e.length&&0<t.length?(y=getComputedStyle(t[0]),f=e.prop("offsetTop")-e.prop("scrollTop"),m=e.prop("offsetLeft")+e.prop("scrollLeft"),p=t.prop("offsetTop")-t.prop("scrollTop"),g=t.prop("offsetLeft")+t.prop("scrollLeft"),n.show().css({top:(0<f?f:0)+"px",left:(0<m?m:0)+"px",width:g-m+parseFloat(y.width)+2+"px",height:p-f+parseFloat(y.height)+1+"px"})):n.hide())}query(this.box).find(".w2ui-selection-resizer").off(".resizer").on("mousedown.resizer",function(e){var t=r.getSelection();r.last.move={type:"expand",x:e.screenX,y:e.screenY,divX:0,divY:0,recid:t[0].recid,column:t[0].column,originalRange:[w2utils.clone(t[0]),w2utils.clone(t[t.length-1])],newRange:[w2utils.clone(t[0]),w2utils.clone(t[t.length-1])]},query("body").off(".w2ui-"+r.name).on("mousemove.w2ui-"+r.name,i).on("mouseup.w2ui-"+r.name,s),e.preventDefault()}).on("dblclick.resizer",e=>{e=this.trigger("resizerDblClick",{target:this.name,originalEvent:e});!0!==e.isCancelled&&e.finish()});let a={target:this.name,originalRange:null,newRange:null};return Date.now()-e;function i(s){var l=r.last.move;if(l&&"expand"==l.type){l.divX=s.screenX-l.x,l.divY=s.screenY-l.y;let e,t,i=s.target;"TD"!=i.tagName.toUpperCase()&&(i=query(i).closest("td")[0]),null!=(t=null!=query(i).attr("col")?parseInt(query(i).attr("col")):t)&&(i=query(i).closest("tr")[0],e=r.records[query(i).attr("index")].recid,l.newRange[1].recid!=e||l.newRange[1].column!=t)&&(s=w2utils.clone(l.newRange),l.newRange=[{recid:l.recid,column:l.column},{recid:e,column:t}],a.detail&&(a.detail.newRange=w2utils.clone(l.newRange),a.detail.originalRange=w2utils.clone(l.originalRange)),!0===(a=r.trigger("selectionExtend",a)).isCancelled?(l.newRange=s,a.detail.newRange=s):(r.removeRange("grid-selection-expand"),r.addRange({name:"grid-selection-expand",range:l.newRange,style:"background-color: rgba(100,100,100,0.1); border: 2px dotted rgba(100,100,100,0.5);"})))}}function s(e){r.removeRange("grid-selection-expand"),delete r.last.move,query("body").off(".w2ui-"+r.name),a.finish&&a.finish()}}}select(){if(0===arguments.length)return 0;let s=0;var l=this.last.selection;this.multiSelect||this.selectNone(!0);let t=Array.from(arguments);Array.isArray(t[0])&&(t=t[0]);var e={target:this.name},e=(1==t.length?(e.multiple=!1,w2utils.isPlainObject(t[0])?e.clicked={recid:t[0].recid,column:t[0].column}:e.recid=t[0]):(e.multiple=!0,e.clicked={recids:t}),this.trigger("select",e));if(!0===e.isCancelled)return 0;if("row"==this.selectType)for(let e=0;e<t.length;e++){var i="object"==typeof t[e]?t[e].recid:t[e],r=this.get(i,!0);if(null!=r){let e=null,t=null;(0!==this.searchData.length||r+1>=this.last.range_start&&r+1<=this.last.range_end)&&(e=query(this.box).find("#grid_"+this.name+"_frec_"+w2utils.escapeId(i)),t=query(this.box).find("#grid_"+this.name+"_rec_"+w2utils.escapeId(i))),"row"==this.selectType&&-1==l.indexes.indexOf(r)&&(l.indexes.push(r),e&&t&&(e.addClass("w2ui-selected").find(".w2ui-col-number").addClass("w2ui-row-selected"),t.addClass("w2ui-selected").find(".w2ui-col-number").addClass("w2ui-row-selected"),e.find(".w2ui-grid-select-check").prop("checked",!0)),s++)}}else{var n={};for(let e=0;e<t.length;e++){var a="object"==typeof t[e]?t[e].recid:t[e],o="object"==typeof t[e]?t[e].column:null;if(n[a]=n[a]||[],Array.isArray(o))n[a]=o;else if(w2utils.isInt(o))n[a].push(o);else for(let e=0;e<this.columns.length;e++)this.columns[e].hidden||n[a].push(parseInt(e))}var h,d=[];for(h in n){var u=this.get(h,!0);if(null!=u){let t=null,i=null;u+1>=this.last.range_start&&u+1<=this.last.range_end&&(t=query(this.box).find("#grid_"+this.name+"_rec_"+w2utils.escapeId(h)),i=query(this.box).find("#grid_"+this.name+"_frec_"+w2utils.escapeId(h)));var c=l.columns[u]||[];-1==l.indexes.indexOf(u)&&l.indexes.push(u);for(let e=0;e<n[h].length;e++)-1==c.indexOf(n[h][e])&&c.push(n[h][e]);c.sort((e,t)=>e-t);for(let e=0;e<n[h].length;e++){var p=n[h][e];-1==d.indexOf(p)&&d.push(p),t&&(t.find("#grid_"+this.name+"_data_"+u+"_"+p).addClass("w2ui-selected"),t.find(".w2ui-col-number").addClass("w2ui-row-selected"),t.find(".w2ui-grid-select-check").prop("checked",!0)),i&&(i.find("#grid_"+this.name+"_data_"+u+"_"+p).addClass("w2ui-selected"),i.find(".w2ui-col-number").addClass("w2ui-row-selected"),i.find(".w2ui-grid-select-check").prop("checked",!0)),s++}l.columns[u]=c}}for(let e=0;e<d.length;e++)query(this.box).find("#grid_"+this.name+"_column_"+d[e]+" .w2ui-col-header").addClass("w2ui-col-selected")}l.indexes.sort((e,t)=>e-t);var f=0<this.records.length&&l.indexes.length==this.records.length,m=0<l.indexes.length&&0!==this.searchData.length&&l.indexes.length==this.last.searchIds.length;return f||m?query(this.box).find("#grid_"+this.name+"_check_all").prop("checked",!0):query(this.box).find("#grid_"+this.name+"_check_all").prop("checked",!1),this.status(),this.addRange("selection"),this.updateToolbar(l,f),e.finish(),s}unselect(){let s=0;var l=this.last.selection;let t=Array.from(arguments);Array.isArray(t[0])&&(t=t[0]);var e={target:this.name},e=(1==t.length?(e.multiple=!1,w2utils.isPlainObject(t[0])?e.clicked={recid:t[0].recid,column:t[0].column}:e.clicked={recid:t[0]}):(e.multiple=!0,e.recids=t),this.trigger("select",e));if(!0===e.isCancelled)return 0;for(let e=0;e<t.length;e++){var r="object"==typeof t[e]?t[e].recid:t[e],n=this.get(r);if(null!=n){var n=this.get(n.recid,!0),a=query(this.box).find("#grid_"+this.name+"_frec_"+w2utils.escapeId(r)),o=query(this.box).find("#grid_"+this.name+"_rec_"+w2utils.escapeId(r));if("row"==this.selectType)-1!=l.indexes.indexOf(n)&&(l.indexes.splice(l.indexes.indexOf(n),1),a.removeClass("w2ui-selected w2ui-inactive").find(".w2ui-col-number").removeClass("w2ui-row-selected"),o.removeClass("w2ui-selected w2ui-inactive").find(".w2ui-col-number").removeClass("w2ui-row-selected"),0!=a.length&&(a[0].style.cssText="height: "+this.recordHeight+"px; "+a.attr("custom_style"),o[0].style.cssText="height: "+this.recordHeight+"px; "+o.attr("custom_style")),a.find(".w2ui-grid-select-check").prop("checked",!1),s++);else{var h=t[e].column;if(!w2utils.isInt(h)){var i=[];for(let e=0;e<this.columns.length;e++)this.columns[e].hidden||i.push({recid:r,column:e});return this.unselect(i)}o=l.columns[n];if(Array.isArray(o)&&-1!=o.indexOf(h)){o.splice(o.indexOf(h),1),query(this.box).find(`#grid_${this.name}_rec_${w2utils.escapeId(r)} > td[col="${h}"]`).removeClass("w2ui-selected w2ui-inactive"),query(this.box).find(`#grid_${this.name}_frec_${w2utils.escapeId(r)} > td[col="${h}"]`).removeClass("w2ui-selected w2ui-inactive");let t=!1,i=!1;var d=this.getSelection();for(let e=0;e<d.length;e++)d[e].column==h&&(t=!0),d[e].recid==r&&(i=!0);t||query(this.box).find(`.w2ui-grid-columns td[col="${h}"] .w2ui-col-header, .w2ui-grid-fcolumns td[col="${h}"] .w2ui-col-header`).removeClass("w2ui-col-selected"),i||query(this.box).find("#grid_"+this.name+"_frec_"+w2utils.escapeId(r)).find(".w2ui-col-number").removeClass("w2ui-row-selected"),s++,0===o.length&&(delete l.columns[n],l.indexes.splice(l.indexes.indexOf(n),1),a.find(".w2ui-grid-select-check").prop("checked",!1))}}}}var u=0<this.records.length&&l.indexes.length==this.records.length,c=0<l.indexes.length&&0!==this.searchData.length&&l.indexes.length==this.last.searchIds.length;return u||c?query(this.box).find("#grid_"+this.name+"_check_all").prop("checked",!0):query(this.box).find("#grid_"+this.name+"_check_all").prop("checked",!1),this.status(),this.addRange("selection"),this.updateToolbar(l,u),e.finish(),s}selectAll(){var e=Date.now();if(!1!==this.multiSelect){var s=this.url?.get??this.url;let i=w2utils.clone(this.last.selection);var l=[];for(let e=0;e<this.columns.length;e++)l.push(e);if(i.indexes=[],s||0===this.searchData.length){let t=this.records.length;0==this.searchData.length||s||(t=this.last.searchIds.length);for(let e=0;e<t;e++)i.indexes.push(e),"row"!=this.selectType&&(i.columns[e]=l.slice())}else for(let e=0;e<this.last.searchIds.length;e++)i.indexes.push(this.last.searchIds[e]),"row"!=this.selectType&&(i.columns[this.last.searchIds[e]]=l.slice());s=this.trigger("select",{target:this.name,multiple:!0,all:!0,clicked:i});if(!0!==s.isCancelled)return this.last.selection=i,"row"==this.selectType?(query(this.box).find(".w2ui-grid-records tr:not(.w2ui-empty-record)").addClass("w2ui-selected").find(".w2ui-col-number").addClass("w2ui-row-selected"),query(this.box).find(".w2ui-grid-frecords tr:not(.w2ui-empty-record)").addClass("w2ui-selected").find(".w2ui-col-number").addClass("w2ui-row-selected")):(query(this.box).find(".w2ui-grid-columns td .w2ui-col-header, .w2ui-grid-fcolumns td .w2ui-col-header").addClass("w2ui-col-selected"),query(this.box).find(".w2ui-grid-records tr .w2ui-col-number").addClass("w2ui-row-selected"),query(this.box).find(".w2ui-grid-records tr:not(.w2ui-empty-record)").find(".w2ui-grid-data:not(.w2ui-col-select)").addClass("w2ui-selected"),query(this.box).find(".w2ui-grid-frecords tr .w2ui-col-number").addClass("w2ui-row-selected"),query(this.box).find(".w2ui-grid-frecords tr:not(.w2ui-empty-record)").find(".w2ui-grid-data:not(.w2ui-col-select)").addClass("w2ui-selected")),query(this.box).find("input.w2ui-grid-select-check").prop("checked",!0),i=this.getSelection(!0),this.addRange("selection"),query(this.box).find("#grid_"+this.name+"_check_all").prop("checked",!0),this.status(),this.updateToolbar({indexes:i},!0),s.finish(),Date.now()-e}}selectNone(e){var t,i=Date.now();let s;if(e||!0!==(s=this.trigger("select",{target:this.name,clicked:[]})).isCancelled)return t=this.last.selection,"row"==this.selectType?(query(this.box).find(".w2ui-grid-records tr.w2ui-selected").removeClass("w2ui-selected w2ui-inactive").find(".w2ui-col-number").removeClass("w2ui-row-selected"),query(this.box).find(".w2ui-grid-frecords tr.w2ui-selected").removeClass("w2ui-selected w2ui-inactive").find(".w2ui-col-number").removeClass("w2ui-row-selected")):(query(this.box).find(".w2ui-grid-columns td .w2ui-col-header, .w2ui-grid-fcolumns td .w2ui-col-header").removeClass("w2ui-col-selected"),query(this.box).find(".w2ui-grid-records tr .w2ui-col-number").removeClass("w2ui-row-selected"),query(this.box).find(".w2ui-grid-frecords tr .w2ui-col-number").removeClass("w2ui-row-selected"),query(this.box).find(".w2ui-grid-data.w2ui-selected").removeClass("w2ui-selected w2ui-inactive")),query(this.box).find("input.w2ui-grid-select-check").prop("checked",!1),t.indexes=[],t.columns={},this.removeRange("selection"),query(this.box).find("#grid_"+this.name+"_check_all").prop("checked",!1),this.status(),this.updateToolbar(t,!1),e||s.finish(),Date.now()-i}updateToolbar(s){let l=this,r=s&&s.indexes?s.indexes.length:0;function i(t,i){if(null!=t.batch){let e=!1;!0===t.batch?0<r&&(e=!0):"number"==typeof t.batch?r===t.batch&&(e=!0):"function"==typeof t.batch&&(e=t.batch({cnt:r,sel:s})),e?l.toolbar.enable(i+t.id):l.toolbar.disable(i+t.id)}}this.toolbar.items.forEach(t=>{i(t,""),Array.isArray(t.items)&&t.items.forEach(e=>{i(e,t.id+":")})}),this.show.toolbarSave&&(0<this.getChanges().length?this.toolbar.enable("w2ui-save"):this.toolbar.disable("w2ui-save"))}getSelection(t){var i=[],s=this.last.selection;if("row"==this.selectType)for(let e=0;e<s.indexes.length;e++)this.records[s.indexes[e]]&&i.push(!0===t?s.indexes[e]:this.records[s.indexes[e]].recid);else for(let t=0;t<s.indexes.length;t++){var l=s.columns[s.indexes[t]];if(this.records[s.indexes[t]])for(let e=0;e<l.length;e++)i.push({recid:this.records[s.indexes[t]].recid,index:parseInt(s.indexes[t]),column:l[e]})}return i}search(t,s){var e=this.url?.get??this.url,r=[];let n=this.last.multi,i=this.last.logic,l=this.last.field,a=this.last.search,o=!1;var h=query(`#w2overlay-${this.name}-search-overlay`);for(let e=0;e<this.searches.length;e++)this.searches[e].hidden&&null!=this.searches[e].value&&(r.push({field:this.searches[e].field,operator:this.searches[e].operator||"is",type:this.searches[e].type,value:this.searches[e].value||""}),o=!0);if(0===arguments.length&&0===h.length&&(s=this.multiSearch?(t=this.searchData,this.last.logic):(t=this.last.field,this.last.search)),0===arguments.length&&0!==h.length){this.focus(),i=h.find(`#grid_${this.name}_logic`).val(),a="";for(let l=0;l<this.searches.length;l++){var d=this.searches[l],u=h.find("#grid_"+this.name+"_operator_"+l).val(),c=h.find("#grid_"+this.name+"_field_"+l),p=h.find("#grid_"+this.name+"_field2_"+l);let t=c.val(),e=p.val(),i=null,s=null;if(-1!=["int","float","money","currency","percent"].indexOf(d.type)&&(f=c[0]._w2field,p=p[0]._w2field,f&&(t=f.clean(t)),p)&&(e=p.clean(e)),-1!=["list","enum"].indexOf(d.type)||-1!=["in","not in"].indexOf(u))if(t=c[0]._w2field.selected||{},Array.isArray(t)){i=[];for(let e=0;e<t.length;e++)i.push(w2utils.isFloat(t[e].id)?parseFloat(t[e].id):String(t[e].id).toLowerCase()),delete t[e].hidden;0===Object.keys(t).length&&(t="")}else s=t.text||"",t=t.id||"";if(""!==t&&null!=t||null!=e&&""!==e){var f={field:d.field,type:d.type,operator:u};"between"==u?w2utils.extend(f,{value:[t,e]}):"in"==u&&"string"==typeof t||"not in"==u&&"string"==typeof t?w2utils.extend(f,{value:t.split(",")}):w2utils.extend(f,{value:t}),i&&w2utils.extend(f,{svalue:i}),s&&w2utils.extend(f,{text:s});try{"date"==d.type&&"between"==u&&(f.value[0]=t,f.value[1]=e),"date"==d.type&&"is"==u&&(f.value=t)}catch(e){}r.push(f),n=!0}}}if("string"==typeof t&&(1==arguments.length&&(s=t,t="all"),l=t,a=s,n=!1,i=o?"AND":"OR",null!=s))if("all"==t.toLowerCase())if(0<this.searches.length)for(let e=0;e<this.searches.length;e++){var m,g=this.searches[e];if(("text"==g.type||"alphanumeric"==g.type&&w2utils.isAlphaNumeric(s)||"int"==g.type&&w2utils.isInt(s)||"float"==g.type&&w2utils.isFloat(s)||"percent"==g.type&&w2utils.isFloat(s)||("hex"==g.type||"color"==g.type)&&w2utils.isHex(s)||"currency"==g.type&&w2utils.isMoney(s)||"money"==g.type&&w2utils.isMoney(s)||"date"==g.type&&w2utils.isDate(s)||"time"==g.type&&w2utils.isTime(s)||"datetime"==g.type&&w2utils.isDateTime(s)||"datetime"==g.type&&w2utils.isDate(s)||"enum"==g.type&&w2utils.isAlphaNumeric(s)||"list"==g.type&&w2utils.isAlphaNumeric(s))&&(m=this.defaultOperator[this.operatorsMap[g.type]],m={field:g.field,type:g.type,operator:null!=g.operator?g.operator:m,value:s},""!=String(s).trim())&&r.push(m),-1!=["int","float","money","currency","percent"].indexOf(g.type)&&2==String(s).trim().split("-").length&&(m=String(s).trim().split("-"),y={field:g.field,type:g.type,operator:null!=g.operator?g.operator:"between",value:[m[0],m[1]]},r.push(y)),-1!=["list","enum"].indexOf(g.type)){var y,w=[];null==g.options&&(g.options={}),Array.isArray(g.options.items)||(g.options.items=[]);for(let e=0;e<g.options.items;e++){var b=g.options.items[e];try{var v=new RegExp(s,"i");v.test(b)&&w.push(e),b.text&&v.test(b.text)&&w.push(b.id)}catch(e){}}0<w.length&&(y={field:g.field,type:g.type,operator:null!=g.operator?g.operator:"in",value:w},r.push(y))}}else for(let e=0;e<this.columns.length;e++){var x={field:this.columns[e].field,type:"text",operator:this.defaultOperator.text,value:s};r.push(x)}else{var _=h.find("#grid_"+this.name+"_search_all");let i=this.getSearch(t);if((i=null==i?{field:t,type:"text"}:i).field==t&&(this.last.label=i.label),""!==s){let e=this.defaultOperator[this.operatorsMap[i.type]],t=s;if(-1!=["date","time","datetime"].indexOf(i.type)&&(e="is"),-1!=["list","enum"].indexOf(i.type)&&(e="is",_=_._w2field.get(),t=_&&0<Object.keys(_).length?_.id:""),"int"==i.type&&""!==s)if(e="is",-1!=String(s).indexOf("-")&&2==(_=s.split("-")).length&&(e="between",t=[parseInt(_[0]),parseInt(_[1])]),-1!=String(s).indexOf(",")){var q=s.split(",");e="in",t=[];for(let e=0;e<q.length;e++)t.push(q[e])}null!=i.operator&&(e=i.operator);_={field:i.field,type:i.type,operator:e,value:t};r.push(_)}}if(Array.isArray(t)){let e="AND";"string"==typeof s&&"OR"!=(e=s.toUpperCase())&&"AND"!=e&&(e="AND"),a="",n=!0,i=e;for(let e=0;e<t.length;e++){var C=t[e];"number"==typeof C.value&&null==C.operator&&(C.operator=this.defaultOperator.number),"string"==typeof C.value&&null==C.operator&&(C.operator=this.defaultOperator.text),Array.isArray(C.value)&&null==C.operator&&(C.operator=this.defaultOperator.enum),w2utils.isDate(C.value)&&null==C.operator&&(C.operator=this.defaultOperator.date),r.push(C)}}_=this.trigger("search",{target:this.name,multi:0===arguments.length,searchField:t||"multi",searchValue:t?s:"multi",searchData:r,searchLogic:i});!0!==_.isCancelled&&(this.searchData=_.detail.searchData,this.last.field=l,this.last.search=a,this.last.multi=n,this.last.logic=_.detail.searchLogic,this.last.scrollTop=0,this.last.scrollLeft=0,this.last.selection.indexes=[],this.last.selection.columns={},this.searchClose(),e?(this.last.fetch.offset=0,this.reload()):(this.localSearch(),this.refresh()),_.finish())}searchOpen(){if(this.box&&0!==this.searches.length){let s=this.trigger("searchOpen",{target:this.name});if(!0!==s.isCancelled){let t=query(this.toolbar.box).find(".w2ui-grid-search-input .w2ui-search-drop");t.addClass("checked"),w2tooltip.show({name:this.name+"-search-overlay",anchor:query(this.box).find("#grid_"+this.name+"_search_all").get(0),position:"bottom|top",html:this.getSearchesHTML(),align:"left",arrowSize:12,class:"w2ui-grid-search-advanced",hideOn:["doc-click"]}).then(e=>{this.initSearches(),this.last.search_opened=!0;let t=query(`#w2overlay-${this.name}-search-overlay`);t.data("gridName",this.name).off(".grid-search").on("click.grid-search",()=>{t.find("input, select").each(e=>{e=query(e).data("tooltipName");e&&e.forEach(e=>{w2tooltip.hide(e)})})}),w2utils.bindEvents(t.find("select, input, button"),this);var i=query(`#w2overlay-${this.name}-search-overlay *[rel=search]`);0<i.length&&i[0].focus(),s.finish()}).hide(e=>{t.removeClass("checked"),this.last.search_opened=!1})}}}searchClose(){w2tooltip.hide(this.name+"-search-overlay")}searchFieldTooltip(e,t,i){var e=this.searches[e],s=this.searchData[t];let l=s.operator,r=("less"==(l="more"==l&&"date"==s.type?"since":l)&&"date"==s.type&&(l="before"),""),n=s.value;Array.isArray(s.value)?(s.value.forEach(e=>{r+=`<span class="value">${e.text||e}</span>`}),"date"==s.type&&(r="",s.value.forEach(e=>{r+=`<span class="value">${w2utils.formatDate(e)}</span>`}))):"date"==s.type&&(n=w2utils.formatDateTime(n)),w2tooltip.hide(this.name+"-search-props"),w2tooltip.show({name:this.name+"-search-props",anchor:i,class:"w2ui-white",hideOn:"doc-click",html:`
<div class="w2ui-grid-search-single">
<span class="field">${e.label}</span>
<span class="operator">${w2utils.lang(l)}</span>
${Array.isArray(s.value)?""+r:`<span class="value">${n}</span>`}
<div class="buttons">
<button id="remove" class="w2ui-btn">${w2utils.lang("Remove This Field")}</button>
</div>
</div>`}).then(e=>{query(e.detail.overlay.box).find("#remove").on("click",()=>{this.searchData.splice(""+t,1),this.reload(),this.localSearch(),w2tooltip.hide(this.name+"-search-props")})})}searchSuggest(e,t,i){clearTimeout(this.last.kbd_timer),clearTimeout(this.last.overlay_timer),this.searchShowFields(!0),this.searchClose(),!0===t?w2tooltip.hide(this.name+"-search-suggest"):0<query(`#w2overlay-${this.name}-search-suggest`).length||(e?(t=query(this.box).find(`#grid_${this.name}_search_all`).get(0),e=[...this.defaultSearches??[],...0<this.defaultSearches?.length&&0<this.savedSearches?.length?["--"]:[],...this.savedSearches??[]],Array.isArray(e)&&0<e.length&&w2menu.show({name:this.name+"-search-suggest",anchor:t,align:"both",items:e,hideOn:["doc-click","sleect","remove"],render(e){let t=e.text;return t=e.isDefault?`<b>${t}</b>`:t}}).select(e=>{var t=this.trigger("searchSelect",{target:this.name,index:e.detail.index,item:e.detail.item});!0===t.isCancelled?e.preventDefault():(e.detail.overlay.hide(),this.last.logic=e.detail.item.logic||"AND",this.last.search="",this.last.label="[Multiple Fields]",this.searchData=w2utils.clone(e.detail.item.data),this.searchSelected=w2utils.clone(e.detail.item,{exclude:["icon","remove"]}),this.reload(),t.finish())}).remove(e=>{let i=e.detail.item,s=this.trigger("searchRemove",{target:this.name,index:e.detail.index,item:i});!0===s.isCancelled?e.preventDefault():(e.detail.overlay.hide(),this.confirm(w2utils.lang('Do you want to delete search "${item}"?',{item:i.text})).yes(e=>{var t=this.savedSearches.findIndex(e=>e.id==i.id);-1!==t&&this.savedSearches.splice(t,1),this.cacheSave("searches",this.savedSearches.map(e=>w2utils.clone(e,{exclude:["remove","icon"]}))),e.detail.self.close(),s.finish()}).no(e=>{e.detail.self.close()}))})):this.last.overlay_timer=setTimeout(()=>{this.searchSuggest(!0)},100))}searchSave(){let e="",t=(this.searchSelected&&(e=this.searchSelected.text),this.savedSearches.findIndex(e=>e.id==this.searchSelected?.id)),s=this.trigger("searchSave",{target:this.name,saveLocalStorage:!0});!0!==s.isCancelled&&this.message({width:350,height:150,body:`<div class="w2ui-grid-save-search">
<span>${w2utils.lang(-1!=t?"Update Search":"Save New Search")}</span>
<input class="search-name w2ui-input" placeholder="${w2utils.lang("Search name")}">
</div>`,buttons:`
<button id="grid-search-cancel" class="w2ui-btn">${w2utils.lang("Cancel")}</button>
<button id="grid-search-save" class="w2ui-btn w2ui-btn-blue" ${""==String(e).trim()?"disabled":""}>${w2utils.lang("Save")}</button>
`}).open(async i=>{query(i.detail.box).find("input, button").eq(0).val(e),await i.complete,query(i.detail.box).find("#grid-search-cancel").on("click",()=>{this.message()}),query(i.detail.box).find("#grid-search-save").on("click",()=>{var e=query(i.detail.box).find(".w2ui-message .search-name").val();this.searchSelected&&-1!=t?Object.assign(this.savedSearches[t],{id:e,text:e,logic:this.last.logic,data:w2utils.clone(this.searchData)}):this.savedSearches.push({id:e,text:e,icon:"w2ui-icon-search",remove:!0,logic:this.last.logic,data:this.searchData}),this.cacheSave("searches",this.savedSearches.map(e=>w2utils.clone(e,{exclude:["remove","icon"]}))),this.message(),(this.searchSelected?(this.searchSelected.text=e,query(this.box).find(`#grid_${this.name}_search_name .name-text`)):(this.searchSelected={text:e,logic:this.last.logic,data:w2utils.clone(this.searchData)},query(i.detail.box).find(`#grid_${this.name}_search_all`).val(" ").prop("readOnly",!0),query(i.detail.box).find(`#grid_${this.name}_search_name`).show().find(".name-text"))).html(e),s.finish({name:e})}),query(i.detail.box).find("input, button").off(".message").on("keydown.message",e=>{var t=String(query(i.detail.box).find(".w2ui-message-body input").val()).trim();13==e.keyCode&&""!=t&&query(i.detail.box).find("#grid-search-save").trigger("click"),27==e.keyCode&&this.message()}).eq(0).on("input.message",e=>{var t=query(i.detail.box).closest(".w2ui-message").find("#grid-search-save");""===String(query(i.detail.box).val()).trim()?t.prop("disabled",!0):t.prop("disabled",!1)}).get(0).focus()})}cache(e){if(w2utils.hasLocalStorage&&this.useLocalStorage)try{var t=JSON.parse(localStorage.w2ui||"{}");return t[this.stateId||this.name]??={},t[this.stateId||this.name][e]}catch(e){}return null}cacheSave(e,t){if(w2utils.hasLocalStorage&&this.useLocalStorage)try{var i=JSON.parse(localStorage.w2ui||"{}");return i[this.stateId||this.name]??={},i[this.stateId||this.name][e]=t,localStorage.w2ui=JSON.stringify(i),!0}catch(e){delete localStorage.w2ui}return!1}searchReset(e){var t=[];let i=!1;for(let e=0;e<this.searches.length;e++)this.searches[e].hidden&&null!=this.searches[e].value&&(t.push({field:this.searches[e].field,operator:this.searches[e].operator||"is",type:this.searches[e].type,value:this.searches[e].value||""}),i=!0);var s=this.trigger("search",{reset:!0,target:this.name,searchData:t});if(!0!==s.isCancelled){var l=query(this.box).find("#grid_"+this.name+"_search_all");if(this.searchData=s.detail.searchData,this.searchSelected=null,this.last.search="",this.last.logic=i?"AND":"OR",l.next().hide(),0<this.searches.length)if(this.multiSearch&&this.show.searchAll)this.last.field="all",this.last.label="All Fields",l.next().show();else{let e=0;for(;e<this.searches.length&&(this.searches[e].hidden||!1===this.searches[e].simple);)e++;e>=this.searches.length?(this.last.field="",this.last.label=""):(this.last.field=this.searches[e].field,this.last.label=this.searches[e].label)}this.last.multi=!1,this.last.fetch.offset=0,this.last.scrollTop=0,this.last.scrollLeft=0,this.last.selection.indexes=[],this.last.selection.columns={},this.searchClose();l=l.val("").get(0);l?._w2field&&l._w2field.reset(),e||this.reload(),s.finish()}}searchShowFields(e){if(!0===e)w2tooltip.hide(this.name+"-search-fields");else{var l=[];for(let s=-1;s<this.searches.length;s++){let e=this.searches[s];var r=e?e.field:null,r=this.getColumn(r);let t=!1,i=null;if(1==this.show.searchHiddenMsg&&-1!=s&&(null==r||!0===r.hidden&&!1!==r.hideable)&&(t=!0,i=w2utils.lang("This column "+(null==r?"does not exist":"is hidden"))),-1==s){if(!this.multiSearch||!this.show.searchAll)continue;e={field:"all",label:"All Fields"}}else{if(null!=r&&!1===r.hideable)continue;if(!0===e.hidden&&(i=w2utils.lang("This column is hidden"),!1===e.simple))continue}null==e.label&&null!=e.caption&&(console.log("NOTICE: grid search.caption property is deprecated, please use search.label. Search ->",e),e.label=e.caption),l.push({id:e.field,text:w2utils.lang(e.label),search:e,tooltip:i,disabled:t,checked:e.field==this.last.field})}w2menu.show({type:"radio",name:this.name+"-search-fields",anchor:query(this.box).find("#grid_"+this.name+"_search_name").parent().find(".w2ui-search-down").get(0),items:l,align:"none",hideOn:["doc-click","select"]}).select(e=>{this.searchInitInput(e.detail.item.search.field)})}}searchInitInput(e,t){let i;var s=query(this.box).find("#grid_"+this.name+"_search_all");if("all"==e)i={field:"all",label:w2utils.lang("All Fields")};else if(null==(i=this.getSearch(e)))return;""!=this.last.search?(this.last.label=i.label,this.search(i.field,this.last.search)):(this.last.field=i.field,this.last.label=i.label),s.attr("placeholder",w2utils.lang("Search")+" "+w2utils.lang(i.label||i.caption||i.field,!0))}clear(e){this.total=0,this.records=[],this.summary=[],this.last.fetch.offset=0,this.last.idCache={},this.last.selection={indexes:[],columns:{}},this.reset(!0),e||this.refresh()}reset(e){this.last.scrollTop=0,this.last.scrollLeft=0,this.last.range_start=null,this.last.range_end=null,query(this.box).find(`#grid_${this.name}_records`).prop("scrollTop",0),e||this.refresh()}skip(e,t){this.url?.get??this.url?(this.offset=parseInt(e),this.offset>this.total&&(this.offset=this.total-this.limit),(this.offset<0||!w2utils.isInt(this.offset))&&(this.offset=0),this.clear(!0),this.reload(t)):console.log("ERROR: grid.skip() can only be called when you have remote data source.")}load(e,t){return null==e?(console.log('ERROR: You need to provide url argument when calling .load() method of "'+this.name+'" object.'),new Promise((e,t)=>{t()})):(this.clear(!0),this.request("load",{},e,t))}reload(e){let t=this;var i=this.url?.get??this.url;return t.selectionSave(),i?this.load(i,()=>{t.selectionRestore(),"function"==typeof e&&e()}):(this.reset(!0),this.localSearch(),this.selectionRestore(),"function"==typeof e&&e({status:"success"}),new Promise(e=>{e()}))}request(i,e,t,s){let l=this,r,n;var a=new Promise((e,t)=>{r=e,n=t});if(null==e&&(e={}),!(t=t||this.url))return new Promise((e,t)=>{t()});w2utils.isInt(this.offset)||(this.offset=0),w2utils.isInt(this.last.fetch.offset)||(this.last.fetch.offset=0);let o;var h={limit:this.limit,offset:parseInt(this.offset)+parseInt(this.last.fetch.offset),searchLogic:this.last.logic,search:this.searchData.map(e=>{e=w2utils.clone(e);return this.searchMap&&this.searchMap[e.field]&&(e.field=this.searchMap[e.field]),e}),sort:this.sortData.map(e=>{e=w2utils.clone(e);return this.sortMap&&this.sortMap[e.field]&&(e.field=this.sortMap[e.field]),e})};if(0===this.searchData.length&&(delete h.search,delete h.searchLogic),0===this.sortData.length&&delete h.sort,w2utils.extend(h,this.postData),w2utils.extend(h,e),"delete"!=i&&"save"!=i||(delete h.limit,delete h.offset,"delete"==(h.action=i)&&(h[this.recid||"recid"]=this.getSelection())),"load"==i){if(!0===(o=this.trigger("request",{target:this.name,url:t,postData:h,httpMethod:"GET",httpHeaders:this.httpHeaders})).isCancelled)return new Promise((e,t)=>{t()})}else o={detail:{url:t,postData:h,httpMethod:"save"==i?"PUT":"DELETE",httpHeaders:this.httpHeaders}};if(0===this.last.fetch.offset&&this.lock(w2utils.lang(this.msgRefresh),!0),this.last.fetch.controller)try{this.last.fetch.controller.abort()}catch(e){}switch(t=o.detail.url,i){case"save":t?.save&&(t=t.save);break;case"delete":t?.remove&&(t=t.remove);break;default:t=t?.get??t}if(0<Object.keys(this.routeData).length){var d=w2utils.parseRoute(t);if(0<d.keys.length)for(let e=0;e<d.keys.length;e++)null!=this.routeData[d.keys[e].name]&&(t=t.replace(new RegExp(":"+d.keys[e].name,"g"),this.routeData[d.keys[e].name]))}t=new URL(t,location);e=w2utils.prepareParams(t,{method:o.detail.httpMethod,headers:o.detail.httpHeaders,body:o.detail.postData},this.dataType);return Object.assign(this.last.fetch,{action:i,options:e,controller:new AbortController,start:Date.now(),loaded:!1}),e.signal=this.last.fetch.controller.signal,fetch(t,e).catch(u).then(e=>{null!=e&&(200!=e?.status?u(e??{}):(l.unlock(),e.json().catch(u).then(e=>{this.requestComplete(e,i,s,r,n)})))}),"load"==i&&o.finish(),a;function u(e){var t;"AbortError"!==e?.name&&(l.unlock(),!0!==(t=l.trigger("error",{response:e,lastFetch:l.last.fetch})).isCancelled)&&(e.status&&200!=e.status?l.error(e.status+": "+e.statusText):(console.log("ERROR: Server communication failed.","\n EXPECTED:",{total:5,records:[{recid:1,field:"value"}]},"\n OR:",{error:!0,message:"error message"}),l.requestComplete({error:!0,message:w2utils.lang(this.msgHTTPError),response:e},i,s,r,n)),t.finish())}}requestComplete(e,t,i,s,l){let r=e.error??!1,n=(null==e.error&&"error"===e.status&&(r=!0),this.last.fetch.response=(Date.now()-this.last.fetch.start)/1e3,setTimeout(()=>{this.show.statusResponse&&this.status(w2utils.lang("Server Response ${count} seconds",{count:this.last.fetch.response}))},10),this.last.pull_more=!1,this.last.pull_refresh=!0,"load");"save"==this.last.fetch.action&&(n="save"),"delete"==this.last.fetch.action&&(n="delete");var a=this.trigger(n,{target:this.name,error:r,data:e,lastFetch:this.last.fetch});if(!0===a.isCancelled)l();else{if(r)this.error(w2utils.lang(e.message??this.msgServerError)),l(e);else if("function"==typeof this.parser?"object"!=typeof(e=this.parser(e))&&console.log("ERROR: Your parser did not return proper object"):null==e?e={error:!0,message:w2utils.lang(this.msgNotJSON)}:Array.isArray(e)&&(e={error:r,records:e,total:e.length}),"load"==t){if(null==e.total&&(e.total=-1),null==e.records&&(e.records=[]),e.records.length==this.limit?(l=this.records.length+e.records.length,this.last.fetch.hasMore=l!=this.total):(this.last.fetch.hasMore=!1,this.total=this.offset+this.last.fetch.offset+e.records.length),this.last.fetch.hasMore||query(this.box).find("#grid_"+this.name+"_rec_more, #grid_"+this.name+"_frec_more").hide(),0===this.last.fetch.offset)this.records=[],this.summary=[];else if(-1!=e.total&&parseInt(e.total)!=parseInt(this.total)){let e=this;return this.message(w2utils.lang(this.msgNeedReload)).ok(()=>{delete e.last.fetch.offset,e.reload()}),new Promise(e=>{e()})}w2utils.isInt(e.total)&&(this.total=parseInt(e.total)),e.records&&e.records.forEach(e=>{this.recid&&(e.recid=this.parseField(e,this.recid)),null==e.recid&&(e.recid="recid-"+this.records.length),(!0===e.w2ui?.summary?this.summary:this.records).push(e)}),e.summary&&(this.summary=[],e.summary.forEach(e=>{this.recid&&(e.recid=this.parseField(e,this.recid)),null==e.recid&&(e.recid="recid-"+this.summary.length),this.summary.push(e)}))}else if("delete"==t)return this.reset(),this.reload();(this.url?.get??this.url)||(this.localSort(),this.localSearch()),this.total=parseInt(this.total),0===this.last.fetch.offset?this.refresh():(this.scroll(),this.resize()),"function"==typeof i&&i(e),s(e),a.finish(),this.last.fetch.loaded=!0}}error(e){var t=this.trigger("error",{target:this.name,message:e});!0!==t.isCancelled&&(this.message(e),t.finish())}getChanges(t){var i=[];void 0===t&&(t=this.records);for(let e=0;e<t.length;e++){var s,l=t[e];l?.w2ui&&(null!=l.w2ui.changes&&((s={})[this.recid||"recid"]=l.recid,i.push(w2utils.extend(s,l.w2ui.changes))),!0!==l.w2ui.expanded)&&l.w2ui.children&&l.w2ui.children.length&&i.push(...this.getChanges(l.w2ui.children))}return i}mergeChanges(){var t=this.getChanges();for(let e=0;e<t.length;e++){var i,s=this.get(t[e][this.recid||"recid"]);for(i in t[e])if(!("recid"==i||this.recid&&i==this.recid)){"object"==typeof t[e][i]&&(t[e][i]=t[e][i].text);try{!function e(t,i,s){let l=i.split(".");1==l.length?t[i]=s:(t=t[l[0]],l.shift(),e(t,l.join("."),s))}(s,i,t[e][i])}catch(e){console.log("ERROR: Cannot merge. ",e.message||"",e)}s.w2ui&&delete s.w2ui.changes}}this.refresh()}save(t){var e=this.getChanges(),i=this.url?.save??this.url;let s=this.trigger("save",{target:this.name,changes:e});!0!==s.isCancelled&&(i?this.request("save",{changes:s.detail.changes},null,e=>{e.error||this.mergeChanges(),s.finish(),"function"==typeof t&&t(e)}):(this.mergeChanges(),s.finish()))}editField(d,u,c,p){let f=this;if(!0===this.last.inEditMode)p&&13==p.keyCode?({index:m,column:g,value:y}=this.last._edit,this.editChange({type:"custom",value:y},m,g,p),this.editDone(m,g,p)):0<(y=query(this.box).find("div.w2ui-edit-box .w2ui-input")).length&&("DIV"==y.get(0).tagName?(y.text(y.text()+c),w2utils.setCursorPosition(y.get(0),y.text().length)):(y.val(y.val()+c),w2utils.setCursorPosition(y.get(0),y.val().length)));else{let o=this.get(d,!0),h=this.getCellEditable(o,u);if(h&&!["checkbox","check"].includes(h.type)){let n=this.records[o],a=this.columns[u];var m=!0===a.frozen?"_f":"_";if(-1!=["enum","file"].indexOf(h.type))console.log('ERROR: input types "enum" and "file" are not supported in inline editing.');else{var g=this.trigger("editField",{target:this.name,recid:d,column:u,value:c,index:o,originalEvent:p});if(!0!==g.isCancelled){c=g.detail.value,this.last.inEditMode=!0,this.last.editColumn=u,this.last._edit={value:c,index:o,column:u,recid:d},this.selectNone(!0),this.select({recid:d,column:u});var y=query(this.box).find("#grid_"+this.name+m+"rec_"+w2utils.escapeId(d));let e=y.find('[col="'+u+'"] > div'),t=(this.last._edit.tr=y,this.last._edit.div=e,query(this.box).find("div.w2ui-edit-box").remove(),"row"!=this.selectType&&(query(this.box).find("#grid_"+this.name+m+"selection").attr("id","grid_"+this.name+"_editable").removeClass("w2ui-selection").addClass("w2ui-edit-box").prepend('<div style="position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px;"></div>').find(".w2ui-selection-resizer").remove(),e=query(this.box).find("#grid_"+this.name+"_editable > div:first-child")),h.attr=h.attr??"",h.text=h.text??"",h.style=h.style??"",h.items=h.items??[],null!=n.w2ui?.changes?.[a.field]?w2utils.stripTags(n.w2ui.changes[a.field]):w2utils.stripTags(f.parseField(n,a.field))),i="object"!=typeof(t=null==t?"":t)?t:"",s=(null!=g.detail.prevValue&&(i=g.detail.prevValue),null!=c&&(t=c),null!=a.style?a.style+";":"");"string"==typeof a.render&&["number","int","float","money","percent","size"].includes(a.render.split(":")[0])&&(s+="text-align: right;"),0<h.items.length&&!w2utils.isPlainObject(h.items[0])&&(h.items=w2utils.normMenu(h.items));let l,r=["date","time","datetime","color","list","combo"];p=getComputedStyle(y.find('[col="'+u+'"] > div').get(0)),m=`font-family: ${p["font-family"]}; font-size: ${p["font-size"]};`;function w(e){try{var t=getComputedStyle(e),i="DIV"==e.tagName.toUpperCase()?e.innerText:e.value,s=query(f.box).find("#grid_"+f.name+"_editable").get(0),l=`font-family: ${t["font-family"]}; font-size: ${t["font-size"]}; white-space: no-wrap;`,r=w2utils.getStrWidth(i,l);r+20>s.clientWidth&&query(s).css("width",r+20+"px")}catch(e){}}"div"===h.type?(e.addClass("w2ui-editable").html(w2utils.stripSpaces(`<div id="grid_${this.name}_edit_${d}_${u}" class="w2ui-input w2ui-focus"
contenteditable autocorrect="off" autocomplete="off" spellcheck="false"
style="${m+s+h.style}"
field="${a.field}" recid="${d}" column="${u}" ${h.attr}>
</div>`+h.text)),(l=e.find("div.w2ui-input").get(0)).innerText="object"!=typeof t?t:"",null!=c?w2utils.setCursorPosition(l,l.innerText.length):w2utils.setCursorPosition(l,0,l.innerText.length)):(e.addClass("w2ui-editable").html(w2utils.stripSpaces(`<input id="grid_${this.name}_edit_${d}_${u}" class="w2ui-input"
autocorrect="off" autocomplete="off" spellcheck="false" type="text"
style="${m+s+h.style}"
field="${a.field}" recid="${d}" column="${u}" ${h.attr}>`+h.text)),l=e.find("input").get(0),"number"==h.type&&(t=w2utils.formatNumber(t)),"date"==h.type&&(t=w2utils.formatDate(w2utils.isDate(t,h.format,!0)||new Date,h.format)),l.value="object"!=typeof t?t:"",y=e=>{var t=this.last._edit?.escKey;let i=!1;var s=query(l).data("tooltipName");s&&null!=w2tooltip.get(s[0])?.selected&&(i=!0),!this.last.inEditMode||t||!r.includes(h.type)||e.detail.overlay.anchor?.id!=this.last._edit.input?.id&&"list"!=h.type||(this.editChange(),this.editDone(void 0,void 0,{keyCode:i?13:0}))},new w2field(w2utils.extend({},h,{el:l,selected:t,onSelect:y,onHide:y})),null==c&&l&&l.select()),Object.assign(this.last._edit,{input:l,edit:h}),query(l).off(".w2ui-editable").on("blur.w2ui-editable",e=>{var t,i;this.last.inEditMode&&(t=this.last._edit.edit.type,i=query(l).data("tooltipName"),r.includes(t)&&i||(this.editChange(l,o,u,e),this.editDone()))}).on("mousedown.w2ui-editable",e=>{e.stopPropagation()}).on("click.w2ui-editable",e=>{w.call(l,e)}).on("paste.w2ui-editable",e=>{e.preventDefault();e=e.clipboardData.getData("text/plain");document.execCommand("insertHTML",!1,e)}).on("keyup.w2ui-editable",e=>{w.call(l,e)}).on("keydown.w2ui-editable",i=>{switch(i.keyCode){case 8:"list"!=h.type||l._w2field||i.preventDefault();break;case 9:case 13:i.preventDefault();break;case 27:var e=query(l).data("tooltipName");e&&0<e.length&&(this.last._edit.escKey=!0,w2tooltip.hide(e[0]),i.preventDefault()),i.stopPropagation()}setTimeout(()=>{switch(i.keyCode){case 9:var e=i.shiftKey?f.prevCell(o,u,!0):f.nextCell(o,u,!0);null!=e&&(t=f.records[e.index].recid,this.editChange(l,o,u,i),this.editDone(o,u,i),"row"!=f.selectType?(f.selectNone(!0),f.select({recid:t,column:e.colIndex})):f.editField(t,e.colIndex,null,i),i.preventDefault)&&i.preventDefault();break;case 13:{let e=!1;var t=query(l).data("tooltipName");t&&null!=w2tooltip.get(t[0]).selected&&(e=!0),t&&e||(this.editChange(l,o,u,i),this.editDone(o,u,i));break}case 27:{this.last._edit.escKey=!1;let e=f.parseField(n,a.field);null!=n.w2ui?.changes?.[a.field]&&(e=n.w2ui.changes[a.field]),null!=l._prevValue&&(e=l._prevValue),"DIV"==l.tagName?l.innerText=null!=e?e:"":l.value=null!=e?e:"",this.editDone(o,u,i),setTimeout(()=>{f.select({recid:d,column:u})},1);break}}w(l)},1)}),l&&(l._prevValue=i),"list"!=h.type&&setTimeout(()=>{this.last.inEditMode&&l&&(l.focus(),clearTimeout(this.last.kbd_timer),(l.resize=w)(l))},50),g.finish({input:l})}}}}}editChange(e,t,i,s){e=e??this.last._edit.input,t=t??this.last._edit.index,i=i??this.last._edit.column,s=s??{};var l=(t<0?this.summary:this.records)[t=t<0?-t-1:t],r=this.columns[i];let n="DIV"==e?.tagName?e.innerText:e.value;var a=e._w2field,o=(a&&("list"==a.type&&(n=a.selected),0!==Object.keys(n).length&&null!=n||(n=""),w2utils.isPlainObject(n)||(n=a.clean(n))),"checkbox"==e.type&&(!1===l.w2ui?.editable&&(e.checked=!e.checked),n=e.checked),this.parseField(l,r.field)),h=l.w2ui?.changes&&l.w2ui.changes.hasOwnProperty(r.field)?l.w2ui.changes[r.field]:o;let d={target:this.name,input:e,recid:l.recid,index:t,column:i,originalEvent:s,value:{new:n,previous:h,original:o}},u=(null!=s.target?._prevValue&&(d.value.previous=s.target._prevValue),0);for(;u<20;){if(u++,"object"!=typeof(n=d.value.new)&&String(o)!=String(n)||"object"==typeof n&&n&&n.id!=o&&("object"!=typeof o||null==o||n.id!=o.id)){if(!0!==(d=this.trigger("change",d)).isCancelled){if(n!==d.detail.value.new)continue;(""!==d.detail.value.new&&null!=d.detail.value.new||""!==h&&null!=h)&&(l.w2ui=l.w2ui??{},l.w2ui.changes=l.w2ui.changes??{},l.w2ui.changes[r.field]=d.detail.value.new),d.finish()}}else if(!0!==(d=this.trigger("restore",d)).isCancelled){if(n!==d.detail.value.new)continue;l.w2ui?.changes&&(delete l.w2ui.changes[r.field],0===Object.keys(l.w2ui.changes).length)&&delete l.w2ui.changes,d.finish()}break}}editDone(t,i,s){if(t=t??this.last._edit.index,i=i??this.last._edit.column,s=s??{},this.advanceOnEdit&&13==s.keyCode){let e=s.shiftKey?this.prevRow(t,i,1):this.nextRow(t,i,1);null==e&&(e=t),setTimeout(()=>{"row"!=this.selectType?(this.selectNone(!0),this.select({recid:this.records[e].recid,column:i})):this.editField(this.records[e].recid,i,null,s)},1)}var e=t<0,l=query(this.last._edit.tr).find('[col="'+i+'"]'),r=this.records[t],n=this.columns[i];this.last.inEditMode=!1,this.last._edit=null,e||(null!=r.w2ui?.changes?.[n.field]?l.addClass("w2ui-changed"):l.removeClass("w2ui-changed"),l.replace(this.getCellHTML(t,i,e))),query(this.box).find("div.w2ui-edit-box").remove(),this.updateToolbar(),setTimeout(()=>{var e=query(this.box).find(`#grid_${this.name}_focus`).get(0);document.activeElement===e||this.last.inEditMode||e.focus()},10)}delete(e){var t=this.trigger("delete",{target:this.name,force:e});if(e&&this.message(),!0!==t.isCancelled){e=t.detail.force;var i=this.getSelection();if(0!==i.length)if(""==this.msgDelete||e){if("object"!=typeof this.url?this.url:this.url.remove)this.request("delete");else if("object"!=typeof i[0])this.selectNone(),this.remove.apply(this,i);else{for(let e=0;e<i.length;e++){var s=this.columns[i[e].column].field,l=this.get(i[e].recid,!0),r=this.records[l];null!=l&&"recid"!=s&&(this.records[l][s]="",r.w2ui?.changes)&&delete r.w2ui.changes[s]}this.update()}t.finish()}else this.confirm({text:w2utils.lang(this.msgDelete,{count:i.length,records:w2utils.lang(1==i.length?"record":"records")}),width:380,height:170,yes_text:w2utils.lang("Delete"),yes_class:"w2ui-btn-red",no_text:w2utils.lang("Cancel")}).yes(e=>{e.detail.self.close(),this.delete(!0)}).no(e=>{e.detail.self.close()})}}click(l,r){var n=Date.now();let a=null;if(!(1==this.last.cancelClick||r&&r.altKey))if("object"==typeof l&&null!==l&&(a=l.column,l=l.recid),null==r&&(r={}),n-parseInt(this.last.click_time)<350&&this.last.click_recid==l&&"click"==r.type)this.dblClick(l,r);else{this.last.bubbleEl&&(this.last.bubbleEl=null),this.last.click_time=n;n=this.last.click_recid;if(this.last.click_recid=l,null==a&&r.target){let e=r.target;"TD"!=e.tagName&&(e=query(e).closest("td")[0]),null!=query(e).attr("col")&&(a=parseInt(query(e).attr("col")))}var o=this.trigger("click",{target:this.name,recid:l,column:a,originalEvent:r});if(!0!==o.isCancelled){var h=this.getSelection(),d=(query(this.box).find("#grid_"+this.name+"_check_all").prop("checked",!1),this.get(l,!0)),u=[];this.last.sel_ind=d,this.last.sel_col=a,this.last.sel_recid=l,this.last.sel_type="click";let e,i,t,s;if(r.shiftKey&&0<h.length&&this.multiSelect){if(h[0].recid){e=this.get(h[0].recid,!0),i=this.get(l,!0),s=a>h[0].column?(t=h[0].column,a):(t=a,h[0].column);for(let e=t;e<=s;e++)u.push(e)}else e=this.get(n,!0),i=this.get(l,!0);var c=[],p=(e>i&&(n=e,e=i,i=n),this.url?.get?this.url.get:this.url);for(let t=e;t<=i;t++)if(!(0<this.searchData.length)||p||this.last.searchIds.includes(t))if("row"==this.selectType)c.push(this.records[t].recid);else for(let e=0;e<u.length;e++)c.push({recid:this.records[t].recid,column:u[e]});this.select(c)}else{n=this.last.selection;let e=-1!=n.indexes.indexOf(d),t=!1;query(r.target).closest("td").hasClass("w2ui-col-select")&&(t=!0),(r.ctrlKey||r.shiftKey||r.metaKey||t)&&this.multiSelect||this.showSelectColumn?!0===(e="row"==this.selectType||n.columns[d]?.includes(a)?e:!1)?this.unselect({recid:l,column:a}):this.select({recid:l,column:a}):("row"==this.selectType||n.columns[d]?.includes(a)||(e=!1),this.selectNone(!0),!0===e&&1==h.length?this.unselect({recid:l,column:a}):this.select({recid:l,column:a}))}this.status(),this.initResize(),o.finish()}}}columnClick(s,t){if(!0!==this.last.colResizing){let e=this.trigger("columnClick",{target:this.name,field:s,originalEvent:t});if(!0!==e.isCancelled){if("row"==this.selectType){var l=this.getColumn(s);l&&l.sortable&&this.sort(s,null,!(!t||!t.ctrlKey&&!t.metaKey)),"line-number"==e.detail.field&&(this.getSelection().length>=this.records.length?this.selectNone():this.selectAll())}else if(t.altKey&&(l=this.getColumn(s))&&l.sortable&&this.sort(s,null,!(!t||!t.ctrlKey&&!t.metaKey)),"line-number"==e.detail.field)this.getSelection().length>=this.records.length?this.selectNone():this.selectAll();else{t.shiftKey||t.metaKey||t.ctrlKey||this.selectNone(!0);var l=this.getSelection(),s=this.getColumn(e.detail.field,!0),i=[],r=[];if(0!=l.length&&t.shiftKey){let t=s,i=l[0].column;t>i&&(t=l[0].column,i=s);for(let e=t;e<=i;e++)r.push(e)}else r.push(s);if(!0!==(e=this.trigger("columnSelect",{target:this.name,columns:r})).isCancelled){for(let e=0;e<this.records.length;e++)i.push({recid:this.records[e].recid,column:r});this.select(i)}e.finish()}e.finish()}}}columnDblClick(e,t){e=this.trigger("columnDblClick",{target:this.name,field:e,originalEvent:t});!0!==e.isCancelled&&e.finish()}columnContextMenu(e,t){e=this.trigger("columnContextMenu",{target:this.name,field:e,originalEvent:t});!0!==e.isCancelled&&(this.show.columnMenu&&(w2menu.show({type:"check",anchor:document.body,originalEvent:t,items:this.initColumnOnOff()}).then(()=>{query("#w2overlay-context-menu .w2ui-grid-skip").off(".w2ui-grid").on("click.w2ui-grid",e=>{e.stopPropagation()}).on("keypress",e=>{13==e.keyCode&&(this.skip(e.target.value),this.toolbar.click("w2ui-column-on-off"))})}).select(e=>{var t=e.detail.item.id;["w2ui-stateSave","w2ui-stateReset"].includes(t)?this[t.substring(5)]():"w2ui-skip"!=t&&this.columnOnOff(e,e.detail.item.id),clearTimeout(this.last.kbd_timer)}),clearTimeout(this.last.kbd_timer)),t.preventDefault(),e.finish())}focus(e){e=this.trigger("focus",{target:this.name,originalEvent:e});if(!0===e.isCancelled)return!1;this.hasFocus=!0,query(this.box).removeClass("w2ui-inactive").find(".w2ui-inactive").removeClass("w2ui-inactive"),setTimeout(()=>{var e=query(this.box).find(`#grid_${this.name}_focus`).get(0);e&&document.activeElement!=e&&e.focus()},10),e.finish()}blur(e){e=this.trigger("blur",{target:this.name,originalEvent:e});if(!0===e.isCancelled)return!1;this.hasFocus=!1,query(this.box).addClass("w2ui-inactive").find(".w2ui-selected").addClass("w2ui-inactive"),query(this.box).find(".w2ui-selection").addClass("w2ui-inactive"),e.finish()}keydown(c){let p=this,f="object"!=typeof this.url?this.url:this.url.get;if(!0===p.keyboard){var m=p.trigger("keydown",{target:p.name,originalEvent:c});if(!0!==m.isCancelled)if(0<query(this.box).find(".w2ui-message").length)27==c.keyCode&&this.message();else{let t=!1,i=query(p.box).find("#grid_"+p.name+"_records"),r=p.getSelection(),n=(0===r.length&&(t=!0),r[0]||null),a=[],s=r[r.length-1];if("object"==typeof n&&null!=n){n=r[0].recid,a=[];let e=0;for(;;){if(!r[e]||r[e].recid!=n)break;a.push(r[e].column),e++}s=r[r.length-1].recid}let o=p.get(n,!0),l=p.get(s,!0),h=query(p.box).find(`#grid_${p.name}_rec_`+(null!=o?w2utils.escapeId(p.records[o].recid):"none"));var g,y=Math.floor(i[0].clientHeight/p.recordHeight);let d=!1,e=c.keyCode,u=c.shiftKey;switch(e){case 8:case 46:p.delete(),d=!0,c.stopPropagation();break;case 27:p.selectNone(),d=!0;break;case 65:(c.metaKey||c.ctrlKey)&&(p.selectAll(),d=!0);break;case 13:if("row"==this.selectType&&!0===p.show.expandColumn){if(h.length<=0)break;p.toggle(n,c),d=!0}else{for(let e=0;e<this.columns.length;e++)if(this.getCellEditable(o,e)){a.push(parseInt(e));break}0<(a="row"==this.selectType&&this.last._edit&&this.last._edit.column?[this.last._edit.column]:a).length&&(p.editField(n,this.last.editColumn||a[0],null,c),d=!0)}break;case 37:!function(){if(t)x();else{if("row"==p.selectType){if(h.length<=0)return;var e=p.records[o].w2ui||{};!e||null==e.parent_recid||Array.isArray(e.children)&&0!==e.children.length&&e.expanded?p.collapse(n,c):(p.unselect(n),p.collapse(e.parent_recid,c),p.select(e.parent_recid))}else{let t=p.prevCell(o,a[0]);if(t=t?.index!=o?null:t?.colIndex,u||null!=t||(p.selectNone(!0),t=0),null!=t)if(u&&p.multiSelect){if(_())return;var i=[],s=[],l=[];if(0===a.indexOf(p.last.sel_col)&&1<a.length){for(let e=0;e<r.length;e++)-1==i.indexOf(r[e].recid)&&i.push(r[e].recid),l.push({recid:r[e].recid,column:a[a.length-1]});p.unselect(l),p.scrollIntoView(o,a[a.length-1],!0)}else{for(let e=0;e<r.length;e++)-1==i.indexOf(r[e].recid)&&i.push(r[e].recid),s.push({recid:r[e].recid,column:t});p.select(s),p.scrollIntoView(o,t,!0)}}else p.click({recid:n,column:t},c),p.scrollIntoView(o,t,!0);else u||p.selectNone(!0)}d=!0}}();break;case 39:!function(){if(t)x();else{if("row"==p.selectType){if(h.length<=0)return;p.expand(n,c)}else{let t=p.nextCell(o,a[a.length-1]);if(t=t.index!=o?null:t.colIndex,u||null!=t||(p.selectNone(!0),t=p.columns.length-1),null!=t)if(u&&39==e&&p.multiSelect){if(_())return;var i=[],s=[],l=[];if(a.indexOf(p.last.sel_col)==a.length-1&&1<a.length){for(let e=0;e<r.length;e++)-1==i.indexOf(r[e].recid)&&i.push(r[e].recid),l.push({recid:r[e].recid,column:a[0]});p.unselect(l),p.scrollIntoView(o,a[0],!0)}else{for(let e=0;e<r.length;e++)-1==i.indexOf(r[e].recid)&&i.push(r[e].recid),s.push({recid:r[e].recid,column:t});p.select(s),p.scrollIntoView(o,t,!0)}}else p.click({recid:n,column:t},c),p.scrollIntoView(o,t,!0);else u||p.selectNone(!0)}d=!0}}();break;case 33:b(y);break;case 34:v(y);break;case 35:v(-1);break;case 36:b(-1);break;case 38:b(c.metaKey||c.ctrlKey?-1:1);break;case 40:v(c.metaKey||c.ctrlKey?-1:1);break;case 17:case 91:t||w2utils.isSafari&&(p.last.copy_event=p.copy(!1,c),(g=query(p.box).find("#grid_"+p.name+"_focus")).val(p.last.copy_event.detail.text),g[0].select());break;case 67:(c.metaKey||c.ctrlKey)&&(w2utils.isSafari||(p.last.copy_event=p.copy(!1,c),(g=query(p.box).find("#grid_"+p.name+"_focus")).val(p.last.copy_event.detail.text),g[0].select()),p.copy(p.last.copy_event,c));break;case 88:t||(c.ctrlKey||c.metaKey)&&(w2utils.isSafari||(p.last.copy_event=p.copy(!1,c),(g=query(p.box).find("#grid_"+p.name+"_focus")).val(p.last.copy_event.detail.text),g[0].select()),p.copy(p.last.copy_event,c))}var w=[32,187,189,192,219,220,221,186,222,188,190,191];for(let e=48;e<=111;e++)w.push(e);function b(e){if(t&&x(),!(h.length<=0)){let t=p.prevRow(o,"row"==p.selectType?0:r[0].column,e);if(null!=(t=u||null!=t?t:0==p.searchData.length||f?0:p.last.searchIds[0])){if(u&&p.multiSelect){if(_())return;if("row"==p.selectType)p.last.sel_ind>t&&p.last.sel_ind!=l?p.unselect(p.records[l].recid):p.select(p.records[t].recid);else if(p.last.sel_ind>t&&p.last.sel_ind!=l){t=l;var i=[];for(let e=0;e<a.length;e++)i.push({recid:p.records[t].recid,column:a[e]});p.unselect(i)}else{var s=[];for(let e=0;e<a.length;e++)s.push({recid:p.records[t].recid,column:a[e]});p.select(s)}}else p.selectNone(!0),p.click({recid:p.records[t].recid,column:a[0]},c);p.scrollIntoView(t,null,!0,1!=e),c.preventDefault&&c.preventDefault()}else u||p.selectNone(!0)}}function v(e){if(t&&x(),!(h.length<=0)){let t=p.nextRow(l,"row"==p.selectType?0:r[0].column,e);if(null!=(t=u||null!=t?t:0==p.searchData.length||f?p.records.length-1:p.last.searchIds[p.last.searchIds.length-1])){if(u&&p.multiSelect){if(_())return;if("row"==p.selectType)p.last.sel_ind<t&&p.last.sel_ind!=o?p.unselect(p.records[o].recid):p.select(p.records[t].recid);else if(p.last.sel_ind<t&&p.last.sel_ind!=o){t=o;var i=[];for(let e=0;e<a.length;e++)i.push({recid:p.records[t].recid,column:a[e]});p.unselect(i)}else{var s=[];for(let e=0;e<a.length;e++)s.push({recid:p.records[t].recid,column:a[e]});p.select(s)}}else p.selectNone(!0),p.click({recid:p.records[t].recid,column:a[0]},c);p.scrollIntoView(t,null,!0,1!=e),d=!0}else u||p.selectNone(!0)}}function x(){if(p.records&&0!==p.records.length){let e=Math.floor(i[0].scrollTop/p.recordHeight)+1;(!p.records[e]||e<2)&&(e=0),void 0!==p.records[e]&&p.select({recid:p.records[e].recid,column:0})}}function _(){if("click"==p.last.sel_type){if("row"==p.selectType)return p.last.sel_type="key",1<r.length&&(r.splice(r.indexOf(p.records[p.last.sel_ind].recid),1),p.unselect(r),1);if(p.last.sel_type="key",1<r.length){for(let e=0;e<r.length;e++)if(r[e].recid==p.last.sel_recid&&r[e].column==p.last.sel_col){r.splice(e,1);break}return p.unselect(r),1}}}-1==w.indexOf(e)||c.ctrlKey||c.metaKey||d||(0===a.length&&a.push(0),d=!1,setTimeout(()=>{var e=query(p.box).find("#grid_"+p.name+"_focus"),t=e.val();e.val(""),p.editField(n,a[0],t,c)},1)),d&&c.preventDefault&&c.preventDefault(),m.finish()}}}scrollIntoView(e,s,t,i){let l=this.records.length;if(0!==(l=0==this.searchData.length||this.url?l:this.last.searchIds.length)){if(null==e){var r=this.getSelection();if(0===r.length)return;w2utils.isPlainObject(r[0])?(e=r[0].index,s=r[0].column):e=this.get(r[0],!0)}var r=query(this.box).find(`#grid_${this.name}_records`),n=r[0].clientWidth,a=r[0].clientHeight,o=r[0].scrollTop,h=r[0].scrollLeft,d=this.last.searchIds.length;if(0<d&&(e=this.last.searchIds.indexOf(e)),r.css({"scroll-behavior":t?"auto":"smooth"}),a<this.recordHeight*(0<d?d:l)&&0<r.length&&(d=(t=Math.floor(o/this.recordHeight))+Math.floor(a/this.recordHeight),e==t&&r.prop("scrollTop",o-a/1.3),e==d&&r.prop("scrollTop",o+a/1.3),(e<t||d<e)&&r.prop("scrollTop",(e-1)*this.recordHeight),!0===i)&&r.prop("scrollTop",e*this.recordHeight),null!=s){let t=0,i=0;o=w2utils.scrollBarSize();for(let e=0;e<=s;e++){var u=this.columns[e];u.frozen||u.hidden||(t=i,i+=parseInt(u.sizeCalculated))}n<i-h?r.prop("scrollLeft",t-o):t<h&&r.prop("scrollLeft",i-n+2*o)}}}scrollToColumn(s){if(null!=s){let t=0,i=!1;for(let e=0;e<this.columns.length;e++){var l=this.columns[e];if(l.field==s){i=!0;break}l.frozen||l.hidden||(l=parseInt(l.sizeCalculated||l.size),t+=l)}i&&(this.last.scrollLeft=t+1,this.scroll())}}dblClick(e,t){let i=null;if("object"==typeof e&&null!==e&&(i=e.column,e=e.recid),null==t&&(t={}),null==i&&t.target){let e=t.target;"TD"!=e.tagName.toUpperCase()&&(e=query(e).closest("td")[0]),i=parseInt(query(e).attr("col"))}var s=this.get(e,!0),l=this.records[s],r=this.trigger("dblClick",{target:this.name,recid:e,column:i,originalEvent:t});!0!==r.isCancelled&&(this.selectNone(!0),this.getCellEditable(s,i)?this.editField(e,i,null,t):(this.select({recid:e,column:i}),(this.show.expandColumn||l&&l.w2ui&&Array.isArray(l.w2ui.children))&&this.toggle(e)),r.finish())}showContextMenu(i,s,e){if("text"!=this.last.userSelect){null==(e=null==e?{offsetX:0,offsetY:0,target:query(this.box).find(`#grid_${this.name}_rec_`+i)[0]}:e).offsetX&&(e.offsetX=e.layerX-e.target.offsetLeft,e.offsetY=e.layerY-e.target.offsetTop),w2utils.isFloat(i)&&(i=parseFloat(i));var l=this.getSelection();if("row"==this.selectType)-1==l.indexOf(i)&&this.click(i);else{let t=!1;for(let e=0;e<l.length;e++)l[e].recid!=i&&l[e].column!=s||(t=!0);t||null==i||this.click({recid:i,column:s}),t||null==s||this.columnClick(this.columns[s].field,e)}var t=this.trigger("contextMenu",{target:this.name,originalEvent:e,recid:i,column:s});!0!==t.isCancelled&&(0<this.contextMenu.length&&(w2menu.show({anchor:document.body,originalEvent:e,items:this.contextMenu}).select(e=>{clearTimeout(this.last.kbd_timer),this.contextMenuClick(i,s,e)}),clearTimeout(this.last.kbd_timer)),e.preventDefault(),t.finish())}}contextMenuClick(e,t,i){e=this.trigger("contextMenuClick",{target:this.name,recid:e,column:t,originalEvent:i.detail.originalEvent,menuEvent:i,menuIndex:i.detail.index,menuItem:i.detail.item});!0!==e.isCancelled&&e.finish()}toggle(e){var t=this.get(e);if(null!=t)return t.w2ui=t.w2ui??{},!0===t.w2ui.expanded?this.collapse(e):this.expand(e)}expand(e,t){var i=this.get(e,!0);let s=this.records[i];s.w2ui=s.w2ui??{};var l=w2utils.escapeId(e),r=s.w2ui.children;let n;if(Array.isArray(r)){if(!0===s.w2ui.expanded||0===r.length)return!1;if(!0===(n=this.trigger("expand",{target:this.name,recid:e})).isCancelled)return!1;s.w2ui.expanded=!0,r.forEach(e=>{e.w2ui=e.w2ui??{},e.w2ui.parent_recid=s.recid,null==e.w2ui.children&&(e.w2ui.children=[])}),this.records.splice.apply(this.records,[i+1,0].concat(r)),-1!==this.total&&(this.total+=r.length),("object"!=typeof this.url?this.url:this.url.get)||(this.localSort(!0,!0),0<this.searchData.length&&this.localSearch(!0)),!0!==t&&this.refresh(),n.finish()}else{if(0<query(this.box).find("#grid_"+this.name+"_rec_"+l+"_expanded_row").length||!0!==this.show.expandColumn)return!1;if("none"==s.w2ui.expanded)return!1;if(query(this.box).find("#grid_"+this.name+"_rec_"+l).after(`<tr id="grid_${this.name}_rec_${e}_expanded_row" class="w2ui-expanded-row">
<td colspan="100" class="w2ui-expanded2">
<div id="grid_${this.name}_rec_${e}_expanded"></div>
</td>
<td class="w2ui-grid-data-last"></td>
</tr>`),query(this.box).find("#grid_"+this.name+"_frec_"+l).after(`<tr id="grid_${this.name}_frec_${e}_expanded_row" class="w2ui-expanded-row">
${this.show.lineNumbers?'<td class="w2ui-col-number"></td>':""}
<td class="w2ui-grid-data w2ui-expanded1" colspan="100">
<div id="grid_${this.name}_frec_${e}_expanded"></div>
</td>
</tr>`),!0===(n=this.trigger("expand",{target:this.name,recid:e,box_id:"grid_"+this.name+"_rec_"+e+"_expanded",fbox_id:"grid_"+this.name+"_frec_"+e+"_expanded"})).isCancelled)return query(this.box).find("#grid_"+this.name+"_rec_"+l+"_expanded_row").remove(),query(this.box).find("#grid_"+this.name+"_frec_"+l+"_expanded_row").remove(),!1;i=query(this.box).find("#grid_"+this.name+"_rec_"+e+"_expanded"),r=query(this.box).find("#grid_"+this.name+"_frec_"+e+"_expanded"),t=i.find(":scope div:first-child")[0]?.clientHeight??50;i[0].clientHeight<t&&i.css({height:t+"px"}),r[0].clientHeight<t&&r.css({height:t+"px"}),query(this.box).find("#grid_"+this.name+"_rec_"+l).attr("expanded","yes").addClass("w2ui-expanded"),query(this.box).find("#grid_"+this.name+"_frec_"+l).attr("expanded","yes").addClass("w2ui-expanded"),query(this.box).find("#grid_"+this.name+"_cell_"+this.get(e,!0)+"_expand div").html("-"),s.w2ui.expanded=!0,n.finish(),this.resizeRecords()}return!0}collapse(t,i){var s=this.get(t,!0);let l=this.records[s],e=(l.w2ui=l.w2ui||{},w2utils.escapeId(t));var r=l.w2ui.children;let n;if(Array.isArray(r)){if(!0!==l.w2ui.expanded)return!1;if(!0===(n=this.trigger("collapse",{target:this.name,recid:t})).isCancelled)return!1;!function i(s){s.w2ui.expanded=!1;for(let t=0;t<s.w2ui.children.length;t++){let e=s.w2ui.children[t];e.w2ui.expanded&&i(e)}}(l);var a=[];for(let e=l;null!=e;e=this.get(e.w2ui.parent_recid))a.push(e.w2ui.parent_recid);r=s+1;let e=r;for(;;){if(this.records.length<=e+1||null==this.records[e+1].w2ui||0<=a.indexOf(this.records[e+1].w2ui.parent_recid))break;e++}this.records.splice(r,e-r+1),-1!==this.total&&(this.total-=e-r+1),("object"!=typeof this.url?this.url:this.url.get)||0<this.searchData.length&&this.localSearch(!0),!0!==i&&this.refresh(),n.finish()}else{if(0===query(this.box).find("#grid_"+this.name+"_rec_"+e+"_expanded_row").length||!0!==this.show.expandColumn)return!1;if(!0===(n=this.trigger("collapse",{target:this.name,recid:t,box_id:"grid_"+this.name+"_rec_"+t+"_expanded",fbox_id:"grid_"+this.name+"_frec_"+t+"_expanded"})).isCancelled)return!1;query(this.box).find("#grid_"+this.name+"_rec_"+e).removeAttr("expanded").removeClass("w2ui-expanded"),query(this.box).find("#grid_"+this.name+"_frec_"+e).removeAttr("expanded").removeClass("w2ui-expanded"),query(this.box).find("#grid_"+this.name+"_cell_"+this.get(t,!0)+"_expand div").html("+"),query(this.box).find("#grid_"+this.name+"_rec_"+e+"_expanded").css("height","0px"),query(this.box).find("#grid_"+this.name+"_frec_"+e+"_expanded").css("height","0px"),setTimeout(()=>{query(this.box).find("#grid_"+this.name+"_rec_"+e+"_expanded_row").remove(),query(this.box).find("#grid_"+this.name+"_frec_"+e+"_expanded_row").remove(),l.w2ui.expanded=!1,n.finish(),this.resizeRecords()},300)}return!0}sort(i,e,s){var t=this.trigger("sort",{target:this.name,field:i,direction:e,multiField:s});if(!0!==t.isCancelled){if(null!=i){let t=this.sortData.length;for(let e=0;e<this.sortData.length;e++)if(this.sortData[e].field==i){t=e;break}null==e&&(e=null!=this.sortData[t]&&(null==this.sortData[t].direction&&(this.sortData[t].direction=""),"asc"===this.sortData[t].direction.toLowerCase())?"desc":"asc"),!1===this.multiSort&&(this.sortData=[],t=0),1!=s&&(this.sortData=[],t=0),null==this.sortData[t]&&(this.sortData[t]={}),this.sortData[t].field=i,this.sortData[t].direction=e}else this.sortData=[];("object"!=typeof this.url?this.url:this.url.get)?(t.finish({direction:e}),this.last.fetch.offset=0,this.reload()):(this.localSort(!1,!0),0<this.searchData.length&&this.localSearch(!0),this.last.scrollTop=0,query(this.box).find(`#grid_${this.name}_records`).prop("scrollTop",0),t.finish({direction:e}),this.refresh())}}copy(e,t){if(w2utils.isPlainObject(e))return e.finish(),e.text;var s=this.getSelection();if(0===s.length)return"";let l="";if("object"==typeof s[0]){let t=s[0].column,i=s[0].column;var r=[];for(let e=0;e<s.length;e++)s[e].column<t&&(t=s[e].column),s[e].column>i&&(i=s[e].column),-1==r.indexOf(s[e].index)&&r.push(s[e].index);r.sort((e,t)=>e-t);for(let e=0;e<r.length;e++){var n=r[e];for(let e=t;e<=i;e++)!0!==this.columns[e].hidden&&(l+=this.getCellCopy(n,e)+"\t");l=l.substr(0,l.length-1),l+="\n"}}else{for(let e=0;e<this.columns.length;e++){var i=this.columns[e];if(!0!==i.hidden){let e=i.text||i.field;i.text&&i.text.length<3&&i.tooltip&&(e=i.tooltip),l+='"'+w2utils.stripTags(e)+'"\t'}}l=l.substr(0,l.length-1),l+="\n";for(let e=0;e<s.length;e++){var a=this.get(s[e],!0);for(let e=0;e<this.columns.length;e++)!0!==this.columns[e].hidden&&(l+='"'+this.getCellCopy(a,e)+'"\t');l=l.substr(0,l.length-1),l+="\n"}}l=l.substr(0,l.length-1);let o;return null==e?!0===(o=this.trigger("copy",{target:this.name,text:l,cut:88==t.keyCode,originalEvent:t})).isCancelled?"":(l=o.detail.text,o.finish(),l):!1===e?!0===(o=this.trigger("copy",{target:this.name,text:l,cut:88==t.keyCode,originalEvent:t})).isCancelled?"":(l=o.detail.text,o):void 0}getCellCopy(e,t){return w2utils.stripTags(this.getCellHTML(e,t))}paste(i,e){var t=this.getSelection();let s=this.get(t[0].recid,!0);var l,r,n,a=t[0].column,e=this.trigger("paste",{target:this.name,text:i,index:s,column:a,originalEvent:e});if(!0!==e.isCancelled){if(i=e.detail.text,"row"==this.selectType||0===t.length)console.log("ERROR: You can paste only if grid.selectType = 'cell' and when at least one cell selected.");else{if("object"!=typeof i){var o=[];i=i.split("\n");for(let e=0;e<i.length;e++){var h=i[e].split("\t");let t=0;var d=this.records[s],u=[];if(null!=d){for(let e=0;e<h.length;e++)this.columns[a+t]&&(l=d,r=this.columns[a+t].field,n=h[e],l.w2ui=l.w2ui??{},l.w2ui.changes=l.w2ui.changes||{},l.w2ui.changes[r]=n,u.push(a+t),t++);for(let e=0;e<u.length;e++)o.push({recid:d.recid,column:u[e]});s++}}this.selectNone(!0),this.select(o)}else this.selectNone(!0),this.select([{recid:this.records[s],column:a}]);this.refresh()}e.finish()}}resize(){var e=Date.now();if(this.box&&query(this.box).attr("name")==this.name){var t=this.trigger("resize",{target:this.name});if(!0!==t.isCancelled)return this.resizeBoxes(),this.resizeRecords(),t.finish(),Date.now()-e}}update({cells:t,fullCellRefresh:i,ignoreColumns:e}={}){var s=Date.now();let u=this;if(null==this.box)return 0;if(Array.isArray(t))for(let e=0;e<t.length;e++){var l=t[e].index,r=t[e].column;if(!(l<0))if(null==l||null==r)console.log("ERROR: Wrong argument for grid.update({ cells }), cells should be [{ index: X, column: Y }, ...]");else{var n=this.records[l]??{};n.w2ui=n.w2ui??{},n.w2ui._update=n.w2ui._update??{cells:[]};let e=n.w2ui._update.row1,t=n.w2ui._update.row2;null!=e&&e.isConnected&&null!=t&&t.isColSelected||(e=this.box.querySelector(`#grid_${this.name}_rec_`+w2utils.escapeId(n.recid)),t=this.box.querySelector(`#grid_${this.name}_frec_`+w2utils.escapeId(n.recid)),n.w2ui._update.row1=e,n.w2ui._update.row2=t),o(n,e,t,l,r)}}else for(let e=this.last.range_start-1;e<=this.last.range_end;e++){let s=e;s=0<this.last.searchIds.length?this.last.searchIds[e]:e;var a=this.records[s];if(!(s<0||null==a)){a.w2ui=a.w2ui??{},a.w2ui._update=a.w2ui._update??{cells:[]};let t=a.w2ui._update.row1,i=a.w2ui._update.row2;null!=t&&t.isConnected&&null!=i&&i.isColSelected||(t=this.box.querySelector(`#grid_${this.name}_rec_`+w2utils.escapeId(a.recid)),i=this.box.querySelector(`#grid_${this.name}_frec_`+w2utils.escapeId(a.recid)),a.w2ui._update.row1=t,a.w2ui._update.row2=i);for(let e=0;e<this.columns.length;e++)o(a,t,i,s,e)}}return Date.now()-s;function o(s,l,r,n,t){var a=u.columns[t];if(!Array.isArray(e)||!e.includes(t)&&!e.includes(a.field)){let e=s.w2ui._update.cells[t];if(null!=e&&e.isConnected||(e=u.box.querySelector(`#grid_${u.name}_data_${n}_`+t),s.w2ui._update.cells[t]=e),null!=e){if(i)query(e).replace(u.getCellHTML(n,t,!1)),e=u.box.querySelector(`#grid_${u.name}_data_${n}_`+t),s.w2ui._update.cells[t]=e;else{var o=e.children[0],{value:n,style:h,className:d}=u.getCellValue(n,t,!1,!0);if(o.innerHTML!=n&&(o.innerHTML=n),""!=h&&e.style.cssText!=h&&(e.style.cssText=h),""!=d){let t=["w2ui-grid-data"],i=[];o=d.split(" ").filter(e=>!!e);e.classList.forEach(e=>{t.includes(e)||i.push(e)}),e.classList.remove(...i),e.classList.add(...o)}}if(u.columns[t].style&&u.columns[t].style!=e.style.cssText&&(e.style.cssText=u.columns[t].style??""),null!=s.w2ui.class){if("string"==typeof s.w2ui.class){let t=["w2ui-odd","w2ui-even","w2ui-record"],i=[];n=s.w2ui.class.split(" ").filter(e=>!!e);l&&r&&(l.classList.forEach(e=>{t.includes(e)||i.push(e)}),l.classList.remove(...i),l.classList.add(...n),r.classList.remove(...i),r.classList.add(...n))}if(w2utils.isPlainObject(s.w2ui.class)&&"string"==typeof s.w2ui.class[a.field]){let t=["w2ui-grid-data"],i=[];h=s.w2ui.class[a.field].split(" ").filter(e=>!!e);e.classList.forEach(e=>{t.includes(e)||i.push(e)}),e.classList.remove(...i),e.classList.add(...h)}}null!=s.w2ui.style&&(l&&r&&"string"==typeof s.w2ui.style&&l.style.cssText!==s.w2ui.style&&(l.style.cssText="height: "+u.recordHeight+"px;"+s.w2ui.style,l.setAttribute("custom_style",s.w2ui.style),r.style.cssText="height: "+u.recordHeight+"px;"+s.w2ui.style,r.setAttribute("custom_style",s.w2ui.style)),w2utils.isPlainObject(s.w2ui.style))&&"string"==typeof s.w2ui.style[a.field]&&e.style.cssText!==s.w2ui.style[a.field]&&(e.style.cssText=s.w2ui.style[a.field])}}}}refreshCell(e,t){var i=this.get(e,!0),t=this.getColumn(t,!0),e=!this.records[i]||this.records[i].recid!=e,s=query(this.box).find(`${e?".w2ui-grid-summary ":""}#grid_${this.name}_data_${i}_`+t);return 0!=s.length&&(s.replace(this.getCellHTML(i,t,e)),!0)}refreshRow(t,i=null){let s=query(this.box).find("#grid_"+this.name+"_frec_"+w2utils.escapeId(t)),l=query(this.box).find("#grid_"+this.name+"_rec_"+w2utils.escapeId(t));if(0<s.length){null==i&&(i=this.get(t,!0));var r=s.attr("line"),n=!this.records[i]||this.records[i].recid!=t,a="object"!=typeof this.url?this.url:this.url.get;if(0<this.searchData.length&&!a)for(let e=0;e<this.last.searchIds.length;e++)this.last.searchIds[e]==i&&(i=e);a=this.getRecordHTML(i,r,n);s.replace(a[0]),l.replace(a[1]);let e=this.records[i].w2ui?this.records[i].w2ui.style:"";return"string"==typeof e&&(s=query(this.box).find("#grid_"+this.name+"_frec_"+w2utils.escapeId(t)),l=query(this.box).find("#grid_"+this.name+"_rec_"+w2utils.escapeId(t)),s.attr("custom_style",e),l.attr("custom_style",e),s.hasClass("w2ui-selected")&&(e=e.replace("background-color","none")),s[0].style.cssText="height: "+this.recordHeight+"px;"+e,l[0].style.cssText="height: "+this.recordHeight+"px;"+e),n&&this.resize(),!0}return!1}refresh(){var e=Date.now(),t="object"!=typeof this.url?this.url:this.url.get;if(this.total<=0&&!t&&0===this.searchData.length&&(this.total=this.records.length),this.box){t=this.trigger("refresh",{target:this.name});if(!0!==t.isCancelled){this.show.header?query(this.box).find(`#grid_${this.name}_header`).html(w2utils.lang(this.header)+" ").show():query(this.box).find(`#grid_${this.name}_header`).hide(),this.show.toolbar?query(this.box).find("#grid_"+this.name+"_toolbar").show():query(this.box).find("#grid_"+this.name+"_toolbar").hide(),this.searchClose();var i=query(this.box).find("#grid_"+this.name+"_search_all");!this.multiSearch&&"all"==this.last.field&&0<this.searches.length&&(this.last.field=this.searches[0].field,this.last.label=this.searches[0].label);for(let e=0;e<this.searches.length;e++)this.searches[e].field==this.last.field&&(this.last.label=this.searches[e].label);if(this.last.multi?i.attr("placeholder","["+w2utils.lang("Multiple Fields")+"]"):i.attr("placeholder",w2utils.lang("Search")+" "+w2utils.lang(this.last.label,!0)),i.val()!=this.last.search){let e=this.last.search;var s=i._w2field;s&&(e=s.format(e)),i.val(e)}this.refreshSearch(),this.refreshBody(),this.show.footer?query(this.box).find(`#grid_${this.name}_footer`).html(this.getFooterHTML()).show():query(this.box).find(`#grid_${this.name}_footer`).hide();var s=this.last.selection,i=0<this.records.length&&s.indexes.length==this.records.length,s=0<s.indexes.length&&0!==this.searchData.length&&s.indexes.length==this.last.searchIds.length,l=(i||s?query(this.box).find("#grid_"+this.name+"_check_all").prop("checked",!0):query(this.box).find("#grid_"+this.name+"_check_all").prop("checked",!1),this.status(),this.find({"w2ui.expanded":!0},!0,!0));for(let e=0;e<l.length;e++){var r=this.records[l[e]].w2ui;r&&!Array.isArray(r.children)&&(r.expanded=!1)}return this.markSearch&&setTimeout(()=>{var t=[];for(let e=0;e<this.searchData.length;e++){var i=this.searchData[e],s=this.getSearch(i.field);s&&!s.hidden&&(s=this.getColumn(i.field,!0),t.push({field:i.field,search:i.value,col:s}))}0<t.length&&t.forEach(e=>{var t=query(this.box).find('td[col="'+e.col+'"]:not(.w2ui-head)');w2utils.marker(t,e.search)})},50),this.updateToolbar(this.last.selection),t.finish(),this.resize(),this.addRange("selection"),setTimeout(()=>{this.resize(),this.scroll()},1),this.reorderColumns&&!this.last.columnDrag?this.last.columnDrag=this.initColumnDrag():!this.reorderColumns&&this.last.columnDrag&&this.last.columnDrag.remove(),Date.now()-e}}}refreshSearch(){if(this.multiSearch&&0<this.searchData.length){0==query(this.box).find(".w2ui-grid-searches").length&&query(this.box).find(".w2ui-grid-toolbar").css("height",this.last.toolbar_height+35+"px").append(`<div id="grid_${this.name}_searches" class="w2ui-grid-searches"></div>`);let r=`
<span id="grid_${this.name}_search_logic" class="w2ui-grid-search-logic"></span>
<div class="grid-search-line"></div>`;this.searchData.forEach((i,e)=>{var t=this.getSearch(i.field,!0),s=this.searches[t];let l;if(l=Array.isArray(i.value)?`<span class="grid-search-count">${i.value.length}</span>`:s&&"list"==s.type&&i.text&&i.text!==i.value?": "+i.text:": "+i.value,s&&"date"==s.type)if("between"==i.operator){let e=i.value[0],t=i.value[1];Number(e)===e&&(e=w2utils.formatDate(e)),Number(t)===t&&(t=w2utils.formatDate(t)),l=`: ${e} - `+t}else{let e=i.value,t=(Number(e)==e&&(e=w2utils.formatDate(e)),i.operator);"more:"==(t="less"==(t="more"==t?"since":t)?"before":t).substr(0,5)&&(t="since"),l=`: ${t} `+e}r+=`<span class="w2ui-action" data-click="searchFieldTooltip|${t}|${e}|this">
${s?s.label:""}
${l}
<span class="icon-chevron-down"></span>
</span>`}),r+=`
${this.show.searchSave?`<div class="grid-search-line"></div>
<button class="w2ui-btn grid-search-btn" data-click="searchSave">${w2utils.lang("Save")}</button>
`:""}
<button class="w2ui-btn grid-search-btn btn-remove"
data-click="searchReset">X</button>
`,query(this.box).find(`#grid_${this.name}_searches`).html(r),query(this.box).find(`#grid_${this.name}_search_logic`).html(w2utils.lang("AND"==this.last.logic?"All":"Any"))}else query(this.box).find(".w2ui-grid-toolbar").css("height",this.last.toolbar_height+"px").find(".w2ui-grid-searches").remove();this.searchSelected?(query(this.box).find(`#grid_${this.name}_search_all`).val(" ").prop("readOnly",!0),query(this.box).find(`#grid_${this.name}_search_name`).show().find(".name-text").html(this.searchSelected.text)):(query(this.box).find(`#grid_${this.name}_search_all`).prop("readOnly",!1),query(this.box).find(`#grid_${this.name}_search_name`).hide().find(".name-text").html("")),w2utils.bindEvents(query(this.box).find(`#grid_${this.name}_searches .w2ui-action, #grid_${this.name}_searches button`),this)}refreshBody(){this.scroll();var e=this.getRecordsHTML(),t=this.getColumnsHTML(),e='<div id="grid_'+this.name+'_frecords" class="w2ui-grid-frecords" style="margin-bottom: '+(w2utils.scrollBarSize()-1)+'px;">'+e[0]+'</div><div id="grid_'+this.name+'_records" class="w2ui-grid-records">'+e[1]+'</div><div id="grid_'+this.name+'_scroll1" class="w2ui-grid-scroll1" style="height: '+w2utils.scrollBarSize()+'px"></div><div id="grid_'+this.name+'_fcolumns" class="w2ui-grid-fcolumns"> <table><tbody>'+t[0]+'</tbody></table></div><div id="grid_'+this.name+'_columns" class="w2ui-grid-columns"> <table><tbody>'+t[1]+"</tbody></table></div>"+`<div class="w2ui-intersection-marker" style="display: none; height: ${this.recordHeight-5}px">
<div class="top-marker"></div>
<div class="bottom-marker"></div>
</div>`;let l=query(this.box).find(`#grid_${this.name}_body`,this.box).html(e);t=query(this.box).find(`#grid_${this.name}_records`,this.box),e=query(this.box).find(`#grid_${this.name}_frecords`,this.box);"row"==this.selectType&&(t.on("mouseover mouseout",{delegate:"tr"},e=>{var t=query(e.delegate).attr("recid");query(this.box).find(`#grid_${this.name}_frec_`+w2utils.escapeId(t)).toggleClass("w2ui-record-hover","mouseover"==e.type)}),e.on("mouseover mouseout",{delegate:"tr"},e=>{var t=query(e.delegate).attr("recid");query(this.box).find(`#grid_${this.name}_rec_`+w2utils.escapeId(t)).toggleClass("w2ui-record-hover","mouseover"==e.type)})),w2utils.isIOS?t.append(e).on("click",{delegate:"tr"},e=>{var t=query(e.delegate).attr("recid");this.dblClick(t,e)}):t.add(e).on("click",{delegate:"tr"},e=>{var t=query(e.delegate).attr("recid");"-none-"!=t&&this.click(t,e)}).on("contextmenu",{delegate:"tr"},e=>{var t=query(e.delegate).attr("recid"),i=query(e.target).closest("td"),i=parseInt(i.attr("col")??-1);this.showContextMenu(t,i,e)}).on("mouseover",{delegate:"tr"},e=>{this.last.rec_out=!1;let t=query(e.delegate).attr("index"),i=query(e.delegate).attr("recid");t!==this.last.rec_over&&(this.last.rec_over=t,setTimeout(()=>{delete this.last.rec_out,this.trigger("mouseEnter",{target:this.name,originalEvent:e,index:t,recid:i}).finish()}))}).on("mouseout",{delegate:"tr"},t=>{let i=query(t.delegate).attr("index"),s=query(t.delegate).attr("recid");this.last.rec_out=!0,setTimeout(()=>{let e=()=>{this.trigger("mouseLeave",{target:this.name,originalEvent:t,index:i,recid:s}).finish()};i!==this.last.rec_over&&e(),setTimeout(()=>{this.last.rec_out&&(delete this.last.rec_out,delete this.last.rec_over,e())})})}),l.data("scroll",{lastDelta:0,lastTime:0}).find(".w2ui-grid-frecords").on("mousewheel DOMMouseScroll ",e=>{e.preventDefault();var t=l.data("scroll"),i=l.find(".w2ui-grid-records"),e=null!=typeof e.wheelDelta?-e.wheelDelta:e.detail||e.deltaY,s=i.prop("scrollTop");t.lastDelta+=e,e=Math.round(t.lastDelta),l.data("scroll",t),i.get(0).scroll({top:s+e,behavior:"smooth"})}),t.off(".body-global").on("scroll.body-global",{delegate:".w2ui-grid-records"},e=>{this.scroll(e)}),query(this.box).find(".w2ui-grid-body").off(".body-global").on("click.body-global dblclick.body-global contextmenu.body-global",{delegate:"td.w2ui-head"},e=>{var t=query(e.delegate).attr("col"),i=this.columns[t]??{field:t};switch(e.type){case"click":this.columnClick(i.field,e);break;case"dblclick":this.columnDblClick(i.field,e);break;case"contextmenu":this.columnContextMenu(i.field,e)}}).on("mouseover.body-global",{delegate:".w2ui-col-header"},e=>{let t=query(e.delegate).parent().attr("col");this.columnTooltipShow(t,e),query(e.delegate).off(".tooltip").on("mouseleave.tooltip",()=>{this.columnTooltipHide(t,e)})}).on("click.body-global",{delegate:"input.w2ui-select-all"},e=>{e.delegate.checked?this.selectAll():this.selectNone(),e.stopPropagation(),clearTimeout(this.last.kbd_timer)}).on("click.body-global",{delegate:".w2ui-show-children, .w2ui-col-expand"},e=>{e.stopPropagation(),this.toggle(query(e.target).parents("tr").attr("recid"))}).on("click.body-global mouseover.body-global",{delegate:".w2ui-info"},e=>{var t=query(e.delegate).closest("td"),i=t.parent(),s=this.columns[t.attr("col")],l=i.parents(".w2ui-grid-body").hasClass("w2ui-grid-summary");["mouseenter","mouseover"].includes(s.info?.showOn?.toLowerCase())&&"mouseover"==e.type?this.showBubble(i.attr("index"),t.attr("col"),l).then(()=>{query(e.delegate).off(".tooltip").on("mouseleave.tooltip",()=>{w2tooltip.hide(this.name+"-bubble")})}):"click"==e.type&&(w2tooltip.hide(this.name+"-bubble"),this.showBubble(i.attr("index"),t.attr("col"),l))}).on("mouseover.body-global",{delegate:".w2ui-clipboard-copy"},l=>{if(!l.delegate._tooltipShow){let t=query(l.delegate).parent(),i=t.parent();var e=this.columns[t.attr("col")];let s=i.parents(".w2ui-grid-body").hasClass("w2ui-grid-summary");w2tooltip.show({name:this.name+"-bubble",anchor:l.delegate,html:w2utils.lang("string"==typeof e.clipboardCopy?e.clipboardCopy:"Copy to clipboard"),position:"top|bottom",offsetY:-2}).hide(e=>{l.delegate._tooltipShow=!1,query(l.delegate).off(".tooltip")}),query(l.delegate).off(".tooltip").on("mouseleave.tooltip",e=>{w2tooltip.hide(this.name+"-bubble")}).on("click.tooltip",e=>{e.stopPropagation(),w2tooltip.update(this.name+"-bubble",w2utils.lang("Copied")),this.clipboardCopy(i.attr("index"),t.attr("col"),s)}),l.delegate._tooltipShow=!0}}).on("click.body-global",{delegate:".w2ui-editable-checkbox"},e=>{var t=query(e.delegate).data();this.editChange.call(this,e.delegate,t.changeind,t.colind,e),this.updateToolbar()}),0===this.records.length&&this.msgEmpty?query(this.box).find(`#grid_${this.name}_body`).append(`<div id="grid_${this.name}_empty_msg" class="w2ui-grid-empty-msg"><div>${w2utils.lang(this.msgEmpty)}</div></div>`):0<query(this.box).find(`#grid_${this.name}_empty_msg`).length&&query(this.box).find(`#grid_${this.name}_empty_msg`).remove(),0<this.summary.length?(e=this.getSummaryHTML(),query(this.box).find(`#grid_${this.name}_fsummary`).html(e[0]).show(),query(this.box).find(`#grid_${this.name}_summary`).html(e[1]).show()):(query(this.box).find(`#grid_${this.name}_fsummary`).hide(),query(this.box).find(`#grid_${this.name}_summary`).hide())}render(e){var i=Date.now();let p=this;"string"==typeof e&&(e=query(e).get(0));var s=this.trigger("render",{target:this.name,box:e??this.box});if(!0!==s.isCancelled&&(null!=e&&(0<query(this.box).find(`#grid_${this.name}_body`).length&&query(this.box).removeAttr("name").removeClass("w2ui-reset w2ui-grid w2ui-inactive").html(""),this.box=e),this.box)){e="object"!=typeof this.url?this.url:this.url.get;if(this.reset(!0),!this.last.field)if(this.multiSearch&&this.show.searchAll)this.last.field="all",this.last.label="All Fields";else{let e=0;for(;e<this.searches.length&&(this.searches[e].hidden||!1===this.searches[e].simple);)e++;e>=this.searches.length?(this.last.field="",this.last.label=""):(this.last.field=this.searches[e].field,this.last.label=this.searches[e].label)}if(query(this.box).attr("name",this.name).addClass("w2ui-reset w2ui-grid w2ui-inactive").html('<div class="w2ui-grid-box"> <div id="grid_'+this.name+'_header" class="w2ui-grid-header"></div> <div id="grid_'+this.name+'_toolbar" class="w2ui-grid-toolbar"></div> <div id="grid_'+this.name+'_body" class="w2ui-grid-body"></div> <div id="grid_'+this.name+'_fsummary" class="w2ui-grid-body w2ui-grid-summary"></div> <div id="grid_'+this.name+'_summary" class="w2ui-grid-body w2ui-grid-summary"></div> <div id="grid_'+this.name+'_footer" class="w2ui-grid-footer"></div> <textarea id="grid_'+this.name+'_focus" class="w2ui-grid-focus-input" '+(this.tabIndex?'tabindex="'+this.tabIndex+'"':"")+(w2utils.isIOS?"readonly":"")+"></textarea></div>"),"row"!=this.selectType&&query(this.box).addClass("w2ui-ss"),0<query(this.box).length&&(query(this.box)[0].style.cssText+=this.style),this.initToolbar(),null!=this.toolbar&&this.toolbar.render(query(this.box).find("#grid_"+this.name+"_toolbar")[0]),this.last.toolbar_height=query(this.box).find(`#grid_${this.name}_toolbar`).prop("offsetHeight"),this.last.field&&"all"!=this.last.field){let e=this.searchData;setTimeout(()=>{this.searchInitInput(this.last.field,1==e.length?e[0].value:null)},1)}query(this.box).find(`#grid_${this.name}_footer`).html(this.getFooterHTML()),this.last.state||(this.last.state=this.stateSave(!0)),this.stateRestore(),e&&(this.clear(),this.refresh());let t=!1;for(let e=0;e<this.searches.length;e++)if(this.searches[e].hidden){t=!0;break}t?(this.searchReset(!1),e||setTimeout(()=>{this.searchReset()},1)):this.reload(),query(this.box).find(`#grid_${this.name}_focus`).on("focus",e=>{clearTimeout(this.last.kbd_timer),this.hasFocus||this.focus()}).on("blur",e=>{clearTimeout(this.last.kbd_timer),this.last.kbd_timer=setTimeout(()=>{this.hasFocus&&this.blur()},100)}).on("paste",i=>{var s=i.clipboardData||null;if(s){let e=s.items,t=[];for(var l in e=2==e.length&&2==(e=2==e.length&&"file"==e[1].kind?[e[1]]:e).length&&"text/plain"==e[0].type&&"text/html"==e[1].type?[e[1]]:e){l=e[l];if("file"===l.kind){var r=l.getAsFile();t.push({kind:"file",data:r})}else if("string"===l.kind&&("text/plain"===l.type||"text/html"===l.type)){i.preventDefault();let e=s.getData("text/plain");-1!=e.indexOf("\r")&&-1==e.indexOf("\n")&&(e=e.replace(/\r/g,"\n")),t.push({kind:"text/html"==l.type?"html":"text",data:e})}}1===t.length&&"file"!=t[0].kind&&(t=t[0].data),w2ui[this.name].paste(t,i),i.preventDefault()}}).on("keydown",function(e){w2ui[p.name].keydown.call(w2ui[p.name],e)});let c;return query(this.box).off("mousedown.mouseStart").on("mousedown.mouseStart",function(l){if(1==l.which&&("text"==p.last.userSelect&&(p.last.userSelect="",query(p.box).find(".w2ui-grid-body").css("user-select","none")),!("row"==p.selectType&&(query(l.target).parents().hasClass("w2ui-head")||query(l.target).hasClass("w2ui-head"))||p.last.move&&"expand"==p.last.move.type))){if(l.altKey)query(p.box).find(".w2ui-grid-body").css("user-select","text"),p.selectNone(),p.last.move={type:"text-select"},p.last.userSelect="text";else{let e=l.target;var r={x:l.offsetX-10,y:l.offsetY-10};let t=!1;for(;e&&(!e.classList||!e.classList.contains("w2ui-grid"));)e.tagName&&"TD"==e.tagName.toUpperCase()&&(t=!0),e.tagName&&"TR"!=e.tagName.toUpperCase()&&1==t&&(r.x+=e.offsetLeft,r.y+=e.offsetTop),e=e.parentNode;p.last.move={x:l.screenX,y:l.screenY,divX:0,divY:0,focusX:r.x,focusY:r.y,recid:query(l.target).parents("tr").attr("recid"),column:parseInt(("TD"==l.target.tagName.toUpperCase()?query(l.target):query(l.target).parents("td")).attr("col")),type:"select",ghost:!1,start:!0},null==p.last.move.recid&&(p.last.move.type="select-column");let i=l.target,s=query(p.box).find("#grid_"+p.name+"_focus");if(p.last.move){let e=p.last.move.focusX,t=p.last.move.focusY;var n=query(i).parents("table").parent();(n.hasClass("w2ui-grid-records")||n.hasClass("w2ui-grid-frecords")||n.hasClass("w2ui-grid-columns")||n.hasClass("w2ui-grid-fcolumns")||n.hasClass("w2ui-grid-summary"))&&(e=p.last.move.focusX-query(p.box).find("#grid_"+p.name+"_records").prop("scrollLeft"),t=p.last.move.focusY-query(p.box).find("#grid_"+p.name+"_records").prop("scrollTop")),(query(i).hasClass("w2ui-grid-footer")||0<query(i).parents("div.w2ui-grid-footer").length)&&(t=query(p.box).find("#grid_"+p.name+"_footer").get(0).offsetTop),n.hasClass("w2ui-scroll-wrapper")&&n.parent().hasClass("w2ui-toolbar")&&(e=p.last.move.focusX-n.prop("scrollLeft")),s.css({left:e-10,top:t})}setTimeout(()=>{p.last.inEditMode||(["INPUT","TEXTAREA","SELECT"].includes(i.tagName)?i.focus():s.get(0)!==document.active&&s.get(0)?.focus({preventScroll:!0}))},50),p.multiSelect||p.reorderRows||"drag"!=p.last.move.type||delete p.last.move}if(1==p.reorderRows){let e=l.target;var t,i,s,a;"TD"!=e.tagName.toUpperCase()&&(e=query(e).parents("td")[0]),query(e).hasClass("w2ui-col-number")||query(e).hasClass("w2ui-col-order")?(p.selectNone(),p.last.move.reorder=!0,n=query(p.box).find(".w2ui-even.w2ui-empty-record").css("background-color"),t=query(p.box).find(".w2ui-odd.w2ui-empty-record").css("background-color"),query(p.box).find(".w2ui-even td").filter(":not(.w2ui-col-number)").css("background-color",n),query(p.box).find(".w2ui-odd td").filter(":not(.w2ui-col-number)").css("background-color",t),t=p.last.move,i=query(p.box).find(".w2ui-grid-records"),t.ghost||(s=query(p.box).find(`#grid_${p.name}_rec_`+t.recid),a=s.parents("table").find("tr:first-child").get(0).cloneNode(!0),t.offsetY=l.offsetY,t.from=t.recid,t.pos={top:s.get(0).offsetTop-1,left:s.get(0).offsetLeft},t.ghost=query(s.get(0).cloneNode(!0)),t.ghost.removeAttr("id"),t.ghost.find("td").css({"border-top":"1px solid silver","border-bottom":"1px solid silver"}),s.find("td").remove(),s.append(`<td colspan="1000"><div class="w2ui-reorder-empty" style="height: ${p.recordHeight-2}px"></div></td>`),i.append('<div id="grid_'+p.name+'_ghost_line" style="position: absolute; z-index: 999999; pointer-events: none; width: 100%;"></div>'),i.append('<table id="grid_'+p.name+'_ghost" style="position: absolute; z-index: 999998; opacity: 0.9; pointer-events: none;"></table>'),query(p.box).find("#grid_"+p.name+"_ghost").append(a).append(t.ghost)),query(p.box).find("#grid_"+p.name+"_ghost").css({top:t.pos.top+"px",left:t.pos.left+"px"})):p.last.move.reorder=!1}query(document).on("mousemove.w2ui-"+p.name,o).on("mouseup.w2ui-"+p.name,h),l.stopPropagation()}}),this.updateToolbar(),s.finish(),this.last.observeResize=new ResizeObserver(()=>{this.resize()}),this.last.observeResize.observe(this.box),Date.now()-i;function o(t){if(t.target.tagName){var r=p.last.move;if(r&&-1!=["select","select-column"].indexOf(r.type)&&(r.divX=t.screenX-r.x,r.divY=t.screenY-r.y,!(Math.abs(r.divX)<=1&&Math.abs(r.divY)<=1)))if(p.last.cancelClick=!0,1==p.reorderRows&&p.last.move.reorder){let e=query(t.target).parents("tr").attr("recid");(e="-none-"==e?"bottom":e)!=r.from&&(a=query(p.box).find("#grid_"+p.name+"_rec_"+e),query(p.box).find(".insert-before"),a.addClass("insert-before"),r.lastY=t.screenY,r.to=e,a={top:a.get(0)?.offsetTop,left:a.get(0)?.offsetLeft},query(p.box).find("#grid_"+p.name+"_ghost_line").css({top:a.top+"px",left:r.pos.left+"px","border-top":"2px solid #769EFC"})),void query(p.box).find("#grid_"+p.name+"_ghost").css({top:r.pos.top+r.divY+"px",left:r.pos.left+"px"})}else{r.start&&r.recid&&(p.selectNone(),r.start=!1);var n=[],a=("TR"==t.target.tagName.toUpperCase()?query(t.target):query(t.target).parents("tr")).attr("recid");if(null==a){if("row"!=p.selectType&&(!p.last.move||"select"!=p.last.move.type)){var o=parseInt(query(t.target).parents("td").attr("col"));if(isNaN(o))p.removeRange("column-selection"),query(p.box).find(".w2ui-grid-columns .w2ui-col-header, .w2ui-grid-fcolumns .w2ui-col-header").removeClass("w2ui-col-selected"),query(p.box).find(".w2ui-col-number").removeClass("w2ui-row-selected"),delete r.colRange;else{let e=o+"-"+o;r.column<o&&(e=r.column+"-"+o);var i=[],s=(e=r.column>o?o+"-"+r.column:e).split("-");for(let e=parseInt(s[0]);e<=parseInt(s[1]);e++)i.push(e);if(r.colRange!=e&&!0!==(c=p.trigger("columnSelect",{target:p.name,columns:i})).isCancelled){null==r.colRange&&p.selectNone();var l=e.split("-");query(p.box).find(".w2ui-grid-columns .w2ui-col-header, .w2ui-grid-fcolumns .w2ui-col-header").removeClass("w2ui-col-selected");for(let e=parseInt(l[0]);e<=parseInt(l[1]);e++)query(p.box).find("#grid_"+p.name+"_column_"+e+" .w2ui-col-header").addClass("w2ui-col-selected");query(p.box).find(".w2ui-col-number").not(".w2ui-head").addClass("w2ui-row-selected"),r.colRange=e,p.removeRange("column-selection"),p.addRange({name:"column-selection",range:[{recid:p.records[0].recid,column:l[0]},{recid:p.records[p.records.length-1].recid,column:l[1]}],style:"background-color: rgba(90, 145, 234, 0.1)"})}}}}else{let l=p.get(r.recid,!0);if(!(null==l||p.records[l]&&p.records[l].recid!=r.recid)){let e=p.get(a,!0);if(null!=e){let i=parseInt(r.column),s=parseInt(("TD"==t.target.tagName.toUpperCase()?query(t.target):query(t.target).parents("td")).attr("col"));isNaN(i)&&isNaN(s)&&(i=0,s=p.columns.length-1),l>e&&(o=l,l=e,e=o);var h,a="ind1:"+l+",ind2;"+e+",col1:"+i+",col2:"+s;if(r.range!=a){r.range=a;for(let t=l;t<=e;t++)if(!(0<p.last.searchIds.length&&-1==p.last.searchIds.indexOf(t)))if("row"!=p.selectType){i>s&&(h=i,i=s,s=h);for(let e=i;e<=s;e++)p.columns[e].hidden||n.push({recid:p.records[t].recid,column:parseInt(e)})}else n.push(p.records[t].recid);if("row"!=p.selectType){var d=p.getSelection();let e=[];for(let i=0;i<n.length;i++){let t=!1;for(let e=0;e<d.length;e++)n[i].recid==d[e].recid&&n[i].column==d[e].column&&(t=!0);t||e.push({recid:n[i].recid,column:n[i].column})}p.select(e),e=[];for(let i=0;i<d.length;i++){let t=!1;for(let e=0;e<n.length;e++)n[e].recid==d[i].recid&&n[e].column==d[i].column&&(t=!0);t||e.push({recid:d[i].recid,column:d[i].column})}p.unselect(e)}else if(p.multiSelect){var u=p.getSelection();for(let e=0;e<n.length;e++)-1==u.indexOf(n[e])&&p.select(n[e]);for(let e=0;e<u.length;e++)-1==n.indexOf(u[e])&&p.unselect(u[e])}}}}}}}}function h(t){var i=p.last.move;if(setTimeout(()=>{delete p.last.cancelClick},1),!query(t.target).parents().hasClass(".w2ui-head")&&!query(t.target).hasClass(".w2ui-head")){if(i&&-1!=["select","select-column"].indexOf(i.type)){if(null!=i.colRange&&!0!==c.isCancelled){var s=i.colRange.split("-"),l=[];for(let e=0;e<p.records.length;e++){var r=[];for(let e=parseInt(s[0]);e<=parseInt(s[1]);e++)r.push(e);l.push({recid:p.records[e].recid,column:r})}p.removeRange("column-selection"),c.finish(),p.select(l)}if(1==p.reorderRows&&p.last.move.reorder)if(null!=i.to){t=p.trigger("reorderRow",{target:p.name,recid:i.from,moveBefore:i.to});if(!0===t.isCancelled)return a(),void delete p.last.move;var n=p.get(i.from,!0);let e=p.get(i.to,!0);"bottom"==i.to&&(e=p.records.length);i=p.records[n];null!=n&&null!=e&&(p.records.splice(n,1),n>e?p.records.splice(e,0,i):p.records.splice(e-1,0,i)),p.sortData=[],query(p.box).find(`#grid_${p.name}_columns .w2ui-col-header`).removeClass("w2ui-col-sorted"),a(),t.finish()}else a()}delete p.last.move,query(document).off(".w2ui-"+p.name)}}function a(){query(p.box).find(`#grid_${p.name}_ghost`).remove(),query(p.box).find(`#grid_${p.name}_ghost_line`).remove(),p.refresh(),delete p.last.move}}}destroy(){var e=this.trigger("destroy",{target:this.name});!0!==e.isCancelled&&(query(this.box).off(),"object"==typeof this.toolbar&&this.toolbar.destroy&&this.toolbar.destroy(),0<query(this.box).find(`#grid_${this.name}_body`).length&&query(this.box).removeAttr("name").removeClass("w2ui-reset w2ui-grid w2ui-inactive").html(""),this.last.observeResize?.disconnect(),delete w2ui[this.name],e.finish())}initColumnOnOff(){var e,i=[{id:"line-numbers",text:"Line #",checked:this.show.lineNumbers}];for(let t=0;t<this.columns.length;t++){var s=this.columns[t];let e=this.columns[t].text;!1!==s.hideable&&(e=(e=!e&&this.columns[t].tooltip?this.columns[t].tooltip:e)||"- column "+(parseInt(t)+1)+" -",i.push({id:s.field,text:w2utils.stripTags(e),checked:!s.hidden}))}(("object"!=typeof this.url?this.url:this.url.get)&&this.show.skipRecords||this.show.saveRestoreState)&&i.push({text:"--"}),this.show.skipRecords&&(e=w2utils.lang("Skip")+`<input id="${this.name}_skip" type="text" class="w2ui-input w2ui-grid-skip" value="${this.offset}">`+w2utils.lang("records"),i.push({id:"w2ui-skip",text:e,group:!1,icon:"w2ui-icon-empty"})),this.show.saveRestoreState&&i.push({id:"w2ui-stateSave",text:w2utils.lang("Save Grid State"),icon:"w2ui-icon-empty",group:!1},{id:"w2ui-stateReset",text:w2utils.lang("Restore Default State"),icon:"w2ui-icon-empty",group:!1});let t=[];return i.forEach(e=>{e.text=w2utils.lang(e.text),e.checked&&t.push(e.id)}),this.toolbar.set("w2ui-column-on-off",{selected:t,items:i}),i}initColumnDrag(e){if(this.columnGroups&&this.columnGroups.length)throw"Draggable columns are not currently supported with column groups.";let r=this,n={pressed:!1,targetPos:null,columnHead:null},a=(t,e)=>{var i=["w2ui-col-number","w2ui-col-expand","w2ui-col-select"];!0!==e&&i.push("w2ui-head-last");for(let e=0;e<i.length;e++)if(query(t).closest(".w2ui-head").hasClass(i[e]))return!0;return!1};function o(e){var t,i,s,l;n.pressed&&n.columnHead&&(t=e.pageX,i=e.pageY,a(e.target,!0)||(e=e,0!=query(e.target).closest("td").length&&(l=query(r.box).find(".w2ui-grid-body").get(0).getBoundingClientRect(),s=query(e.target).closest("td").get(0).getBoundingClientRect(),query(r.box).find(".w2ui-intersection-marker").show().css({left:s.left-l.left+"px"}),s=query(e.target).closest("td"),n.targetPos=s.hasClass("w2ui-head-last")?r.columns.length:parseInt(s.attr("col")))),l=t,e=i,query(n.ghost).css({left:l-10+"px",top:e-10+"px"}).show())}function h(e){if(n.pressed&&n.columnHead){n.pressed=!1;var t,i,s=()=>{var e=query(r.box).find(".w2ui-grid-ghost");query(r.box).find(".w2ui-intersection-marker").hide(),query(n.ghost).remove(),e.remove(),query(document).off(".colDrag"),n={}};if(e.pageX==n.initialX&&e.pageY==n.initialY)r.columnClick(r.columns[n.originalPos].field,e),s();else{if(!0===(e=r.trigger("columnDragEnd",{originalEvent:e,target:n.columnHead[0],dragData:n})).isCancelled)return!1;t=r.columns[n.originalPos],i=r.columns,n.originalPos!=n.targetPos&&null!=n.targetPos&&(i.splice(n.targetPos,0,w2utils.clone(t)),i.splice(i.indexOf(t),1)),s(),r.refresh(),e.finish({targetColumn:NaN})}}}return query(r.box).off(".colDrag").on("mousedown.colDrag",function(e){if(!n.pressed&&0!==n.numberPreColumnsPresent&&0===e.button){var i,t;if(query(e.target).parents().hasClass("w2ui-head")&&!a(e.target)){if(n.pressed=!0,n.initialX=e.pageX,n.initialY=e.pageY,n.numberPreColumnsPresent=query(r.box).find(".w2ui-head.w2ui-col-number, .w2ui-head.w2ui-col-expand, .w2ui-head.w2ui-col-select").length,n.columnHead=s=query(e.target).closest(".w2ui-head"),n.originalPos=t=parseInt(s.attr("col"),10),!0===(t=r.trigger("columnDragStart",{originalEvent:e,origColumnNumber:t,target:s[0]})).isCancelled)return!1;i=n.columns=query(r.box).find(".w2ui-head:not(.w2ui-head-last)"),query(document).on("mouseup.colDrag",h),query(document).on("mousemove.colDrag",o);var s=r.columns[n.originalPos],s=w2utils.lang("function"==typeof s.text?s.text(s):s.text);n.ghost=query.html(`<span col="${n.originalPos}">${s}</span>`)[0],query(document.body).append(n.ghost),query(n.ghost).css({display:"none",left:e.pageX,top:e.pageY,opacity:1,margin:"3px 0 0 20px",padding:"3px","background-color":"white",position:"fixed","z-index":999999}).addClass(".w2ui-grid-ghost"),n.offsets=[];for(let e=0,t=i.length;e<t;e++){var l=i[e].getBoundingClientRect();n.offsets.push(l.left)}t.finish()}}}),{remove(){query(r.box).off(".colDrag"),r.last.columnDrag=!1}}}columnOnOff(e,t){e=this.trigger("columnOnOff",{target:this.name,field:t,originalEvent:e});if(!0!==e.isCancelled){var i=this.find({"w2ui.expanded":!0},!0);for(let e=0;e<i.length;e++){var s=this.records[e].w2ui;s&&!Array.isArray(s.children)&&(this.records[e].w2ui.expanded=!1)}"line-numbers"==t?(this.show.lineNumbers=!this.show.lineNumbers,this.refresh()):(t=this.getColumn(t)).hidden?this.showColumn(t.field):this.hideColumn(t.field),e.finish()}}initToolbar(){if(null==this.toolbar.render){let e=this.toolbar.items||[];var t;this.toolbar.items=[],this.toolbar=new w2toolbar(w2utils.extend({},this.toolbar,{name:this.name+"_toolbar",owner:this})),this.show.toolbarReload&&this.toolbar.items.push(w2utils.extend({},this.buttons.reload)),this.show.toolbarColumns&&this.toolbar.items.push(w2utils.extend({},this.buttons.columns)),this.show.toolbarSearch&&(t=`
<div class="w2ui-grid-search-input">
${this.buttons.search.html}
<div id="grid_${this.name}_search_name" class="w2ui-grid-search-name">
<span class="name-icon w2ui-icon-search"></span>
<span class="name-text"></span>
<span class="name-cross w2ui-action" data-click="searchReset">x</span>
</div>
<input type="text" id="grid_${this.name}_search_all" class="w2ui-search-all" tabindex="-1"
autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"
placeholder="${w2utils.lang(this.last.label,!0)}" value="${this.last.search}"
data-focus="searchSuggest" data-click="stop"
>
<div class="w2ui-search-drop w2ui-action" data-click="searchOpen"
style="${this.multiSearch?"":"display: none"}">
<span class="w2ui-icon-drop"></span>
</div>
</div>`,this.toolbar.items.push({id:"w2ui-search",type:"html",html:t,onRefresh:async e=>{await e.complete;var e=query(this.box).find(`#grid_${this.name}_search_all`),t=(w2utils.bindEvents(query(this.box).find(`#grid_${this.name}_search_all, .w2ui-action`),this),w2utils.debounce(e=>{var t=e.target.value;this.liveSearch&&this.last.liveText!=t&&(this.last.liveText=t,this.search(this.last.field,t)),40==e.keyCode&&this.searchSuggest(!0)},250));e.on("change",e=>{this.liveSearch||(this.search(this.last.field,e.target.value),this.searchSuggest(!0,!0,this))}).on("blur",()=>{this.last.liveText=""}).on("keyup",t)}})),Array.isArray(e)&&(t=e.map(e=>e.id),this.show.toolbarAdd&&!t.includes(this.buttons.add.id)&&this.toolbar.items.push(w2utils.extend({},this.buttons.add)),this.show.toolbarEdit&&!t.includes(this.buttons.edit.id)&&this.toolbar.items.push(w2utils.extend({},this.buttons.edit)),this.show.toolbarDelete&&!t.includes(this.buttons.delete.id)&&this.toolbar.items.push(w2utils.extend({},this.buttons.delete)),this.show.toolbarSave&&!t.includes(this.buttons.save.id)&&((this.show.toolbarAdd||this.show.toolbarDelete||this.show.toolbarEdit)&&this.toolbar.items.push({type:"break",id:"w2ui-break2"}),this.toolbar.items.push(w2utils.extend({},this.buttons.save))),e=e.map(e=>this.buttons[e.name]?w2utils.extend({},this.buttons[e.name],e):e)),this.toolbar.items.push(...e),this.toolbar.on("click",e=>{var i=this.trigger("toolbar",{target:e.target,originalEvent:e});if(!0!==i.isCancelled){let t;switch(e.detail.item.id){case"w2ui-reload":if(!0===(t=this.trigger("reload",{target:this.name})).isCancelled)return!1;this.reload(),t.finish();break;case"w2ui-column-on-off":e.detail.subItem?(s=e.detail.subItem.id,["w2ui-stateSave","w2ui-stateReset"].includes(s)?this[s.substring(5)]():"w2ui-skip"!=s&&this.columnOnOff(e,e.detail.subItem.id)):(this.initColumnOnOff(),setTimeout(()=>{query(`#w2overlay-${this.name}_toolbar-drop .w2ui-grid-skip`).off(".w2ui-grid").on("click.w2ui-grid",e=>{e.stopPropagation()}).on("keypress",e=>{13==e.keyCode&&(this.skip(e.target.value),this.toolbar.click("w2ui-column-on-off"))})},100));break;case"w2ui-add":if(!0===(t=this.trigger("add",{target:this.name,recid:null})).isCancelled)return!1;t.finish();break;case"w2ui-edit":{var s=this.getSelection();let e=null;if(1==s.length&&(e=s[0]),!0===(t=this.trigger("edit",{target:this.name,recid:e})).isCancelled)return!1;t.finish();break}case"w2ui-delete":this.delete();break;case"w2ui-save":this.save()}i.finish()}}),this.toolbar.on("refresh",e=>{if("w2ui-search"==e.target){let e=this.searchData;setTimeout(()=>{this.searchInitInput(this.last.field,1==e.length?e[0].value:null)},1)}})}}initResize(){let r=this;query(this.box).find(".w2ui-resizer").off(".grid-col-resize").on("click.grid-col-resize",function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,e.preventDefault&&e.preventDefault()}).on("mousedown.grid-col-resize",function(e){e=e||window.event,r.last.colResizing=!0,r.last.tmp={x:e.screenX,y:e.screenY,gx:e.screenX,gy:e.screenY,col:parseInt(query(this).attr("name"))},r.last.tmp.tds=query(r.box).find("#grid_"+r.name+'_body table tr:first-child td[col="'+r.last.tmp.col+'"]'),e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,e.preventDefault&&e.preventDefault();for(let e=0;e<r.columns.length;e++)r.columns[e].hidden||(null==r.columns[e].sizeOriginal&&(r.columns[e].sizeOriginal=r.columns[e].size),r.columns[e].size=r.columns[e].sizeCalculated);let i={phase:"before",type:"columnResize",target:r.name,column:r.last.tmp.col,field:r.columns[r.last.tmp.col].field};i=r.trigger(w2utils.extend(i,{resizeBy:0,originalEvent:e}));let s;query(document).off(".grid-col-resize").on("mousemove.grid-col-resize",function(e){var t;1==r.last.colResizing&&(e=e||window.event,!0===(i=r.trigger(w2utils.extend(i,{resizeBy:e.screenX-r.last.tmp.gx,originalEvent:e}))).isCancelled?i.isCancelled=!1:(r.last.tmp.x=e.screenX-r.last.tmp.x,r.last.tmp.y=e.screenY-r.last.tmp.y,t=parseInt(r.columns[r.last.tmp.col].size)+r.last.tmp.x+"px",r.columns[r.last.tmp.col].size=t,s&&clearTimeout(s),s=setTimeout(()=>{r.resizeRecords(),r.scroll()},100),r.last.tmp.tds.css({width:t}),r.last.tmp.x=e.screenX,r.last.tmp.y=e.screenY))}).on("mouseup.grid-col-resize",function(e){query(document).off(".grid-col-resize"),r.resizeRecords(),r.scroll(),i.finish({originalEvent:e}),setTimeout(()=>{r.last.colResizing=!1},1)})}).on("dblclick.grid-col-resize",function(e){let t=parseInt(query(this).attr("name")),i=r.columns[t],s=0;if(!1===i.autoResize)return!0;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,e.preventDefault&&e.preventDefault(),query(r.box).find('.w2ui-grid-records td[col="'+t+'"] > div',r.box).each(()=>{var e=this.offsetWidth-this.scrollWidth;e<s&&(s=e-3)});var l={phase:"before",type:"columnAutoResize",target:r.name,column:i,field:i.field};!0===(l=r.trigger(w2utils.extend(l,{resizeBy:Math.abs(s),originalEvent:e}))).isCancelled?l.isCancelled=!1:(s<0&&(i.size=Math.min(parseInt(i.size)+Math.abs(s),i.max||1/0)+"px",r.resizeRecords(),r.resizeRecords(),r.scroll()),l.finish({originalEvent:e}))}).each(e=>{var t=query(e).get(0).parentNode;query(e).css({height:t.clientHeight+"px","margin-left":t.clientWidth-3+"px"})})}resizeBoxes(){var e=query(this.box).find(`#grid_${this.name}_header`),t=query(this.box).find(`#grid_${this.name}_toolbar`),i=query(this.box).find(`#grid_${this.name}_fsummary`),s=query(this.box).find(`#grid_${this.name}_summary`),l=query(this.box).find(`#grid_${this.name}_footer`),r=query(this.box).find(`#grid_${this.name}_body`);this.show.header&&e.css({top:"0px",left:"0px",right:"0px"}),this.show.toolbar&&t.css({top:0+(this.show.header?w2utils.getSize(e,"height"):0)+"px",left:"0px",right:"0px"}),0<this.summary.length&&(i.css({bottom:0+(this.show.footer?w2utils.getSize(l,"height"):0)+"px"}),s.css({bottom:0+(this.show.footer?w2utils.getSize(l,"height"):0)+"px",right:"0px"})),this.show.footer&&l.css({bottom:"0px",left:"0px",right:"0px"}),r.css({top:0+(this.show.header?w2utils.getSize(e,"height"):0)+(this.show.toolbar?w2utils.getSize(t,"height"):0)+"px",bottom:0+(this.show.footer?w2utils.getSize(l,"height"):0)+(0<this.summary.length?w2utils.getSize(s,"height"):0)+"px",left:"0px",right:"0px"})}resizeRecords(){let i=this;query(this.box).find(".w2ui-empty-record").remove();var t,e,s=query(this.box),l=query(this.box).find(":scope > div.w2ui-grid-box"),r=query(this.box).find(`#grid_${this.name}_header`),n=query(this.box).find(`#grid_${this.name}_toolbar`),a=query(this.box).find(`#grid_${this.name}_summary`),o=query(this.box).find(`#grid_${this.name}_fsummary`),h=query(this.box).find(`#grid_${this.name}_footer`),d=query(this.box).find(`#grid_${this.name}_body`),u=query(this.box).find(`#grid_${this.name}_columns`),c=query(this.box).find(`#grid_${this.name}_fcolumns`),p=query(this.box).find(`#grid_${this.name}_records`),f=query(this.box).find(`#grid_${this.name}_frecords`),m=query(this.box).find(`#grid_${this.name}_scroll1`);let g=8*String(this.total).length+10,y=(g<34&&(g=34),null!=this.lineNumberWidth&&(g=this.lineNumberWidth),!1),w=!1,b=0;for(let e=0;e<this.columns.length;e++)this.columns[e].frozen||this.columns[e].hidden||(t=parseInt(this.columns[e].sizeCalculated||this.columns[e].size),b+=t);p[0]?.clientWidth<b&&(y=!0),d[0]?.clientHeight-(u[0]?.clientHeight??0)<(query(p).find(":scope > table")[0]?.clientHeight??0)+(y?w2utils.scrollBarSize():0)&&(w=!0),this.fixedBody?(e=l[0]?.clientHeight-(this.show.header?w2utils.getSize(r,"height"):0)-(this.show.toolbar?w2utils.getSize(n,"height"):0)-("none"!=a.css("display")?w2utils.getSize(a,"height"):0)-(this.show.footer?w2utils.getSize(h,"height"):0),d.css("height",e+"px")):(r=(e=w2utils.getSize(u,"height")+w2utils.getSize(query(this.box).find("#grid_"+this.name+"_records table"),"height")+(y?w2utils.scrollBarSize():0))+(this.show.header?w2utils.getSize(r,"height"):0)+(this.show.toolbar?w2utils.getSize(n,"height"):0)+("none"!=a.css("display")?w2utils.getSize(a,"height"):0)+(this.show.footer?w2utils.getSize(h,"height"):0),l.css("height",r+"px"),d.css("height",e+"px"),s.css("height",w2utils.getSize(l,"height")+"px"));let v=this.records.length;n="object"!=typeof this.url?this.url:this.url.get;if(0==this.searchData.length||n||(v=this.last.searchIds.length),this.fixedBody||(w=!1),y||w?(u.find(":scope > table > tbody > tr:nth-child(1) td.w2ui-head-last").css("width",w2utils.scrollBarSize()+"px").show(),p.css({top:(0<this.columnGroups.length&&this.show.columns?1:0)+w2utils.getSize(u,"height")+"px","-webkit-overflow-scrolling":"touch","overflow-x":y?"auto":"hidden","overflow-y":w?"auto":"hidden"})):(u.find(":scope > table > tbody > tr:nth-child(1) td.w2ui-head-last").hide(),p.css({top:(0<this.columnGroups.length&&this.show.columns?1:0)+w2utils.getSize(u,"height")+"px",overflow:"hidden"}),0<p.length&&(this.last.scrollTop=0,this.last.scrollLeft=0)),y?(f.css("margin-bottom",w2utils.scrollBarSize()+"px"),m.show()):(f.css("margin-bottom",0),m.hide()),f.css({overflow:"hidden",top:p.css("top")}),this.show.emptyRecords&&!w){let t=Math.floor((p[0]?.clientHeight??0)/this.recordHeight)-1,e=0;if((e=p[0]?p[0].scrollHeight-t*this.recordHeight:e)>=this.recordHeight&&(e-=this.recordHeight,t++),this.fixedBody){for(let e=v;e<t;e++)x(e,this.recordHeight,this);x(t,e,this)}}function x(e,t,i){let s="",l="";var r;s+='<tr class="'+(e%2?"w2ui-even":"w2ui-odd")+' w2ui-empty-record" recid="-none-" style="height: '+t+'px">',l+='<tr class="'+(e%2?"w2ui-even":"w2ui-odd")+' w2ui-empty-record" recid="-none-" style="height: '+t+'px">',i.show.lineNumbers&&(s+='<td class="w2ui-col-number"></td>'),i.show.selectColumn&&(s+='<td class="w2ui-grid-data w2ui-col-select"></td>'),i.show.expandColumn&&(s+='<td class="w2ui-grid-data w2ui-col-expand"></td>'),l+='<td class="w2ui-grid-data-spacer" col="start" style="border-right: 0"></td>',i.reorderRows&&(l+='<td class="w2ui-grid-data w2ui-col-order" col="order"></td>');for(let e=0;e<i.columns.length;e++){var n=i.columns[e];(n.hidden||e<i.last.colStart||e>i.last.colEnd)&&!n.frozen||(r='<td class="w2ui-grid-data" '+(null!=n.attr?n.attr:"")+' col="'+e+'"></td>',n.frozen?s+=r:l+=r)}s+='<td class="w2ui-grid-data-last"></td> </tr>',l+='<td class="w2ui-grid-data-last" col="end"></td> </tr>',query(i.box).find("#grid_"+i.name+"_frecords > table").append(s),query(i.box).find("#grid_"+i.name+"_records > table").append(l)}let _,q;if(0<d.length){let t=parseInt(d[0].clientWidth)-(w?w2utils.scrollBarSize():0)-(this.show.lineNumbers?g:0)-(this.reorderRows?26:0)-(this.show.selectColumn?26:0)-(this.show.expandColumn?26:0)-1,i=(_=t,!1);for(let e=q=0;e<this.columns.length;e++){var C=this.columns[e];0<C.gridMinWidth&&(C.gridMinWidth>_&&!0!==C.hidden&&(C.hidden=!0,i=!0),C.gridMinWidth<_)&&!0===C.hidden&&(C.hidden=!1,i=!0)}if(!0===i)return void this.refresh();for(let e=0;e<this.columns.length;e++){var k=this.columns[e];k.hidden||("px"==String(k.size).substr(String(k.size).length-2).toLowerCase()?(t-=parseFloat(k.size),this.columns[e].sizeCalculated=k.size,this.columns[e].sizeType="px"):(q+=parseFloat(k.size),this.columns[e].sizeType="%",delete k.sizeCorrected))}if(100!=q&&0<q)for(let e=0;e<this.columns.length;e++){var S=this.columns[e];S.hidden||"%"==S.sizeType&&(S.sizeCorrected=Math.round(100*parseFloat(S.size)*100/q)/100+"%")}for(let e=0;e<this.columns.length;e++){var T=this.columns[e];T.hidden||"%"==T.sizeType&&(null!=this.columns[e].sizeCorrected?this.columns[e].sizeCalculated=Math.floor(t*parseFloat(T.sizeCorrected)/100)-1+"px":this.columns[e].sizeCalculated=Math.floor(t*parseFloat(T.size)/100)-1+"px")}}let $=0;for(let e=0;e<this.columns.length;e++){var E=this.columns[e];E.hidden||(null==E.min&&(E.min=20),parseInt(E.sizeCalculated)<parseInt(E.min)&&(E.sizeCalculated=E.min+"px"),parseInt(E.sizeCalculated)>parseInt(E.max)&&(E.sizeCalculated=E.max+"px"),$+=parseInt(E.sizeCalculated))}let z=parseInt(_)-parseInt($);if(0<z&&0<q){let e=0;for(;;){var D=this.columns[e];if(null==D)e=0;else{if(!D.hidden&&"px"!=D.sizeType&&(D.sizeCalculated=parseInt(D.sizeCalculated)+1+"px",0===--z))break;e++}}}else 0<z&&u.find(":scope > table > tbody > tr:nth-child(1) td.w2ui-head-last").css("width",w2utils.scrollBarSize()+"px").show();let O=1;this.show.lineNumbers&&(O+=g),this.show.selectColumn&&(O+=26),this.show.expandColumn&&(O+=26);for(let e=0;e<this.columns.length;e++)this.columns[e].hidden||this.columns[e].frozen&&(O+=parseInt(this.columns[e].sizeCalculated));c.css("width",O+"px"),f.css("width",O+"px"),o.css("width",O+"px"),m.css("width",O+"px"),u.css("left",O+"px"),p.css("left",O+"px"),a.css("left",O+"px"),u.find(":scope > table > tbody > tr:nth-child(1) td").add(c.find(":scope > table > tbody > tr:nth-child(1) td")).each(e=>{query(e).hasClass("w2ui-col-number")&&query(e).css("width",g+"px");var t=query(e).attr("col");if(null!=t){if("start"==t){let t=0;for(let e=0;e<i.last.colStart;e++)!i.columns[e]||i.columns[e].frozen||i.columns[e].hidden||(t+=parseInt(i.columns[e].sizeCalculated));query(e).css("width",t+"px")}i.columns[t]&&query(e).css("width",i.columns[t].sizeCalculated)}if(query(e).hasClass("w2ui-head-last"))if(i.last.colEnd+1<i.columns.length){let t=0;for(let e=i.last.colEnd+1;e<i.columns.length;e++)!i.columns[e]||i.columns[e].frozen||i.columns[e].hidden||(t+=parseInt(i.columns[e].sizeCalculated));query(e).css("width",t+"px")}else query(e).css("width",w2utils.scrollBarSize()+(0<z&&0===q?z:0)+"px")}),3==u.find(":scope > table > tbody > tr").length&&u.find(":scope > table > tbody > tr:nth-child(1) td").add(c.find(":scope > table > tbody > tr:nth-child(1) td")).html("").css({height:"0",border:"0",padding:"0",margin:"0"}),p.find(":scope > table > tbody > tr:nth-child(1) td").add(f.find(":scope > table > tbody > tr:nth-child(1) td")).each(e=>{query(e).hasClass("w2ui-col-number")&&query(e).css("width",g+"px");var t=query(e).attr("col");if(null!=t){if("start"==t){let t=0;for(let e=0;e<i.last.colStart;e++)!i.columns[e]||i.columns[e].frozen||i.columns[e].hidden||(t+=parseInt(i.columns[e].sizeCalculated));query(e).css("width",t+"px")}i.columns[t]&&query(e).css("width",i.columns[t].sizeCalculated)}if(query(e).hasClass("w2ui-grid-data-last")&&0===query(e).parents(".w2ui-grid-frecords").length)if(i.last.colEnd+1<i.columns.length){let t=0;for(let e=i.last.colEnd+1;e<i.columns.length;e++)!i.columns[e]||i.columns[e].frozen||i.columns[e].hidden||(t+=parseInt(i.columns[e].sizeCalculated));query(e).css("width",t+"px")}else query(e).css("width",(0<z&&0===q?z:0)+"px")}),a.find(":scope > table > tbody > tr:nth-child(1) td").add(o.find(":scope > table > tbody > tr:nth-child(1) td")).each(e=>{query(e).hasClass("w2ui-col-number")&&query(e).css("width",g+"px");var t=query(e).attr("col");if(null!=t){if("start"==t){let t=0;for(let e=0;e<i.last.colStart;e++)!i.columns[e]||i.columns[e].frozen||i.columns[e].hidden||(t+=parseInt(i.columns[e].sizeCalculated));query(e).css("width",t+"px")}i.columns[t]&&query(e).css("width",i.columns[t].sizeCalculated)}query(e).hasClass("w2ui-grid-data-last")&&0===query(e).parents(".w2ui-grid-frecords").length&&query(e).css("width",w2utils.scrollBarSize()+(0<z&&0===q?z:0)+"px")}),this.initResize(),this.refreshRanges(),(this.last.scrollTop||this.last.scrollLeft)&&0<p.length&&(u.prop("scrollLeft",this.last.scrollLeft),p.prop("scrollTop",this.last.scrollTop),p.prop("scrollLeft",this.last.scrollLeft)),u.css("will-change","scroll-position")}getSearchesHTML(){let i=`
<div class="search-title">
${w2utils.lang("Advanced Search")}
<span class="search-logic" style="${this.show.searchLogic?"":"display: none"}">
<select id="grid_${this.name}_logic" class="w2ui-input">
<option value="AND" ${"AND"==this.last.logic?"selected":""}>${w2utils.lang("All")}</option>
<option value="OR" ${"OR"==this.last.logic?"selected":""}>${w2utils.lang("Any")}</option>
</select>
</span>
</div>
<table cellspacing="0"><tbody>
`;for(let t=0;t<this.searches.length;t++){var s=this.searches[t];if(s.type=String(s.type).toLowerCase(),!s.hidden){null==s.attr&&(s.attr=""),null==s.text&&(s.text=""),null==s.style&&(s.style=""),null==s.type&&(s.type="text"),null==s.label&&null!=s.caption&&(console.log("NOTICE: grid search.caption property is deprecated, please use search.label. Search ->",s),s.label=s.caption);var l=`<select id="grid_${this.name}_operator_${t}" class="w2ui-input" data-change="initOperator|${t}">
${this.getOperators(s.type,s.operators)}
</select>`;i+=`<tr>
<td class="caption">${w2utils.lang(s.label)||""}</td>
<td class="operator">${l}</td>
<td class="value">`;let e;switch(s.type){case"text":case"alphanumeric":case"hex":case"color":case"list":case"combo":case"enum":e="width: 250px;",-1!=["hex","color"].indexOf(s.type)&&(e="width: 90px;"),i+=`<input rel="search" type="text" id="grid_${this.name}_field_${t}" name="${s.field}"
class="w2ui-input" style="${e+s.style}" ${s.attr}>`;break;case"int":case"float":case"money":case"currency":case"percent":case"date":case"time":case"datetime":e="width: 90px;","datetime"==s.type&&(e="width: 140px;"),i+=`<input id="grid_${this.name}_field_${t}" name="${s.field}" ${s.attr} rel="search" type="text"
class="w2ui-input" style="${e+s.style}">
<span id="grid_${this.name}_range_${t}" style="display: none"> -  
<input rel="search" type="text" class="w2ui-input" style="${e+s.style}" id="grid_${this.name}_field2_${t}" name="${s.field}" ${s.attr}>
</span>`;break;case"select":i+=`<select rel="search" class="w2ui-input" style="${s.style}" id="grid_${this.name}_field_${t}"
name="${s.field}" ${s.attr}></select>`}i+=s.text+" </td></tr>"}}return i+=`<tr>
<td colspan="2" class="actions">
<button type="button" class="w2ui-btn close-btn" data-click="searchClose">${w2utils.lang("Close")}</button>
</td>
<td class="actions">
<button type="button" class="w2ui-btn" data-click="searchReset">${w2utils.lang("Reset")}</button>
<button type="button" class="w2ui-btn w2ui-btn-blue" data-click="search">${w2utils.lang("Search")}</button>
</td>
</tr></tbody></table>`}getOperators(e,t){let i=this.operators[this.operatorsMap[e]]||[],s=(null!=t&&Array.isArray(t)&&(i=t),"");return i.forEach(e=>{let t=e,i=e;Array.isArray(e)?(t=e[1],i=e[0]):w2utils.isPlainObject(e)&&(t=e.text,i=e.oper),null==t&&(t=e),s+=`<option name="11" value="${i}">${w2utils.lang(t)}</option>
`}),s}initOperator(e){let i;var t=this.searches[e],s=this.getSearchData(t.field),l=query(`#w2overlay-${this.name}-search-overlay`),r=l.find(`#grid_${this.name}_range_`+e);let n=l.find(`#grid_${this.name}_field_`+e),a=l.find(`#grid_${this.name}_field2_`+e);var o=l.find(`#grid_${this.name}_operator_`+e).val();switch(n.show(),r.hide(),o){case"between":r.show();break;case"null":case"not null":n.hide(),n.val(o),n.trigger("change")}switch(t.type){case"text":case"alphanumeric":var h=n[0]._w2field;h&&h.reset();break;case"int":case"float":case"hex":case"color":case"money":case"currency":case"percent":case"date":case"time":case"datetime":n[0]._w2field||(new w2field(t.type,{el:n[0],...t.options}),new w2field(t.type,{el:a[0],...t.options}),setTimeout(()=>{n.trigger("keydown"),a.trigger("keydown")},1));break;case"list":case"combo":case"enum":i=t.options,"list"==t.type&&(i.selected={}),"enum"==t.type&&(i.selected=[]),s&&(i.selected=s.value),n[0]._w2field||(h=new w2field(t.type,{el:n[0],...i}),s&&null!=s.text&&h.set({id:s.value,text:s.text}));break;case"select":i='<option value="">--</option>';for(let e=0;e<t.options.items.length;e++){var d=t.options.items[e];if(w2utils.isPlainObject(t.options.items[e])){let e=d.id,t=d.text;null==e&&null!=d.value&&(e=d.value),null==t&&null!=d.text&&(t=d.text),null==e&&(e=""),i+='<option value="'+e+'">'+t+"</option>"}else i+='<option value="'+d+'">'+d+"</option>"}n.html(i)}}initSearches(){var s=query(`#w2overlay-${this.name}-search-overlay`);for(let t=0;t<this.searches.length;t++){var l=this.searches[t],r=this.getSearchData(l.field);l.type=String(l.type).toLowerCase(),"object"!=typeof l.options&&(l.options={});let e=l.operator,i=[...this.operators[this.operatorsMap[l.type]]];l.operators&&(i=l.operators),w2utils.isPlainObject(e)&&(e=e.oper),i.forEach((e,t)=>{w2utils.isPlainObject(e)&&(i[t]=e.oper)}),r&&r.operator&&(e=r.operator);var l=this.defaultOperator[this.operatorsMap[l.type]],l=(-1==i.indexOf(e)&&(e=l),s.find(`#grid_${this.name}_operator_`+t).val(e),this.initOperator(t),s.find(`#grid_${this.name}_field_`+t)),n=s.find(`#grid_${this.name}_field2_`+t);null!=r&&(Array.isArray(r.value)?["in","not in"].includes(r.operator)?l[0]._w2field.set(r.value):(l.val(r.value[0]).trigger("change"),n.val(r.value[1]).trigger("change")):null!=r.value&&l.val(r.value).trigger("change"))}s.find(".w2ui-grid-search-advanced *[rel=search]").on("keypress",e=>{13==e.keyCode&&(this.search(),w2tooltip.hide(this.name+"-search-overlay"))})}getColumnsHTML(){let h=this,e="",t="";var i,s,l;return this.show.columnHeaders&&(t=0<this.columnGroups.length?(l=r(!0),i=function(){let t="<tr>",s="<tr>",l="",e=h.columnGroups.length-1;null==h.columnGroups[e].text&&null!=h.columnGroups[e].caption&&(console.log("NOTICE: grid columnGroup.caption property is deprecated, please use columnGroup.text. Group -> ",h.columnGroups[e]),h.columnGroups[e].text=h.columnGroups[e].caption);""!=h.columnGroups[h.columnGroups.length-1].text&&h.columnGroups.push({text:""});h.show.lineNumbers&&(t+='<td class="w2ui-head w2ui-col-number" col="line-number"> <div> </div></td>');h.show.selectColumn&&(t+='<td class="w2ui-head w2ui-col-select" col="select"> <div style="height: 25px"> </div></td>');h.show.expandColumn&&(t+='<td class="w2ui-head w2ui-col-expand" col="expand"> <div style="height: 25px"> </div></td>');let r=0;s+=`<td id="grid_${h.name}_column_start" class="w2ui-head" col="start" style="border-right: 0"></td>`,h.reorderRows&&(s+='<td class="w2ui-head w2ui-col-order" col="order"> <div style="height: 25px"> </div></td>');for(let e=0;e<h.columnGroups.length;e++){var n=h.columnGroups[e],a=h.columns[r]||{};null!=n.colspan&&(n.span=n.colspan),null!=n.span&&n.span==parseInt(n.span)||(n.span=1),null==a.text&&null!=a.caption&&(console.log("NOTICE: grid column.caption property is deprecated, please use column.text. Column ->",a),a.text=a.caption);let i=0;for(let e=r;e<r+n.span;e++)h.columns[e]&&!h.columns[e].hidden&&i++;if(!((i=e==h.columnGroups.length-1?100:i)<=0)){if(!0===n.main){let t="";for(let e=0;e<h.sortData.length;e++)h.sortData[e].field==a.field&&("asc"===(h.sortData[e].direction||"").toLowerCase()&&(t="w2ui-sort-up"),"desc"===(h.sortData[e].direction||"").toLowerCase())&&(t="w2ui-sort-down");let e="";!1!==a.resizable&&(e=`<div class="w2ui-resizer" name="${r}"></div>`);var o=w2utils.lang("function"==typeof a.text?a.text(a):a.text);l=`<td id="grid_${h.name}_column_${r}" class="w2ui-head ${t}" col="${r}" `+` rowspan="2" colspan="${i}">`+e+` <div class="w2ui-col-group w2ui-col-header ${t?"w2ui-col-sorted":""}">`+` <div class="${t}"></div>`+(o||" ")+" </div></td>"}else{o=w2utils.lang("function"==typeof n.text?n.text(n):n.text);l=`<td id="grid_${h.name}_column_${r}" class="w2ui-head" col="${r}" colspan="${i}">`+` <div class="w2ui-col-group" style="${n.style??""}">${o||" "}</div>`+"</td>"}a&&a.frozen?t+=l:s+=l}r+=n.span}return t+="<td></td></tr>",s+=`<td id="grid_${h.name}_column_end" class="w2ui-head" col="end"></td></tr>`,[t,s]}(),s=r(!1),e=l[0]+i[0]+s[0],l[1]+i[1]+s[1]):(l=r(!0),e=l[0],l[1])),[e,t];function r(t){let i="<tr>",s="<tr>",l=(h.show.lineNumbers&&(i+='<td class="w2ui-head w2ui-col-number" col="line-number"> <div>#</div></td>'),h.show.selectColumn&&(i+='<td class="w2ui-head w2ui-col-select" col="select"> <div>'+` <input type="checkbox" id="grid_${h.name}_check_all" class="w2ui-select-all" tabindex="-1"`+` style="${0==h.multiSelect?"display: none;":""}"`+" > </div></td>"),h.show.expandColumn&&(i+='<td class="w2ui-head w2ui-col-expand" col="expand"> <div> </div></td>'),0),r=0,n;s+=`<td id="grid_${h.name}_column_start" class="w2ui-head" col="start" style="border-right: 0"></td>`,h.reorderRows&&(s+='<td class="w2ui-head w2ui-col-order" col="order"> <div> </div></td>');for(let e=0;e<h.columns.length;e++){var a,o=h.columns[e];null==o.text&&null!=o.caption&&(console.log("NOTICE: grid column.caption property is deprecated, please use column.text. Column -> ",o),o.text=o.caption),null==o.size&&(o.size="100%"),e==r&&(n=h.columnGroups[l++]||{},r+=n.span),(e<h.last.colStart||e>h.last.colEnd)&&!o.frozen||o.hidden||!0===n.main&&!t||(a=h.getColumnCellHTML(e),o&&o.frozen?i+=a:s+=a)}return i+='<td class="w2ui-head w2ui-head-last"><div> </div></td>',s+='<td class="w2ui-head w2ui-head-last" col="end"><div> </div></td>',i+="</tr>",s+="</tr>",[i,s]}}getColumnCellHTML(t){var i=this.columns[t];if(null==i)return"";var e=!this.reorderColumns||this.columnGroups&&this.columnGroups.length?"":" w2ui-col-reorderable ";let s="";for(let e=0;e<this.sortData.length;e++)this.sortData[e].field==i.field&&("asc"===(this.sortData[e].direction||"").toLowerCase()&&(s="w2ui-sort-up"),"desc"===(this.sortData[e].direction||"").toLowerCase())&&(s="w2ui-sort-down");var l,r=this.last.selection.columns;let n=!1;for(l in r)for(let e=0;e<r[l].length;e++)r[l][e]==t&&(n=!0);var a=w2utils.lang("function"==typeof i.text?i.text(i):i.text);return'<td id="grid_'+this.name+"_column_"+t+'" col="'+t+'" class="w2ui-head '+s+e+'">'+(!1!==i.resizable?'<div class="w2ui-resizer" name="'+t+'"></div>':"")+' <div class="w2ui-col-header '+(s?"w2ui-col-sorted":"")+" "+(n?"w2ui-col-selected":"")+'"> <div class="'+s+'"></div>'+(a||" ")+" </div></td>"}columnTooltipShow(e,t){var i=query(this.box).find("#grid_"+this.name+"_column_"+e),e=this.columns[e],s=this.columnTooltip;w2tooltip.show({name:this.name+"-column-tooltip",anchor:i.get(0),html:e?.tooltip,position:s})}columnTooltipHide(e,t){w2tooltip.hide(this.name+"-column-tooltip")}getRecordsHTML(){let e=this.records.length;var t="object"!=typeof this.url?this.url:this.url.get,t=((e=0==this.searchData.length||t?e:this.last.searchIds.length)>this.vs_start?this.last.show_extra=this.vs_extra:this.last.show_extra=this.vs_start,query(this.box).find(`#grid_${this.name}_records`));let i=Math.floor((t.get(0)?.clientHeight||0)/this.recordHeight)+this.last.show_extra+1;(!this.fixedBody||i>e)&&(i=e);var s=this.getRecordHTML(-1,0);let l="<table><tbody>"+s[0],r="<table><tbody>"+s[1];l+='<tr id="grid_'+this.name+'_frec_top" line="top" style="height: 0px"> <td colspan="2000"></td></tr>',r+='<tr id="grid_'+this.name+'_rec_top" line="top" style="height: 0px"> <td colspan="2000"></td></tr>';for(let e=0;e<i;e++)s=this.getRecordHTML(e,e+1),l+=s[0],r+=s[1];t=(e-i)*this.recordHeight;return l+='<tr id="grid_'+this.name+'_frec_bottom" rec="bottom" line="bottom" style="height: '+t+'px; vertical-align: top"> <td colspan="2000" style="border-right: 1px solid #D6D5D7;"></td></tr><tr id="grid_'+this.name+'_frec_more" style="display: none; "> <td colspan="2000" class="w2ui-load-more"></td></tr></tbody></table>',r+='<tr id="grid_'+this.name+'_rec_bottom" rec="bottom" line="bottom" style="height: '+t+'px; vertical-align: top"> <td colspan="2000" style="border: 0"></td></tr><tr id="grid_'+this.name+'_rec_more" style="display: none"> <td colspan="2000" class="w2ui-load-more"></td></tr></tbody></table>',this.last.range_start=0,this.last.range_end=i,[l,r]}getSummaryHTML(){if(0!==this.summary.length){var s=this.getRecordHTML(-1,0);let t="<table><tbody>"+s[0],i="<table><tbody>"+s[1];for(let e=0;e<this.summary.length;e++)s=this.getRecordHTML(e,e+1,!0),t+=s[0],i+=s[1];return t+="</tbody></table>",i+="</tbody></table>",[t,i]}}scroll(o){let h=this;var i="object"!=typeof this.url?this.url:this.url.get,d=query(this.box).find(`#grid_${this.name}_records`),u=query(this.box).find(`#grid_${this.name}_frecords`);o&&(w=o.target.scrollTop,o=o.target.scrollLeft,this.last.scrollTop=w,this.last.scrollLeft=o,c=query(this.box).find(`#grid_${this.name}_columns`)[0],p=query(this.box).find(`#grid_${this.name}_summary`)[0],c&&(c.scrollLeft=o),p&&(p.scrollLeft=o),u[0])&&(u[0].scrollTop=w),this.last.bubbleEl&&(w2tooltip.hide(this.name+"-bubble"),this.last.bubbleEl=null);let l=null,r=null;if(this.disableCVS||0<this.columnGroups.length)l=0,r=this.columns.length-1;else{var s,n=d.prop("clientWidth");let t=0;for(let e=0;e<this.columns.length;e++)this.columns[e].frozen||this.columns[e].hidden||(s=parseInt(this.columns[e].sizeCalculated||this.columns[e].size),t+s+30>this.last.scrollLeft&&null==l&&(l=e),t+s-30>this.last.scrollLeft+n&&null==r&&(r=e),t+=s);null==r&&(r=this.columns.length-1)}if(null!=l&&(l<0&&(l=0),r<0&&(r=0),l==r&&(0<l?l--:r++),l!=this.last.colStart||r!=this.last.colEnd)){var a=query(this.box),c=Math.abs(l-this.last.colStart),p=Math.abs(r-this.last.colEnd);if(c<5&&p<5){var e=a.find(`.w2ui-grid-columns #grid_${this.name}_column_start`),t=a.find(".w2ui-grid-columns .w2ui-head-last"),f=a.find(`#grid_${this.name}_records .w2ui-grid-data-spacer`),m=a.find(`#grid_${this.name}_records .w2ui-grid-data-last`),g=a.find(`#grid_${this.name}_summary .w2ui-grid-data-spacer`),y=a.find(`#grid_${this.name}_summary .w2ui-grid-data-last`);if(l>this.last.colStart)for(let e=this.last.colStart;e<l;e++)a.find("#grid_"+this.name+"_columns #grid_"+this.name+"_column_"+e).remove(),a.find("#grid_"+this.name+'_records td[col="'+e+'"]').remove(),a.find("#grid_"+this.name+'_summary td[col="'+e+'"]').remove();if(r<this.last.colEnd)for(let e=this.last.colEnd;e>r;e--)a.find("#grid_"+this.name+"_columns #grid_"+this.name+"_column_"+e).remove(),a.find("#grid_"+this.name+'_records td[col="'+e+'"]').remove(),a.find("#grid_"+this.name+'_summary td[col="'+e+'"]').remove();if(l<this.last.colStart)for(let s=this.last.colStart-1;s>=l;s--)this.columns[s]&&(this.columns[s].frozen||this.columns[s].hidden)||(e.after(this.getColumnCellHTML(s)),f.each(e=>{var t=query(e).parent().attr("index");let i='<td class="w2ui-grid-data" col="'+s+'" style="height: 0px"></td>';null!=t&&(i=this.getCellHTML(parseInt(t),s,!1)),query(e).after(i)}),g.each(e=>{var t=query(e).parent().attr("index");let i='<td class="w2ui-grid-data" col="'+s+'" style="height: 0px"></td>';null!=t&&(i=this.getCellHTML(parseInt(t),s,!0)),query(e).after(i)}));if(r>this.last.colEnd)for(let s=this.last.colEnd+1;s<=r;s++)this.columns[s]&&(this.columns[s].frozen||this.columns[s].hidden)||(t.before(this.getColumnCellHTML(s)),m.each(e=>{var t=query(e).parent().attr("index");let i='<td class="w2ui-grid-data" col="'+s+'" style="height: 0px"></td>';null!=t&&(i=this.getCellHTML(parseInt(t),s,!1)),query(e).before(i)}),y.each(e=>{var t=query(e).parent().attr("index")||-1,t=this.getCellHTML(parseInt(t),s,!0);query(e).before(t)}));this.last.colStart=l,this.last.colEnd=r}else{this.last.colStart=l,this.last.colEnd=r;var o=this.getColumnsHTML(),w=this.getRecordsHTML(),c=this.getSummaryHTML(),p=a.find(`#grid_${this.name}_columns`);let e=a.find(`#grid_${this.name}_records`);var b=a.find(`#grid_${this.name}_frecords`);let t=a.find(`#grid_${this.name}_summary`);p.find("tbody").html(o[1]),b.html(w[0]),e.prepend(w[1]),null!=c&&t.html(c[1]),setTimeout(()=>{e.find(":scope > table").filter(":not(table:first-child)").remove(),t[0]&&(t[0].scrollLeft=this.last.scrollLeft)},1)}this.resizeRecords()}let v=this.records.length;if(v>this.total&&-1!==this.total&&(v=this.total),0!==(v=0==this.searchData.length||i?v:this.last.searchIds.length)&&0!==d.length&&0!==d.prop("clientHeight")){v>this.vs_start?this.last.show_extra=this.vs_extra:this.last.show_extra=this.vs_start;let e=Math.round(d.prop("scrollTop")/this.recordHeight+1),t=e+(Math.round(d.prop("clientHeight")/this.recordHeight)-1);if(e>v&&(e=v),t>=v-1&&(t=v),query(this.box).find("#grid_"+this.name+"_footer .w2ui-footer-right").html((this.show.statusRange?w2utils.formatNumber(this.offset+e)+"-"+w2utils.formatNumber(this.offset+t)+(-1!=this.total?" "+w2utils.lang("of")+" "+w2utils.formatNumber(this.total):""):"")+(i&&this.show.statusBuffered?" ("+w2utils.lang("buffered")+" "+w2utils.formatNumber(v)+(0<this.offset?", skip "+w2utils.formatNumber(this.offset):"")+")":"")),i||this.fixedBody&&!(-1!=this.total&&this.total<=this.vs_start)){let t=Math.floor(d.prop("scrollTop")/this.recordHeight)-this.last.show_extra,i=t+Math.floor(d.prop("clientHeight")/this.recordHeight)+2*this.last.show_extra+1;t<1&&(t=1),i>this.total&&-1!=this.total&&(i=this.total);var x=d.find("#grid_"+this.name+"_rec_top"),_=d.find("#grid_"+this.name+"_rec_bottom"),q=u.find("#grid_"+this.name+"_frec_top"),C=u.find("#grid_"+this.name+"_frec_bottom"),p=(-1!=String(x.next().prop("id")).indexOf("_expanded_row")&&(x.next().remove(),q.next().remove()),this.total>i&&-1!=String(_.prev().prop("id")).indexOf("_expanded_row")&&(_.prev().remove(),C.prev().remove()),parseInt(x.next().attr("line"))),o=parseInt(_.prev().attr("line"));let e,s,l,r,n;if(p<t||1==p||this.last.pull_refresh){if(i<=o+this.last.show_extra-2&&i!=this.total)return;for(this.last.pull_refresh=!1;;){if(s=u.find("#grid_"+this.name+"_frec_top").next(),"bottom"==(l=d.find("#grid_"+this.name+"_rec_top").next()).attr("line"))break;if(!(parseInt(l.attr("line"))<t))break;s.remove(),l.remove()}e=d.find("#grid_"+this.name+"_rec_bottom").prev(),"top"==(r=e.attr("line"))&&(r=t);for(let e=parseInt(r)+1;e<=i;e++)this.records[e-1]&&((l=this.records[e-1].w2ui)&&!Array.isArray(l.children)&&(l.expanded=!1),n=this.getRecordHTML(e-1,e),_.before(n[1]),C.before(n[0]))}else{if(t>=p-this.last.show_extra+2&&1<t)return;for(;;){if(s=u.find("#grid_"+this.name+"_frec_bottom").prev(),"top"==(l=d.find("#grid_"+this.name+"_rec_bottom").prev()).attr("line"))break;if(!(parseInt(l.attr("line"))>i))break;s.remove(),l.remove()}e=d.find("#grid_"+this.name+"_rec_top").next(),"bottom"==(r=e.attr("line"))&&(r=i);for(let e=parseInt(r)-1;e>=t;e--)this.records[e-1]&&((l=this.records[e-1].w2ui)&&!Array.isArray(l.children)&&(l.expanded=!1),n=this.getRecordHTML(e-1,e),x.after(n[1]),q.after(n[0]))}k(),setTimeout(()=>{this.refreshRanges()},0);b=(t-1)*this.recordHeight;let a=(v-i)*this.recordHeight;function k(){h.markSearch&&(clearTimeout(h.last.marker_timer),h.last.marker_timer=setTimeout(()=>{var t=[];for(let e=0;e<h.searchData.length;e++){var i=h.searchData[e],s=h.getSearch(i.field);s&&!s.hidden&&(s=h.getColumn(i.field,!0),t.push({field:i.field,search:i.value,col:s}))}0<t.length&&t.forEach(e=>{var t=query(h.box).find('td[col="'+e.col+'"]:not(.w2ui-head)');w2utils.marker(t,e.search)})},50))}a<0&&(a=0),x.css("height",b+"px"),q.css("height",b+"px"),_.css("height",a+"px"),C.css("height",a+"px"),this.last.range_start=t,this.last.range_end=i,Math.floor(d.prop("scrollTop")/this.recordHeight)+Math.floor(d.prop("clientHeight")/this.recordHeight)+10>v&&!0!==this.last.pull_more&&(v<this.total-this.offset||-1==this.total&&this.last.fetch.hasMore)&&(!0===this.autoLoad&&(this.last.pull_more=!0,this.last.fetch.offset+=this.limit,this.request("load")),query(this.box).find("#grid_"+this.name+"_rec_more, #grid_"+this.name+"_frec_more").show().eq(1).off(".load-more").on("click.load-more",function(){query(this).find("td").html('<div><div style="width: 20px; height: 20px;" class="w2ui-spinner"></div></div>'),h.last.pull_more=!0,h.last.fetch.offset+=h.limit,h.request("load")}).find("td").html(h.autoLoad?'<div><div style="width: 20px; height: 20px;" class="w2ui-spinner"></div></div>':'<div style="padding-top: 15px">'+w2utils.lang("Load ${count} more...",{count:h.limit})+"</div>"))}}}getRecordHTML(r,n,a){let o="",h="";var d=this.last.selection;let u;if(-1==r){o+='<tr line="0">',h+='<tr line="0">',this.show.lineNumbers&&(o+='<td class="w2ui-col-number" style="height: 0px"></td>'),this.show.selectColumn&&(o+='<td class="w2ui-col-select" style="height: 0px"></td>'),this.show.expandColumn&&(o+='<td class="w2ui-col-expand" style="height: 0px"></td>'),h+='<td class="w2ui-grid-data w2ui-grid-data-spacer" col="start" style="height: 0px; width: 0px"></td>',this.reorderRows&&(h+='<td class="w2ui-col-order" style="height: 0px"></td>');for(let e=0;e<this.columns.length;e++){var t=this.columns[e],i='<td class="w2ui-grid-data" col="'+e+'" style="height: 0px;"></td>';t.frozen&&!t.hidden?o+=i:t.hidden||e<this.last.colStart||e>this.last.colEnd||(h+=i)}o+='<td class="w2ui-grid-data-last" style="height: 0px"></td>',h+='<td class="w2ui-grid-data-last" col="end" style="height: 0px"></td>'}else{var c="object"!=typeof this.url?this.url:this.url.get;if(!0!==a){if(0<this.searchData.length&&!c){if(r>=this.last.searchIds.length)return"";r=this.last.searchIds[r]}else if(r>=this.records.length)return"";u=this.records[r]}else{if(r>=this.summary.length)return"";u=this.summary[r]}if(!u)return"";null==u.recid&&null!=this.recid&&null!=(c=this.parseField(u,this.recid))&&(u.recid=c);let e=!1,t=(-1!=d.indexes.indexOf(r)&&(e=!0),u.w2ui?u.w2ui.style:""),i=(null!=t&&"string"==typeof t||(t=""),u.w2ui?u.w2ui.class:"");if(null!=i&&"string"==typeof i||(i=""),o+='<tr id="grid_'+this.name+"_frec_"+u.recid+'" recid="'+u.recid+'" line="'+n+'" index="'+r+'" class="'+(n%2==0?"w2ui-even":"w2ui-odd")+" w2ui-record "+i+(e&&"row"==this.selectType?" w2ui-selected":"")+(u.w2ui&&!1===u.w2ui.editable?" w2ui-no-edit":"")+(u.w2ui&&!0===u.w2ui.expanded?" w2ui-expanded":"")+'" style="height: '+this.recordHeight+"px; "+(e||""==t?t.replace("background-color","none"):t)+'" '+(""!=t?'custom_style="'+t+'"':"")+">",h+='<tr id="grid_'+this.name+"_rec_"+u.recid+'" recid="'+u.recid+'" line="'+n+'" index="'+r+'" class="'+(n%2==0?"w2ui-even":"w2ui-odd")+" w2ui-record "+i+(e&&"row"==this.selectType?" w2ui-selected":"")+(u.w2ui&&!1===u.w2ui.editable?" w2ui-no-edit":"")+(u.w2ui&&!0===u.w2ui.expanded?" w2ui-expanded":"")+'" style="height: '+this.recordHeight+"px; "+(e||""==t?t.replace("background-color","none"):t)+'" '+(""!=t?'custom_style="'+t+'"':"")+">",this.show.lineNumbers&&(o+='<td id="grid_'+this.name+"_cell_"+r+"_number"+(a?"_s":"")+'" class="w2ui-col-number '+(e?" w2ui-row-selected":"")+'"'+(this.reorderRows?' style="cursor: move"':"")+">"+(!0!==a?this.getLineHTML(n,u):"")+"</td>"),this.show.selectColumn&&(o+='<td id="grid_'+this.name+"_cell_"+r+"_select"+(a?"_s":"")+'" class="w2ui-grid-data w2ui-col-select">'+(!0===a||u.w2ui&&!0===u.w2ui.hideCheckBox?"":' <div> <input class="w2ui-grid-select-check" type="checkbox" tabindex="-1" '+(e?'checked="checked"':"")+' style="pointer-events: none"/> </div>')+"</td>"),this.show.expandColumn){let e="";e=!0===u.w2ui?.expanded?"-":"+","none"!=u.w2ui?.expanded&&Array.isArray(u.w2ui?.children)&&u.w2ui?.children.length||(e="+"),"spinner"==u.w2ui?.expanded&&(e='<div class="w2ui-spinner" style="width: 16px; margin: -2px 2px;"></div>'),o+='<td id="grid_'+this.name+"_cell_"+r+"_expand"+(a?"_s":"")+'" class="w2ui-grid-data w2ui-col-expand">'+(!0!==a?`<div>${e}</div>`:"")+"</td>"}h+='<td class="w2ui-grid-data-spacer" col="start" style="border-right: 0"></td>',this.reorderRows&&(h+='<td id="grid_'+this.name+"_cell_"+r+"_order"+(a?"_s":"")+'" class="w2ui-grid-data w2ui-col-order" col="order">'+(!0!==a?'<div title="Drag to reorder"> </div>':"")+"</td>");let s=0,l=0;for(;;){let e=1;var p,f=this.columns[s];if(null==f)break;if(f.hidden)s++,0<l&&l--;else if(0<l){if(s++,null==this.columns[s])break;u.w2ui.colspan[this.columns[s-1].field]=0,l--}else{if(u.w2ui&&(g=u.w2ui.colspan,p=this.columns[s].field,g)&&0===g[p]&&delete g[p],!(s<this.last.colStart||s>this.last.colEnd)||f.frozen){if(u.w2ui&&"object"==typeof u.w2ui.colspan){var m=parseInt(u.w2ui.colspan[f.field])||null;if(1<m){let t=0;for(let e=s;e<s+m&&!(e>=this.columns.length);e++)this.columns[e].hidden&&t++;e=m-t,l=m-1}}var g=this.getCellHTML(r,s,a,e);f.frozen?o+=g:h+=g}s++}}o+='<td class="w2ui-grid-data-last"></td>',h+='<td class="w2ui-grid-data-last" col="end"></td>'}return o+="</tr>",h+="</tr>",[o,h]}getLineHTML(e){return"<div>"+e+"</div>"}getCellHTML(i,s,l,e){let r=this,n=this.columns[s];if(null==n)return"";let a=(!0!==l?this.records:this.summary)[i],{value:t,style:o,className:h,attr:d,divAttr:u}=this.getCellValue(i,s,l,!0);var c=-1!==i?this.getCellEditable(i,s):"";let p="max-height: "+parseInt(this.recordHeight)+"px;"+(n.clipboardCopy?"margin-right: 20px":"");var f=!l&&a?.w2ui?.changes&&null!=a.w2ui.changes[n.field],m=this.last.selection;let g=!1,y="";if(-1!=m.indexes.indexOf(i)&&(g=!0),null==e&&(e=a?.w2ui?.colspan&&a.w2ui.colspan[n.field]?a.w2ui.colspan[n.field]:1),0===s&&Array.isArray(a?.w2ui?.children)){let t=0,e=this.get(a.w2ui.parent_recid,!0);for(;;){if(null==e)break;t++;var w=this.records[e].w2ui;if(null==w||null==w.parent_recid)break;e=this.get(w.parent_recid,!0)}if(a.w2ui.parent_recid)for(let e=0;e<t;e++)y+='<span class="w2ui-show-children w2ui-icon-empty"></span>';var b=0<a.w2ui.children.length?a.w2ui.expanded?"w2ui-icon-collapse":"w2ui-icon-expand":"w2ui-icon-empty";y+=`<span class="w2ui-show-children ${b}"></span>`}if(!0===n.info&&(n.info={}),null!=n.info){let e="w2ui-icon-info",t=("function"==typeof n.info.icon?e=n.info.icon(a,{self:this,index:i,colIndex:s,summary:!!l}):"object"==typeof n.info.icon?e=n.info.icon[this.parseField(a,n.field)]||"":"string"==typeof n.info.icon&&(e=n.info.icon),n.info.style||"");"function"==typeof n.info.style?t=n.info.style(a,{self:this,index:i,colIndex:s,summary:!!l}):"object"==typeof n.info.style?t=n.info.style[this.parseField(a,n.field)]||"":"string"==typeof n.info.style&&(t=n.info.style),y+=`<span class="w2ui-info ${e}" style="${t}"></span>`}let v=t,x=(c&&-1!=["checkbox","check"].indexOf(c.type)&&(p+="text-align: center;",v=`<input tabindex="-1" type="checkbox" class="w2ui-editable-checkbox"
data-changeInd="${l?-(i+1):i}" data-colInd="${s}" ${v?'checked="checked"':""}>`,y=""),null==(v=`<div style="${p}" ${function(e){let t;r.show.recordTitles&&(null!=n.title?("function"==typeof n.title&&(t=n.title.call(r,a,{self:this,index:i,colIndex:s,summary:!!l})),"string"==typeof n.title&&(t=n.title)):t=w2utils.stripTags(String(e).replace(/"/g,"''")));return null!=t?'title="'+String(t)+'"':""}(v)} ${u}>${y}${String(v)}</div>`)&&(v=""),"string"==typeof n.render&&(b=n.render.toLowerCase().split(":"),-1!=["number","int","float","money","currency","percent","size"].indexOf(b[0]))&&(o+="text-align: right;"),a?.w2ui&&("object"==typeof a.w2ui.style&&("string"==typeof a.w2ui.style[s]&&(o+=a.w2ui.style[s]+";"),"string"==typeof a.w2ui.style[n.field])&&(o+=a.w2ui.style[n.field]+";"),"object"==typeof a.w2ui.class)&&("string"==typeof a.w2ui.class[s]&&(h+=a.w2ui.class[s]+" "),"string"==typeof a.w2ui.class[n.field])&&(h+=a.w2ui.class[n.field]+" "),!1);g&&m.columns[i]?.includes(s)&&(x=!0);let _;return n.clipboardCopy&&(_='<span class="w2ui-clipboard-copy w2ui-icon-paste"></span>'),v='<td class="w2ui-grid-data'+(x?" w2ui-selected":"")+" "+h+(f?" w2ui-changed":"")+'" id="grid_'+this.name+"_data_"+i+"_"+s+'" col="'+s+'" style="'+o+(null!=n.style?n.style:"")+'" '+(null!=n.attr?n.attr:"")+d+(1<e?'colspan="'+e+'"':"")+">"+v+(_&&w2utils.stripTags(v)?_:"")+"</td>",v=-1===i&&!0===l?'<td class="w2ui-grid-data" col="'+s+'" style="height: 0px; '+o+'" '+(1<e?'colspan="'+e+'"':"")+"></td>":v}clipboardCopy(e,t,i){var s=(i?this.summary:this.records)[e],l=this.columns[t];let r=l?this.parseField(s,l.field):"";"function"==typeof l.clipboardCopy&&(r=l.clipboardCopy(s,{self:this,index:e,colIndex:t,summary:!!i})),query(this.box).find("#grid_"+this.name+"_focus").text(r).get(0).select(),document.execCommand("copy")}showBubble(s,l,r){var n=this.columns[l].info;if(n){let i="";var a=this.records[s],e=query(this.box).find(`${r?".w2ui-grid-summary":""} #grid_${this.name}_data_${s}_${l} .w2ui-info`);if(this.last.bubbleEl&&w2tooltip.hide(this.name+"-bubble"),this.last.bubbleEl=e,null==n.fields){n.fields=[];for(let e=0;e<this.columns.length;e++){var o=this.columns[e];n.fields.push(o.field+("string"==typeof o.render?":"+o.render:""))}}let t=n.fields;if("function"==typeof t&&(t=t(a,{self:this,index:s,colIndex:l,summary:!!r})),"function"==typeof n.render)i=n.render(a,{self:this,index:s,colIndex:l,summary:!!r});else if(Array.isArray(t)){i='<table cellpadding="0" cellspacing="0">';for(let e=0;e<t.length;e++){var h=String(t[e]).split(":");if(""==h[0]||"-"==h[0]||"--"==h[0]||"---"==h[0])i+='<tr><td colspan=2><div style="border-top: '+(""==h[0]?"0":"1")+'px solid #C1BEBE; margin: 6px 0px;"></div></td></tr>';else{let e=this.getColumn(h[0]),t=(e=null==e?{field:h[0],caption:h[0]}:e)?this.parseField(a,e.field):"";1<h.length&&(w2utils.formatters[h[1]]?t=w2utils.formatters[h[1]](t,h[2]||null,a):console.log('ERROR: w2utils.formatters["'+h[1]+'"] does not exists.')),(!0===n.showEmpty||null!=t&&""!=t)&&(null!=n.maxLength&&"string"==typeof t&&t.length>n.maxLength&&(t=t.substr(0,n.maxLength)+"..."),i+="<tr><td>"+e.text+"</td><td>"+((0===t?"0":t)||"")+"</td></tr>")}}i+="</table>"}else if(w2utils.isPlainObject(t)){for(var d in i='<table cellpadding="0" cellspacing="0">',t){var u=t[d];if(""==u||"-"==u||"--"==u||"---"==u)i+='<tr><td colspan=2><div style="border-top: '+(""==u?"0":"1")+'px solid #C1BEBE; margin: 6px 0px;"></div></td></tr>';else{var c=String(u).split(":");let e=this.getColumn(c[0]),t=(e=null==e?{field:c[0],caption:c[0]}:e)?this.parseField(a,e.field):"";1<c.length&&(w2utils.formatters[c[1]]?t=w2utils.formatters[c[1]](t,c[2]||null,a):console.log('ERROR: w2utils.formatters["'+c[1]+'"] does not exists.')),"function"==typeof u&&(t=u(a,{self:this,index:s,colIndex:l,summary:!!r})),(!0===n.showEmpty||null!=t&&""!=t)&&(null!=n.maxLength&&"string"==typeof t&&t.length>n.maxLength&&(t=t.substr(0,n.maxLength)+"..."),i+="<tr><td>"+d+"</td><td>"+((0===t?"0":t)||"")+"</td></tr>")}}i+="</table>"}return w2tooltip.show(w2utils.extend({name:this.name+"-bubble",html:i,anchor:e.get(0),position:"top|bottom",class:"w2ui-info-bubble",style:"",hideOn:["doc-click"]},n.options??{})).hide(()=>[this.last.bubbleEl=null])}}getCellEditable(e,t){var i=this.columns[t],s=this.records[e];if(!s||!i)return null;let l=s.w2ui?s.w2ui.editable:null;return!1===l?null:(null!=l&&!0!==l||"function"==typeof(l=0<Object.keys(i.editable??{}).length?i.editable:null)&&(i=this.getCellValue(e,t,!1),l=l.call(this,s,{self:this,value:i,index:e,colIndex:t})),l)}getCellValue(t,i,s,e){var l=this.columns[i],r=(!0!==s?this.records:this.summary)[t];let n=this.parseField(r,l.field),a="",o="",h="",d="";if(null!=r?.w2ui?.changes?.[l.field]&&(n=r.w2ui.changes[l.field]),null!=l.render&&-1!==t){if("function"==typeof l.render&&null!=r){let e;try{e=l.render(r,{self:this,value:n,index:t,colIndex:i,summary:!!s})}catch(e){throw new Error(`Render function for column "${l.field}" in grid "${this.name}": -- `+e.message)}null!=e&&"object"==typeof e&&"function"!=typeof e?(null!=e.id&&null!=e.text?n=e.text:"string"==typeof e.html?n=(e.html||"").trim():(n="",console.log("ERROR: render function should return a primitive or an object of the following structure.",{html:"",attr:"",style:"",class:"",divAttr:""})),h=e.attr??"",o=e.style??"",a=e.class??"",d=e.divAttr??""):n=String(e||"").trim()}if("object"==typeof l.render&&null!=(t=l.render[n])&&""!==t&&(n=t),"string"==typeof l.render){i=l.render.toLowerCase().indexOf(":"),s=[];-1==i?(s[0]=l.render.toLowerCase(),s[1]=""):(s[0]=l.render.toLowerCase().substr(0,i),s[1]=l.render.toLowerCase().substr(i+1));let e=w2utils.formatters[s[0]];l.options&&!1===l.options.autoFormat&&(e=null),n="function"==typeof e?e(n,s[1],r):""}}return null==n&&(n=""),e?{value:n,attr:h,style:o,className:a,divAttr:d}:n}getFooterHTML(){return'<div> <div class="w2ui-footer-left"></div> <div class="w2ui-footer-right"></div> <div class="w2ui-footer-center"></div></div>'}status(i){if(null!=i)query(this.box).find(`#grid_${this.name}_footer`).find(".w2ui-footer-left").html(i);else{let t="";i=this.getSelection();if(0<i.length&&(this.show.statusSelection&&1<i.length&&(t=String(i.length).replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+w2utils.settings.groupSymbol)+" "+w2utils.lang("selected")),this.show.statusRecordID)&&1==i.length){let e=i[0];"object"==typeof e&&(e=e.recid+", "+w2utils.lang("Column")+": "+e.column),t=w2utils.lang("Record ID")+": "+e+" "}query(this.box).find("#grid_"+this.name+"_footer .w2ui-footer-left").html(t)}}lock(e,t){let i=Array.from(arguments);i.unshift(this.box),setTimeout(()=>{query(this.box).find("#grid_"+this.name+"_empty_msg").remove(),w2utils.lock(...i)},10)}unlock(e){setTimeout(()=>{query(this.box).find(".w2ui-message").hasClass("w2ui-closing")||w2utils.unlock(this.box,e)},25)}stateSave(e){var t={columns:[],show:w2utils.clone(this.show),last:{search:this.last.search,multi:this.last.multi,logic:this.last.logic,label:this.last.label,field:this.last.field,scrollTop:this.last.scrollTop,scrollLeft:this.last.scrollLeft},sortData:[],searchData:[]};let l;for(let e=0;e<this.columns.length;e++){let i=this.columns[e],s={};Object.keys(this.stateColProps).forEach((e,t)=>{this.stateColProps[e]&&(l=void 0!==i[e]?i[e]:this.colTemplate[e]||null,s[e]=l)}),t.columns.push(s)}for(let e=0;e<this.sortData.length;e++)t.sortData.push(w2utils.clone(this.sortData[e]));for(let e=0;e<this.searchData.length;e++)t.searchData.push(w2utils.clone(this.searchData[e]));var i=this.trigger("stateSave",{target:this.name,state:t});if(!0!==i.isCancelled)return!0!==e&&this.cacheSave("state",t),i.finish(),t}stateRestore(i){let s="object"!=typeof this.url?this.url:this.url.get;i=i||this.cache("state");var e=this.trigger("stateRestore",{target:this.name,state:i});if(!0!==e.isCancelled){if(w2utils.isPlainObject(i)){w2utils.extend(this.show,i.show??{}),w2utils.extend(this.last,i.last??{});let e=this.last.scrollTop,t=this.last.scrollLeft;for(let e=0;e<i.columns?.length;e++){var l=i.columns[e],r=this.getColumn(l.field,!0);null!==r&&(w2utils.extend(this.columns[r],l),e!==r)&&this.columns.splice(e,0,this.columns.splice(r,1)[0])}this.sortData.splice(0,this.sortData.length);for(let e=0;e<i.sortData?.length;e++)this.sortData.push(i.sortData[e]);this.searchData.splice(0,this.searchData.length);for(let e=0;e<i.searchData?.length;e++)this.searchData.push(i.searchData[e]);setTimeout(()=>{s||(0<this.sortData.length&&this.localSort(),0<this.searchData.length&&this.localSearch()),this.last.scrollTop=e,this.last.scrollLeft=t,this.refresh()},1),console.log(`INFO (w2ui): state restored for "${this.name}"`)}return e.finish(),!0}}stateReset(){this.stateRestore(this.last.state),this.cacheSave("state",null)}parseField(e,i){if(this.nestedFields){let t="";try{t=e;var s=String(i).split(".");for(let e=0;e<s.length;e++)t=t[s[e]]}catch(e){t=""}return t}return e?e[i]:""}prepareData(){let t=this;for(let e=0;e<this.records.length;e++)!function i(s){for(let e=0;e<t.columns.length;e++){let i=t.columns[e];if(null!=s[i.field]&&"string"==typeof i.render){if(-1!=["number","int","float","money","currency","percent"].indexOf(i.render.split(":")[0])&&"number"!=typeof s[i.field]&&(s[i.field]=parseFloat(s[i.field])),-1!=["date","age"].indexOf(i.render.split(":")[0])&&!s[i.field+"_"]){let e=s[i.field];w2utils.isInt(e)&&(e=parseInt(e)),s[i.field+"_"]=new Date(e)}if(-1!=["time"].indexOf(i.render))if(w2utils.isTime(s[i.field])){let e=w2utils.isTime(s[i.field],!0),t=new Date;t.setHours(e.hours,e.minutes,e.seconds||0,0),s[i.field+"_"]||(s[i.field+"_"]=t)}else{let e=s[i.field],t=(e=null!=(e=w2utils.isInt(e)?parseInt(e):e)?new Date(e):new Date,new Date);t.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),0),s[i.field+"_"]||(s[i.field+"_"]=t)}}}if(s.w2ui?.children&&!0!==s.w2ui?.expanded)for(let t=0;t<s.w2ui.children.length;t++){let e=s.w2ui.children[t];i(e)}}(this.records[e])}nextCell(e,t,i){t+=1;if(t>=this.columns.length)return null==(e=this.nextRow(e))?e:this.nextCell(e,-1,i);var s=this.records[e].w2ui,l=this.columns[t],s=s&&s.colspan&&!isNaN(s.colspan[l.field])?parseInt(s.colspan[l.field]):1;if(null==l)return null;if(l&&l.hidden||0===s)return this.nextCell(e,t,i);if(i){l=this.getCellEditable(e,t);if(null==l||-1!=["checkbox","check"].indexOf(l.type))return this.nextCell(e,t,i)}return{index:e,colIndex:t}}prevCell(e,t,i){t-=1;if(t<0)return null==(e=this.prevRow(e))?e:this.prevCell(e,this.columns.length,i);if(t<0)return null;var s=this.records[e].w2ui,l=this.columns[t],s=s&&s.colspan&&!isNaN(s.colspan[l.field])?parseInt(s.colspan[l.field]):1;if(null==l)return null;if(l&&l.hidden||0===s)return this.prevCell(e,t,i);if(i){l=this.getCellEditable(e,t);if(null==l||-1!=["checkbox","check"].indexOf(l.type))return this.prevCell(e,t,i)}return{index:e,colIndex:t}}nextRow(e,t,i){var s=this.last.searchIds;let l=null;if(-1==(i=null==i?1:i))return this.records.length-1;if(e+i<this.records.length&&0===s.length||0<s.length&&e<s[s.length-i]){if(e+=i,0<s.length)for(;;){if(s.includes(e)||e>this.records.length)break;e+=i}var r=this.records[e].w2ui,n=this.columns[t],r=r&&r.colspan&&null!=n&&!isNaN(r.colspan[n.field])?parseInt(r.colspan[n.field]):1;l=0===r?this.nextRow(e,t,i):e}return l}prevRow(e,t,i){var s=this.last.searchIds;let l=null;if(-1==(i=null==i?1:i))return 0;if(0<=e-i&&0===s.length||0<s.length&&e>s[0]){if(e-=i,0<s.length)for(;;){if(s.includes(e)||e<0)break;e-=i}var r=this.records[e].w2ui,n=this.columns[t],r=r&&r.colspan&&null!=n&&!isNaN(r.colspan[n.field])?parseInt(r.colspan[n.field]):1;l=0===r?this.prevRow(e,t,i):e}return l}selectionSave(){return this.last.saved_sel=this.getSelection(),this.last.saved_sel}selectionRestore(e){var t,i=Date.now(),s=(this.last.selection={indexes:[],columns:{}},this.last.selection),l=this.last.saved_sel;if(l)for(let e=0;e<l.length;e++)w2utils.isPlainObject(l[e])?null!=(t=this.get(l[e].recid,!0))&&(-1==s.indexes.indexOf(t)&&s.indexes.push(t),s.columns[t]||(s.columns[t]=[]),s.columns[t].push(l[e].column)):null!=(t=this.get(l[e],!0))&&s.indexes.push(t);return delete this.last.saved_sel,!0!==e&&this.refresh(),Date.now()-i}message(e){return w2utils.message({owner:this,box:this.box,after:".w2ui-grid-header"},e)}confirm(e){return w2utils.confirm({owner:this,box:this.box,after:".w2ui-grid-header"},e)}}class w2form extends w2base{constructor(e){super(e.name),this.name=null,this.header="",this.box=null,this.url="",this.method=null,this.routeData={},this.formURL="",this.formHTML="",this.page=0,this.pageStyle="",this.recid=null,this.fields=[],this.actions={},this.record={},this.original=null,this.dataType=null,this.postData={},this.httpHeaders={},this.toolbar={},this.tabs={},this.style="",this.focus=0,this.autosize=!0,this.nestedFields=!0,this.tabindexBase=0,this.isGenerated=!1,this.last={fetchCtrl:null,fetchOptions:null,errors:[]},this.onRequest=null,this.onLoad=null,this.onValidate=null,this.onSubmit=null,this.onProgress=null,this.onSave=null,this.onChange=null,this.onInput=null,this.onRender=null,this.onRefresh=null,this.onResize=null,this.onDestroy=null,this.onAction=null,this.onToolbar=null,this.onError=null,this.msgRefresh="Loading...",this.msgSaving="Saving...",this.msgServerError="Server error",this.ALL_TYPES=["text","textarea","email","pass","password","int","float","money","currency","percent","hex","alphanumeric","color","date","time","datetime","toggle","checkbox","radio","check","checks","list","combo","enum","file","select","map","array","div","custom","html","empty"],this.LIST_TYPES=["select","radio","check","checks","list","combo","enum"],this.W2FIELD_TYPES=["int","float","money","currency","percent","hex","alphanumeric","color","date","time","datetime","list","combo","enum","file"],w2utils.extend(this,e);var t,i,s=e.record,l=e.original,r=e.fields,n=e.toolbar;let a=e.tabs;if(Object.assign(this,{record:{},original:null,fields:[],tabs:{},toolbar:{},handlers:[]}),r&&(e=function l(r){let n=[];let a=[];if(w2utils.isPlainObject(r)){let e=r;function o(t){let i=["html"];return null==t.html&&(t.html={}),Object.keys(t).forEach(e=>{-1==i.indexOf(e)&&-1!=["label","attr","style","text","span","page","column","anchor","group","groupStyle","groupTitleStyle","groupCollapsible"].indexOf(e)&&(t.html[e]=t[e],delete t[e])}),t}function h(t,i){let s=["style","html"];Object.keys(t).forEach(e=>{-1==s.indexOf(e)&&-1!=["span","column","attr","text","label"].indexOf(e)&&t[e]&&!i.html[e]&&(i.html[e]=t[e])})}r=[],Object.keys(e).forEach(i=>{let s=e[i];if("group"==s.type){if(s.text=i,w2utils.isPlainObject(s.fields)){let i=s.fields;s.fields=[],Object.keys(i).forEach(e=>{let t=i[e];t.field=e,s.fields.push(o(t))})}r.push(s)}else if("tab"==s.type){let e={id:i,text:i},t=(s.style&&(e.style=s.style),a.push(e),l(s.fields).fields);t.forEach(e=>{e.html=e.html||{},e.html.page=a.length-1,h(s,e)}),r.push(...t)}else s.field=i,r.push(o(s))})}r.forEach(s=>{if("group"==s.type){let i={group:s.text||"",groupStyle:s.style||"",groupTitleStyle:s.titleStyle||"",groupCollapsible:!0===s.collapsible};Array.isArray(s.fields)&&s.fields.forEach(e=>{let t=w2utils.clone(e);null==t.html&&(t.html={}),w2utils.extend(t.html,i),Array("span","column","attr","label","page").forEach(e=>{null==t.html[e]&&null!=s[e]&&(t.html[e]=s[e])}),null==t.field&&null!=t.name&&(console.log("NOTICE: form field.name property is deprecated, please use field.field. Field ->",s),t.field=t.name),n.push(t)})}else{let e=w2utils.clone(s);null==e.field&&null!=e.name&&(console.log("NOTICE: form field.name property is deprecated, please use field.field. Field ->",s),e.field=e.name),n.push(e)}});return{fields:n,tabs:a}}(r),this.fields=e.fields,!a)&&0<e.tabs.length&&(a=e.tabs),Array.isArray(a)){w2utils.extend(this.tabs,{tabs:[]});for(let e=0;e<a.length;e++){var o=a[e];"object"==typeof o?(this.tabs.tabs.push(o),!0===o.active&&(this.tabs.active=o.id)):this.tabs.tabs.push({id:o,text:o})}}else w2utils.extend(this.tabs,a);for(t in w2utils.extend(this.toolbar,n),s)w2utils.isPlainObject(s[t])?this.record[t]=w2utils.clone(s[t]):this.record[t]=s[t];for(i in l)w2utils.isPlainObject(l[i])?this.original[i]=w2utils.clone(l[i]):this.original[i]=l[i];""!==this.formURL?fetch(this.formURL).then(e=>e.text()).then(e=>{this.formHTML=e,this.isGenerated=!0,this.box&&this.render(this.box)}):this.formURL||this.formHTML?this.formHTML&&(this.isGenerated=!0):(this.formHTML=this.generateHTML(),this.isGenerated=!0),"string"==typeof this.box&&(this.box=query(this.box).get(0)),this.box&&this.render(this.box)}get(t,i){if(0===arguments.length){var s=[];for(let e=0;e<this.fields.length;e++)null!=this.fields[e].field&&s.push(this.fields[e].field);return s}for(let e=0;e<this.fields.length;e++)if(this.fields[e].field==t)return!0===i?e:this.fields[e];return null}set(t,i){for(let e=0;e<this.fields.length;e++)if(this.fields[e].field==t)return w2utils.extend(this.fields[e],i),this.refresh(t),!0;return!1}getValue(t,i){if(this.nestedFields){let e=void 0;try{var s=!0===i?this.original:this.record;e=String(t).split(".").reduce((e,t)=>e[t],s)}catch(e){}return e}return this.record[t]}setValue(e,l){if((""===l||null==l||Array.isArray(l)&&0===l.length||w2utils.isPlainObject(l)&&0==Object.keys(l).length)&&(l=null),!this.nestedFields)return this.record[e]=l,!0;try{let s=this.record;return String(e).split(".").map((e,t,i)=>{i.length-1!==t?s=s[e]||(s[e]={},s[e]):s[e]=l}),!0}catch(e){return!1}}getFieldValue(e){let s=this.get(e);if(null!=s){var l=s.el;let t=this.getValue(e);e=this.getValue(e,!0);let i=l.value;["int","float","percent","money","currency"].includes(s.type)&&(i=s.w2field.clean(i)),["radio"].includes(s.type)&&(r=query(l).closest("div").find("input:checked").get(0),i=r?s.options.items[query(r).data("index")].id:null),["toggle","checkbox"].includes(s.type)&&(i=l.checked),-1!==["check","checks"].indexOf(s.type)&&(i=[],0<(r=query(l).closest("div").find("input:checked")).length&&r.each(e=>{e=s.options.items[query(e).data("index")];i.push(e.id)}),Array.isArray(t)||(t=[]));var r=l._w2field?.selected;if(["list","enum","file"].includes(s.type)&&r){var n=r,a=t;if(Array.isArray(n)){i=[];for(let e=0;e<n.length;e++)i[e]=w2utils.clone(n[e])}if(Array.isArray(a)){t=[];for(let e=0;e<a.length;e++)t[e]=w2utils.clone(a[e])}w2utils.isPlainObject(n)&&(i=w2utils.clone(n)),w2utils.isPlainObject(a)&&(t=w2utils.clone(a))}return["map","array"].includes(s.type)&&(i="map"==s.type?{}:[],s.$el.parent().find(".w2ui-map-field").each(e=>{var t=query(e).find(".w2ui-map.key").val(),e=query(e).find(".w2ui-map.value").val();"map"==s.type?i[t]=e:i.push(e)})),{current:i,previous:t,original:e}}}setFieldValue(e,r){let n=this.get(e);if(null!=n){var s=n.el;switch(n.type){case"toggle":case"checkbox":s.checked=!!r;break;case"radio":{r=r?.id??r;let i=query(s).closest("div").find("input");n.options.items.forEach((e,t)=>{e.id===r&&i.filter(`[data-index="${t}"]`).prop("checked",!0)});break}case"check":case"checks":{r=(r=Array.isArray(r)?r:null!=r?[r]:[]).map(e=>e?.id??e);let i=query(s).closest("div").find("input");n.options.items.forEach((e,t)=>{i.filter(`[data-index="${t}"]`).prop("checked",!!r.includes(e.id))});break}case"list":case"combo":let t=r;null==t?.id&&Array.isArray(n.options?.items)&&n.options.items.forEach(e=>{e.id===r&&(t=e)}),t!=r&&this.setValue(n.name,t),"list"==n.type?(n.w2field.selected=t,n.w2field.refresh()):n.el.value=t?.text??r;break;case"enum":case"file":{let s=[...r=Array.isArray(r)?r:null!=r?[r]:[]],l=!1;s.forEach((t,i)=>{null==t?.id&&Array.isArray(n.options.items)&&n.options.items.forEach(e=>{e.id==t&&(s[i]=e,l=!0)})}),l&&this.setValue(n.name,s),n.w2field.selected=s,n.w2field.refresh();break}case"map":case"array":"map"!=n.type||null!=r&&w2utils.isPlainObject(r)||(this.setValue(n.field,{}),r=this.getValue(n.field)),"array"!=n.type||null!=r&&Array.isArray(r)||(this.setValue(n.field,[]),r=this.getValue(n.field));var i=query(n.el).parent().find(".w2ui-map-container");n.el.mapRefresh(r,i);break;case"div":case"custom":query(s).html(r);break;case"html":case"empty":break;default:s.value=r??""}}}show(){var t=[];for(let e=0;e<arguments.length;e++){var i=this.get(arguments[e]);i&&i.hidden&&(i.hidden=!1,t.push(i.field))}return 0<t.length&&this.refresh.apply(this,t),this.updateEmptyGroups(),t}hide(){var t=[];for(let e=0;e<arguments.length;e++){var i=this.get(arguments[e]);i&&!i.hidden&&(i.hidden=!0,t.push(i.field))}return 0<t.length&&this.refresh.apply(this,t),this.updateEmptyGroups(),t}enable(){var t=[];for(let e=0;e<arguments.length;e++){var i=this.get(arguments[e]);i&&i.disabled&&(i.disabled=!1,t.push(i.field))}return 0<t.length&&this.refresh.apply(this,t),t}disable(){var t=[];for(let e=0;e<arguments.length;e++){var i=this.get(arguments[e]);i&&!i.disabled&&(i.disabled=!0,t.push(i.field))}return 0<t.length&&this.refresh.apply(this,t),t}updateEmptyGroups(){query(this.box).find(".w2ui-group").each(e=>{!function(e){let t=!0;return e.each(e=>{"none"!=e.style.display&&(t=!1)}),t}(query(e).find(".w2ui-field"))?query(e).show():query(e).hide()})}change(){Array.from(arguments).forEach(e=>{e=this.get(e);e.$el&&e.$el.change()})}reload(e){return("object"!=typeof this.url?this.url:this.url.get)&&null!=this.recid?this.request(e):("function"==typeof e&&e(),new Promise(e=>{e()}))}clear(){0!=arguments.length?Array.from(arguments).forEach(e=>{let s=this.record;String(e).split(".").map((e,t,i)=>{i.length-1!==t?s=s[e]:delete s[e]}),this.refresh(e)}):(this.recid=null,this.record={},this.original=null,this.refresh(),this.hideErrors())}error(e){var t=this.trigger("error",{target:this.name,message:e,fetchCtrl:this.last.fetchCtrl,fetchOptions:this.last.fetchOptions});!0!==t.isCancelled&&(setTimeout(()=>{this.message(e)},1),t.finish())}message(e){return w2utils.message({owner:this,box:this.box,after:".w2ui-form-header"},e)}confirm(e){return w2utils.confirm({owner:this,box:this.box,after:".w2ui-form-header"},e)}validate(e){null==e&&(e=!0);var t=[];for(let e=0;e<this.fields.length;e++){var i,s,l=this.fields[e];switch(null==this.getValue(l.field)&&this.setValue(l.field,""),-1!=["int","float","currency","money"].indexOf(l.type)&&(i=this.getValue(l.field),r=l.options.min,s=l.options.max,null!=r&&i<r&&t.push({field:l,error:w2utils.lang("Should be more than ${min}",{min:r})}),null!=s)&&s<i&&t.push({field:l,error:w2utils.lang("Should be less than ${max}",{max:s})}),l.type){case"alphanumeric":this.getValue(l.field)&&!w2utils.isAlphaNumeric(this.getValue(l.field))&&t.push({field:l,error:w2utils.lang("Not alpha-numeric")});break;case"int":this.getValue(l.field)&&!w2utils.isInt(this.getValue(l.field))&&t.push({field:l,error:w2utils.lang("Not an integer")});break;case"percent":case"float":this.getValue(l.field)&&!w2utils.isFloat(this.getValue(l.field))&&t.push({field:l,error:w2utils.lang("Not a float")});break;case"currency":case"money":this.getValue(l.field)&&!w2utils.isMoney(this.getValue(l.field))&&t.push({field:l,error:w2utils.lang("Not in money format")});break;case"color":case"hex":this.getValue(l.field)&&!w2utils.isHex(this.getValue(l.field))&&t.push({field:l,error:w2utils.lang("Not a hex number")});break;case"email":this.getValue(l.field)&&!w2utils.isEmail(this.getValue(l.field))&&t.push({field:l,error:w2utils.lang("Not a valid email")});break;case"checkbox":1==this.getValue(l.field)?this.setValue(l.field,!0):this.setValue(l.field,!1);break;case"date":l.options.format||(l.options.format=w2utils.settings.dateFormat),this.getValue(l.field)&&!w2utils.isDate(this.getValue(l.field),l.options.format)&&t.push({field:l,error:w2utils.lang("Not a valid date")+": "+l.options.format})}var r=this.getValue(l.field);!0!==l.hidden&&l.required&&!["div","custom","html","empty"].includes(l.type)&&(null==r||""===r||Array.isArray(r)&&0===r.length||w2utils.isPlainObject(r)&&0==Object.keys(r).length)&&t.push({field:l,error:w2utils.lang("Required field")}),!0!==l.hidden&&0<l.options?.minLength&&!["enum","list","combo"].includes(l.type)&&(null==r||r.length<l.options.minLength)&&t.push({field:l,error:w2utils.lang("Field should be at least ${count} characters.",{count:l.options.minLength})})}var n=this.trigger("validate",{target:this.name,errors:t});if(!0!==n.isCancelled)return this.last.errors=t,e&&this.showErrors(),n.finish(),t}showErrors(){var e=this.last.errors;e.length<=0||(this.goto(e[0].field.page),query(e[0].field.$el).parents(".w2ui-field")[0].scrollIntoView({block:"nearest",inline:"nearest"}),e.forEach(t=>{var i=w2utils.extend({anchorClass:"w2ui-error",class:"w2ui-light",position:"right|left",hideOn:["input"]},t.options);if(null!=t.field){let e=t.field.el;"radio"===t.field.type?e=query(t.field.el).closest("div").get(0):["enum","file"].includes(t.field.type),w2tooltip.show(w2utils.extend({anchor:e,name:`${this.name}-${t.field.field}-error`,html:t.error},i))}}),query(e[0].field.$el).parents(".w2ui-page").off(".hideErrors").on("scroll.hideErrors",e=>{this.hideErrors()}))}hideErrors(){this.fields.forEach(e=>{w2tooltip.hide(`${this.name}-${e.field}-error`)})}getChanges(){let e={};return e=null!=this.original&&"object"==typeof this.original&&0!==Object.keys(this.record).length?function e(t,i,s){if(Array.isArray(t)&&Array.isArray(i))for(;t.length<i.length;)t.push(null);for(var l in t)null!=t[l]&&"object"==typeof t[l]?(s[l]=e(t[l],i[l]||{},{}),(!s[l]||0==Object.keys(s[l]).length&&Object.keys(0==i[l].length))&&delete s[l]):(t[l]!=i[l]||null==t[l]&&null!=i[l])&&(s[l]=t[l]);return 0!=Object.keys(s).length?s:null}(this.record,this.original,{}):e}getCleanRecord(e){let s=w2utils.clone(this.record);return this.fields.forEach(e=>{if(-1!=["list","combo","enum"].indexOf(e.type)){var t={nestedFields:!0,record:s};let i=this.getValue.call(t,e.field);w2utils.isPlainObject(i)&&null!=i.id&&this.setValue.call(t,e.field,i.id),Array.isArray(i)&&i.forEach((e,t)=>{w2utils.isPlainObject(e)&&e.id&&(i[t]=e.id)})}var i;"map"==e.type&&(t={nestedFields:!0,record:s},(t=this.getValue.call(t,e.field))._order)&&delete t._order,"file"==e.type&&(t={nestedFields:!0,record:s},(i=this.getValue.call(t,e.field)??[]).forEach(e=>{delete e.file,delete e.modified}),this.setValue.call(t,e.field,i))}),!0===e&&Object.keys(s).forEach(e=>{this.get(e)||delete s[e]}),s}request(e,i){let s=this,l,r;var n=new Promise((e,t)=>{l=e,r=t});if("function"==typeof e&&(i=e,e=null),null==e&&(e={}),this.url&&("object"!=typeof this.url||this.url.get)){var a={action:"get"},e=(a.recid=this.recid,a.name=this.name,w2utils.extend(a,this.postData),w2utils.extend(a,e),this.trigger("request",{target:this.name,url:this.url,httpMethod:"GET",postData:a,httpHeaders:this.httpHeaders}));if(!0!==e.isCancelled){this.record={},this.original=null,this.lock(w2utils.lang(this.msgRefresh));let t=e.detail.url;if("object"==typeof t&&t.get&&(t=t.get),this.last.fetchCtrl)try{this.last.fetchCtrl.abort()}catch(e){}if(0!=Object.keys(this.routeData).length){var o=w2utils.parseRoute(t);if(0<o.keys.length)for(let e=0;e<o.keys.length;e++)null!=this.routeData[o.keys[e].name]&&(t=t.replace(new RegExp(":"+o.keys[e].name,"g"),this.routeData[o.keys[e].name]))}t=new URL(t,location);a=w2utils.prepareParams(t,{method:e.detail.httpMethod,headers:e.detail.httpHeaders,body:e.detail.postData},this.dataType);return this.last.fetchCtrl=new AbortController,a.signal=this.last.fetchCtrl.signal,this.last.fetchOptions=a,fetch(t,a).catch(h).then(e=>{200!=e?.status?e&&h(e):e.json().catch(h).then(e=>{var t=s.trigger("load",{target:s.name,fetchCtrl:this.last.fetchCtrl,fetchOptions:this.last.fetchOptions,data:e});!0!==t.isCancelled&&(null==e.error&&"error"===e.status&&(e.error=!0),e.record||Object.assign(e,{record:w2utils.clone(e)}),!0===e.error?s.error(w2utils.lang(e.message??this.msgServerError)):s.record=w2utils.clone(e.record),s.unlock(),t.finish(),s.refresh(),s.setFocus(),"function"==typeof i&&i(e),l(e))})}),e.finish(),n;function h(e){var t;"AbortError"!==e.name&&(s.unlock(),!0!==(t=s.trigger("error",{response:e,fetchCtrl:s.last.fetchCtrl,fetchOptions:s.last.fetchOptions})).isCancelled)&&(e.status&&200!=e.status?s.error(e.status+": "+e.statusText):(console.log("ERROR: Server request failed.",e,". ","Expected Response:",{error:!1,record:{field1:1,field2:"item"}},"OR:",{error:!0,message:"Error description"}),s.error(String(e))),t.finish(),r(e))}}}}submit(e,t){return this.save(e,t)}save(e,i){let s=this,l,r;var n=new Promise((e,t)=>{l=e,r=t}),a=("function"==typeof e&&(i=e,e=null),s.validate(!0));if(0===a.length)if(null==e&&(e={}),!s.url||"object"==typeof s.url&&!s.url.save)console.log("ERROR: Form cannot be saved because no url is defined.");else{s.lock(w2utils.lang(s.msgSaving)+' <span id="'+s.name+'_progress"></span>');a={action:"save"},e=(a.recid=s.recid,a.name=s.name,w2utils.extend(a,s.postData),w2utils.extend(a,e),a.record=w2utils.clone(s.record),s.trigger("submit",{target:s.name,url:s.url,httpMethod:this.method??"POST",postData:a,httpHeaders:s.httpHeaders}));if(!0!==e.isCancelled){let t=e.detail.url;if("object"==typeof t&&t.save&&(t=t.save),s.last.fetchCtrl&&s.last.fetchCtrl.abort(),0<Object.keys(s.routeData).length){var o=w2utils.parseRoute(t);if(0<o.keys.length)for(let e=0;e<o.keys.length;e++)null!=s.routeData[o.keys[e].name]&&(t=t.replace(new RegExp(":"+o.keys[e].name,"g"),s.routeData[o.keys[e].name]))}t=new URL(t,location);a=w2utils.prepareParams(t,{method:e.detail.httpMethod,headers:e.detail.httpHeaders,body:e.detail.postData},this.dataType);return this.last.fetchCtrl=new AbortController,a.signal=this.last.fetchCtrl.signal,this.last.fetchOptions=a,fetch(t,a).catch(h).then(e=>{s.unlock(),200!=e?.status?h(e??{}):e.json().catch(h).then(e=>{var t=s.trigger("save",{target:s.name,fetchCtrl:this.last.fetchCtrl,fetchOptions:this.last.fetchOptions,data:e});!0!==t.isCancelled&&(!0===e.error?s.error(w2utils.lang(e.message??this.msgServerError)):s.original=null,t.finish(),s.refresh(),"function"==typeof i&&i(e),l(e))})}),e.finish(),n;function h(e){var t;"AbortError"!==e?.name&&(s.unlock(),!0!==(t=s.trigger("error",{response:e,fetchCtrl:s.last.fetchCtrl,fetchOptions:s.last.fetchOptions})).isCancelled)&&(e.status&&200!=e.status?s.error(e.status+": "+e.statusText):(console.log("ERROR: Server request failed.",e,". ","Expected Response:",{error:!1,record:{field1:1,field2:"item"}},"OR:",{error:!0,message:"Error description"}),s.error(String(e))),t.finish(),r())}}}}lock(e,t){var i=Array.from(arguments);i.unshift(this.box),w2utils.lock(...i)}unlock(e){var t=this.box;w2utils.unlock(t,e)}lockPage(e,t,i){e=query(this.box).find(".page-"+e);return!!e.length&&(w2utils.lock(e,t,i),!0)}unlockPage(e,t){e=query(this.box).find(".page-"+e);return!!e.length&&(w2utils.unlock(e,t),!0)}goto(e){this.page!==e&&(null!=e&&(this.page=e),!0===query(this.box).data("autoSize")&&(query(this.box).get(0).clientHeight=0),this.refresh())}generateHTML(){let s=[],t="",l,r,n,a;for(let e=0;e<this.fields.length;e++){n="";var o=' tabindex="'+(a=this.tabindexBase+e+1)+'"',h=this.fields[e];null==h.html&&(h.html={}),null==h.options&&(h.options={}),null!=h.html.caption&&null==h.html.label&&(console.log("NOTICE: form field.html.caption property is deprecated, please use field.html.label. Field ->",h),h.html.label=h.html.caption),null==h.html.label&&(h.html.label=h.field),h.html=w2utils.extend({label:"",span:6,attr:"",text:"",style:"",page:0,column:0},h.html),null==l&&(l=h.html.page),null==r&&(r=h.html.column);let i=`<input id="${h.field}" name="${h.field}" class="w2ui-input" type="text" ${h.html.attr+o}>`;switch(h.type){case"pass":case"password":i=i.replace('type="text"','type="password"');break;case"checkbox":i=`
<label class="w2ui-box-label">
<input id="${h.field}" name="${h.field}" class="w2ui-input" type="checkbox" ${h.html.attr+o}>
<span>${h.html.label}</span>
</label>`;break;case"check":case"checks":{null==h.options.items&&null!=h.html.items&&(h.options.items=h.html.items);let t=h.options.items;i="",0<(t=Array.isArray(t)?t:[]).length&&(t=w2utils.normMenu.call(this,t,h));for(let e=0;e<t.length;e++)i+=`
<label class="w2ui-box-label">
<input id="${h.field+e}" name="${h.field}" class="w2ui-input" type="checkbox"
${h.html.attr+o} data-value="${t[e].id}" data-index="${e}">
<span> ${t[e].text}</span>
</label>
<br>`;break}case"radio":{i="",null==h.options.items&&null!=h.html.items&&(h.options.items=h.html.items);let t=h.options.items;0<(t=Array.isArray(t)?t:[]).length&&(t=w2utils.normMenu.call(this,t,h));for(let e=0;e<t.length;e++)i+=`
<label class="w2ui-box-label">
<input id="${h.field+e}" name="${h.field}" class="w2ui-input" type="radio"
${h.html.attr+(0===e?o:"")}
data-value="${t[e].id}" data-index="${e}">
<span> ${t[e].text}</span>
</label>
<br>`;break}case"select":{i=`<select id="${h.field}" name="${h.field}" class="w2ui-input" ${h.html.attr+o}>`,null==h.options.items&&null!=h.html.items&&(h.options.items=h.html.items);let t=h.options.items;0<(t=Array.isArray(t)?t:[]).length&&(t=w2utils.normMenu.call(this,t,h));for(let e=0;e<t.length;e++)i+=`<option value="${t[e].id}">${t[e].text}</option>`;i+="</select>";break}case"textarea":i=`<textarea id="${h.field}" name="${h.field}" class="w2ui-input" ${h.html.attr+o}></textarea>`;break;case"toggle":i=`<input id="${h.field}" name="${h.field}" class="w2ui-input w2ui-toggle" type="checkbox" ${h.html.attr+o}>
<div><div></div></div>`;break;case"map":case"array":h.html.key=h.html.key||{},h.html.value=h.html.value||{},h.html.tabindex_str=o,i='<span style="float: right">'+(h.html.text||"")+'</span><input id="'+h.field+'" name="'+h.field+'" type="hidden" '+h.html.attr+o+'><div class="w2ui-map-container"></div>';break;case"div":case"custom":i='<div id="'+h.field+'" name="'+h.field+'" '+h.html.attr+o+' class="w2ui-input">'+(h&&h.html&&h.html.html?h.html.html:"")+"</div>";break;case"html":case"empty":i=h&&h.html?(h.html.html||"")+(h.html.text||""):""}if(""!==t&&(l!=h.html.page||r!=h.html.column||h.html.group&&t!=h.html.group)&&(s[l][r]+="\n </div>\n </div>",t=""),h.html.group&&t!=h.html.group){let e="";h.html.groupCollapsible&&(e='<span class="w2ui-icon-collapse" style="width: 15px; display: inline-block; position: relative; top: -2px;"></span>'),n+='\n <div class="w2ui-group">\n <div class="w2ui-group-title w2ui-eaction" style="'+(h.html.groupTitleStyle||"")+"; "+(""!=e?"cursor: pointer; user-select: none":"")+'"'+(""!=e?'data-group="'+w2utils.base64encode(h.html.group)+'"':"")+(""!=e?'data-click="toggleGroup|'+h.html.group+'"':"")+">"+e+w2utils.lang(h.html.group)+'</div>\n <div class="w2ui-group-fields" style="'+(h.html.groupStyle||"")+'">',t=h.html.group}if(null==h.html.anchor){let e=null!=h.html.span?"w2ui-span"+h.html.span:"",t="<label"+("none"==(e=-1==h.html.span?"w2ui-span-none":e)?' style="display: none"':"")+">"+w2utils.lang("checkbox"!=h.type?h.html.label:h.html.text)+"</label>";h.html.label||(t=""),n+='\n <div class="w2ui-field '+e+'" style="'+(h.hidden?"display: none;":"")+h.html.style+'">\n '+t+("empty"===h.type?i:"\n <div>"+i+("array"!=h.type&&"map"!=h.type?w2utils.lang("checkbox"!=h.type?h.html.text:""):"")+"</div>")+"\n </div>"}else s[h.html.page].anchors=s[h.html.page].anchors||{},s[h.html.page].anchors[h.html.anchor]='<div class="w2ui-field w2ui-field-inline" style="'+(h.hidden?"display: none;":"")+h.html.style+'">'+("empty"===h.type?i:"<div>"+w2utils.lang("checkbox"!=h.type?h.html.label:h.html.text,!0)+i+w2utils.lang("checkbox"!=h.type?h.html.text:"")+"</div>")+"</div>";null==s[h.html.page]&&(s[h.html.page]={}),null==s[h.html.page][h.html.column]&&(s[h.html.page][h.html.column]=""),s[h.html.page][h.html.column]+=n,l=h.html.page,r=h.html.column}if(""!==t&&(s[l][r]+="\n </div>\n </div>"),this.tabs.tabs)for(let e=0;e<this.tabs.tabs.length;e++)null==s[e]&&(s[e]=[]);let e="";if(0<Object.keys(this.actions).length){for(var i in e+='\n<div class="w2ui-buttons">',a=this.tabindexBase+this.fields.length+1,this.actions){var d=this.actions[i],u={text:"",style:"",class:""};w2utils.isPlainObject(d)?(null==d.text&&null!=d.caption&&(console.log("NOTICE: form action.caption property is deprecated, please use action.text. Action ->",d),d.text=d.caption),d.text&&(u.text=d.text),d.style&&(u.style=d.style),d.class&&(u.class=d.class)):(u.text=i,-1!==["save","update","create"].indexOf(i.toLowerCase())?u.class="w2ui-btn-blue":u.class=""),e+='\n <button name="'+i+'" class="w2ui-btn '+u.class+'" style="'+u.style+'" tabindex="'+a+'">'+w2utils.lang(u.text)+"</button>",a++}e+="\n</div>"}n="";for(let i=0;i<s.length;i++){if(n+='<div class="w2ui-page page-'+i+'" style="'+(0!==i?"display: none;":"")+this.pageStyle+'">',!s[i])return console.log(`ERROR: Page ${i} does not exist`),!1;s[i].before&&(n+=s[i].before),n+='<div class="w2ui-column-container">',Object.keys(s[i]).sort().forEach((e,t)=>{e==parseInt(e)&&(n+='<div class="w2ui-column col-'+e+'">'+(s[i][e]||"")+"\n</div>")}),n+="\n</div>",s[i].after&&(n+=s[i].after),n+="\n</div>",s[i].anchors&&Object.keys(s[i].anchors).forEach((e,t)=>{n=n.replace(e,s[i].anchors[e])})}return n+=e}toggleGroup(e,t){var i,e=query(this.box).find('.w2ui-group-title[data-group="'+w2utils.base64encode(e)+'"]');0!==e.length&&(i=query(e.prop("nextElementSibling")),(t=void 0===t?"none"==i.css("display"):t)?(i.show(),e.find("span").addClass("w2ui-icon-collapse").removeClass("w2ui-icon-expand")):(i.hide(),e.find("span").addClass("w2ui-icon-expand").removeClass("w2ui-icon-collapse")))}action(e,t){var i=this.actions[e];let s=i;w2utils.isPlainObject(i)&&i.onClick&&(s=i.onClick);e=this.trigger("action",{target:e,action:i,originalEvent:t});!0!==e.isCancelled&&("function"==typeof s&&s.call(this,t),e.finish())}resize(){let o=this;var e=this.trigger("resize",{target:this.name});if(!0!==e.isCancelled){let s=query(this.box).find(":scope > div .w2ui-form-header"),l=query(this.box).find(":scope > div .w2ui-form-toolbar"),r=query(this.box).find(":scope > div .w2ui-form-tabs"),n=query(this.box).find(":scope > div .w2ui-page");var t=query(this.box).find(":scope > div .w2ui-page.page-"+this.page+" > div");let a=query(this.box).find(":scope > div .w2ui-buttons");var{headerHeight:i,tbHeight:h,tabsHeight:d}=u();function u(){var e=""!==o.header?w2utils.getSize(s,"height"):0,t=Array.isArray(o.toolbar?.items)&&0<o.toolbar?.items?.length?w2utils.getSize(l,"height"):0,i=Array.isArray(o.tabs?.tabs)&&0<o.tabs?.tabs?.length?w2utils.getSize(r,"height"):0;return l.css({top:e+"px"}),r.css({top:e+t+"px"}),n.css({top:e+t+i+"px",bottom:(0<a.length?w2utils.getSize(a,"height"):0)+"px"}),{headerHeight:e,tbHeight:t,tabsHeight:i}}this.autosize&&(0!==query(this.box).get(0).clientHeight&&"yes"!=query(this.box).data("autosize")||(query(this.box).css({height:i+h+d+15+(0<n.length?w2utils.getSize(t,"height"):0)+(0<a.length?w2utils.getSize(a,"height"):0)+"px"}),query(this.box).data("autosize","yes")),u()),e.finish()}}refresh(){var e=Date.now();let c=this;if(this.box&&this.isGenerated&&query(this.box).html()){var t=this.trigger("refresh",{target:this.name,page:this.page,field:arguments[0],fields:arguments});if(!0!==t.isCancelled){let i=Array.from(this.fields.keys());0<arguments.length?i=Array.from(arguments).map((e,t)=>("string"!=typeof e&&console.log("ERROR: Arguments in refresh functions should be field names"),this.get(e,!0))).filter((e,t)=>null!=e):(query(this.box).find("input, textarea, select").each(e=>{var t=null!=query(e).attr("name")?query(e).attr("name"):query(e).attr("id"),i=this.get(t);if(i){var s=query(e).closest(".w2ui-page");if(0<s.length)for(let e=0;e<100;e++)if(s.hasClass("page-"+e)){i.page=e;break}}}),query(this.box).find(".w2ui-page").hide(),query(this.box).find(".w2ui-page.page-"+this.page).show(),query(this.box).find(".w2ui-form-header").html(w2utils.lang(this.header)),"object"==typeof this.tabs&&Array.isArray(this.tabs.tabs)&&0<this.tabs.tabs.length?(query(this.box).find("#form_"+this.name+"_tabs").show(),this.tabs.active=this.tabs.tabs[this.page].id,this.tabs.refresh()):query(this.box).find("#form_"+this.name+"_tabs").hide(),"object"==typeof this.toolbar&&Array.isArray(this.toolbar.items)&&0<this.toolbar.items.length?(query(this.box).find("#form_"+this.name+"_toolbar").show(),this.toolbar.refresh()):query(this.box).find("#form_"+this.name+"_toolbar").hide());for(let t=0;t<i.length;t++){let s=this.fields[i[t]],e=(null==s.name&&null!=s.field&&(s.name=s.field),null==s.field&&null!=s.name&&(s.field=s.name),s.$el=query(this.box).find(`[name='${String(s.name).replace(/\\/g,"\\\\")}']`),s.el=s.$el.get(0),s.el&&(s.el.id=s.name),s.w2field&&s.w2field.reset(),s.$el.off(".w2form").on("change.w2form",function(e){var t=c.getFieldValue(s.field),i=(["enum","file"].includes(s.type)&&(i=s.el._w2field?.helpers?.multi,query(i).removeClass("w2ui-error")),null!=this._previous&&(t.previous=this._previous,delete this._previous),c.trigger("change",{target:this.name,field:this.name,value:t,originalEvent:e}));!0!==i.isCancelled&&(c.setValue(this.name,t.current),i.finish())}).on("input.w2form",function(e){null==c.original&&(0<Object.keys(c.record).length?c.original=w2utils.clone(c.record):c.original={});var t=c.getFieldValue(s.field),e=(null==this._previous&&(this._previous=t.previous),c.trigger("input",{target:c.name,value:t,originalEvent:e}));!0!==e.isCancelled&&(c.setValue(this.name,t.current),e.finish())}),s.required?s.$el.closest(".w2ui-field").addClass("w2ui-required"):s.$el.closest(".w2ui-field").removeClass("w2ui-required"),null!=s.disabled&&(s.disabled?(null==s.$el.data("tabIndex")&&s.$el.data("tabIndex",s.$el.prop("tabIndex")),s.$el.prop("readOnly",!0).prop("disabled",!0).prop("tabIndex",-1).closest(".w2ui-field").addClass("w2ui-disabled")):s.$el.prop("readOnly",!1).prop("disabled",!1).prop("tabIndex",s.$el.data("tabIndex")??s.$el.prop("tabIndex")??0).closest(".w2ui-field").removeClass("w2ui-disabled")),s.el);e=e||query(this.box).find("#"+s.field),s.hidden?query(e).closest(".w2ui-field").hide():query(e).closest(".w2ui-field").show()}query(this.box).find("button, input[type=button]").each(e=>{query(e).off("click").on("click",function(e){let t=this.value;this.id&&(t=this.id),this.name&&(t=this.name),c.action(t,e)})});for(let e=0;e<i.length;e++){var s=this.fields[i[e]];if(s.el){if(s.$el.hasClass("w2ui-input")||s.$el.addClass("w2ui-input"),s.type=String(s.type).toLowerCase(),s.options||(s.options={}),this.LIST_TYPES.includes(s.type)&&(null==(l=s.options.items)&&(s.options.items=[]),s.options.items=w2utils.normMenu.call(this,l,s)),"select"==s.type){var l=s.options.items;let t="";l.forEach(e=>{t+=`<option value="${e.id}">${e.text}</option>`}),s.$el.html(t)}this.W2FIELD_TYPES.includes(s.type)&&(s.w2field=s.w2field??new w2field(w2utils.extend({},s.options,{type:s.type})),s.w2field.render(s.el)),["map","array"].includes(s.type)&&!function(d){let u;d.el.mapAdd=function(e,t,i){var s=(e.disabled?" readOnly ":"")+(e.html.tabindex_str||""),i=`
<div class="w2ui-map-field" style="margin-bottom: 5px" data-index="${i}">
${"map"==e.type?`<input type="text" ${e.html.key.attr+s} class="w2ui-input w2ui-map key">
${e.html.key.text||""}
`:""}
<input type="text" ${e.html.value.attr+s} class="w2ui-input w2ui-map value">
${e.html.value.text||""}
</div>`;t.append(i)},d.el.mapRefresh=function(l,r){let n,a,o;var h;"map"==d.type&&(null==(l=w2utils.isPlainObject(l)?l:{})._order&&(l._order=Object.keys(l)),n=l._order),"array"==d.type&&(Array.isArray(l)||(l=[]),n=l.map((e,t)=>t));for(let e=r.find(".w2ui-map-field").length-1;e>=n.length;e--)r.find(`div[data-index='${e}']`).remove();for(let s=0;s<n.length;s++){let t=n[s],e=r.find(`div[data-index='${s}']`),i=(0==e.length&&(d.el.mapAdd(d,r,s),e=r.find(`div[data-index='${s}']`)),e.attr("data-key",t),a=e.find(".w2ui-map.key"),o=e.find(".w2ui-map.value"),l[t]);"array"==d.type&&0<(h=l.filter(e=>e.key==t)).length&&(i=h[0].value),a.val(t),o.val(i),!0!==d.disabled&&!1!==d.disabled||(a.prop("readOnly",!!d.disabled),o.prop("readOnly",!!d.disabled))}var e=n.length,t=r.find(`div[data-index='${e}']`),e=(0!==t.length||a&&""==a.val()&&""==o.val()||a&&(!0===a.prop("readOnly")||!0===a.prop("disabled"))||d.el.mapAdd(d,r,e),!0!==d.disabled&&!1!==d.disabled||(t.find(".key").prop("readOnly",!!d.disabled),t.find(".value").prop("readOnly",!!d.disabled)),query(d.el).get(0)?.nextSibling);query(e).find("input.w2ui-map").off(".mapChange").on("keyup.mapChange",function(e){var t=query(e.target).closest(".w2ui-map-field"),i=t.get(0).nextElementSibling,t=t.get(0).previousElementSibling,s=(13==e.keyCode&&((s=u??i)instanceof HTMLElement&&0<(s=query(s).find("input")).length&&s.get(0).focus(),u=void 0),query(e.target).hasClass("key")?"key":"value");38==e.keyCode&&t&&(query(t).find("input."+s).get(0).select(),e.preventDefault()),40==e.keyCode&&i&&(query(i).find("input."+s).get(0).select(),e.preventDefault())}).on("keydown.mapChange",function(e){38!=e.keyCode&&40!=e.keyCode||e.preventDefault()}).on("input.mapChange",function(e){var e=query(e.target).closest("div"),t=e.data("index"),i=e.get(0).nextElementSibling;if(""==e.find("input").val()||i){if(""==e.find("input").val()&&i){let t=!0;query(i).find("input").each(e=>{""!=e.value&&(t=!1)}),t&&query(i).remove()}}else d.el.mapAdd(d,r,parseInt(t)+1)}).on("change.mapChange",function(e){null==c.original&&(0<Object.keys(c.record).length?c.original=w2utils.clone(c.record):c.original={});let{current:t,previous:i,original:s}=c.getFieldValue(d.field);var l=query(e.target).closest(".w2ui-map-container"),l=("map"==d.type&&(t._order=[]),l.find(".w2ui-map.key").each(e=>{t._order.push(e.value)}),c.trigger("change",{target:d.field,field:d.field,originalEvent:e,value:{current:t,previous:i,original:s}}));!0!==l.isCancelled&&("map"==d.type&&(t._order=t._order.filter(e=>""!==e),delete t[""]),"array"==d.type&&(t=t.filter(e=>""!==e)),""==query(e.target).parent().find("input").val()&&(u=e.target),c.setValue(d.field,t),d.el.mapRefresh(t,r),l.finish())})}}(s),this.setFieldValue(s.field,this.getValue(s.name))}}return t.finish(),this.resize(),Date.now()-e}}}render(e){var t=Date.now();let i=this;"string"==typeof e&&(e=query(e).get(0));var s=this.trigger("render",{target:this.name,box:e??this.box});if(!0!==s.isCancelled&&(null!=e&&(0<query(this.box).find("#form_"+this.name+"_form").length&&query(this.box).removeAttr("name").removeClass("w2ui-reset w2ui-form").html(""),this.box=e),this.isGenerated||this.formHTML)&&this.box){e='<div class="w2ui-form-box">'+(""!==this.header?'<div class="w2ui-form-header">'+w2utils.lang(this.header)+"</div>":"")+' <div id="form_'+this.name+'_toolbar" class="w2ui-form-toolbar" style="display: none"></div> <div id="form_'+this.name+'_tabs" class="w2ui-form-tabs" style="display: none"></div>'+this.formHTML+"</div>",e=(query(this.box).attr("name",this.name).addClass("w2ui-reset w2ui-form").html(e),0<query(this.box).length&&(query(this.box)[0].style.cssText+=this.style),w2utils.bindEvents(query(this.box).find(".w2ui-eaction"),this),"function"!=typeof this.toolbar.render&&(this.toolbar=new w2toolbar(w2utils.extend({},this.toolbar,{name:this.name+"_toolbar",owner:this})),this.toolbar.on("click",function(e){e=i.trigger("toolbar",{target:e.target,originalEvent:e});!0!==e.isCancelled&&e.finish()})),"object"==typeof this.toolbar&&"function"==typeof this.toolbar.render&&this.toolbar.render(query(this.box).find("#form_"+this.name+"_toolbar")[0]),"function"!=typeof this.tabs.render&&(this.tabs=new w2tabs(w2utils.extend({},this.tabs,{name:this.name+"_tabs",owner:this,active:this.tabs.active})),this.tabs.on("click",function(e){i.goto(this.get(e.target,!0))})),"object"==typeof this.tabs&&"function"==typeof this.tabs.render&&(this.tabs.render(query(this.box).find("#form_"+this.name+"_tabs")[0]),this.tabs.active)&&this.tabs.click(this.tabs.active),s.finish(),this.resize(),"object"!=typeof this.url?this.url:this.url.get);if(e&&null!=this.recid?this.request().catch(e=>this.refresh()):this.refresh(),this.last.observeResize=new ResizeObserver(()=>{this.resize()}),this.last.observeResize.observe(this.box),-1!=this.focus){let e=0,t=()=>{0<query(i.box).find("input, select, textarea").length?i.setFocus():++e<20&&setTimeout(t,50)};t()}return Date.now()-t}}setFocus(e){void 0===e&&(e=this.focus);let t;if(w2utils.isInt(e)){if(e<0)return;for(var i=query(this.box).find("div:not(.w2ui-field-helper) > input, select, textarea, div > label:nth-child(1) > [type=radio]").filter(":not(.file-input)");null==i[e].offsetParent&&i.length>=e;)e++;i[e]&&(t=query(i[e]))}else"string"==typeof e&&(t=query(this.box).find(`[name='${e}']`));return 0<t.length&&t.get(0).focus(),t}destroy(){var e=this.trigger("destroy",{target:this.name});!0!==e.isCancelled&&("object"==typeof this.toolbar&&this.toolbar.destroy&&this.toolbar.destroy(),"object"==typeof this.tabs&&this.tabs.destroy&&this.tabs.destroy(),0<query(this.box).find("#form_"+this.name+"_tabs").length&&query(this.box).removeAttr("name").removeClass("w2ui-reset w2ui-form").html(""),this.last.observeResize?.disconnect(),delete w2ui[this.name],e.finish())}}class w2field extends w2base{constructor(e,t){super(),"string"==typeof e&&null==t&&(t={type:e}),"object"==typeof e&&null==t&&(t=w2utils.clone(e)),"string"==typeof e&&"object"==typeof t&&(t.type=e),t.type=String(t.type).toLowerCase(),this.el=t.el??null,this.selected=null,this.helpers={},this.type=t.type??"text",this.options=w2utils.clone(t),this.onClick=t.onClick??null,this.onAdd=t.onAdd??null,this.onNew=t.onNew??null,this.onRemove=t.onRemove??null,this.onMouseEnter=t.onMouseEnter??null,this.onMouseLeave=t.onMouseLeave??null,this.onScroll=t.onScroll??null,this.tmp={},delete this.options.type,delete this.options.onClick,delete this.options.onMouseEnter,delete this.options.onMouseLeave,delete this.options.onScroll,this.el&&this.render(this.el)}render(e){e instanceof HTMLElement?(e._w2field?e._w2field.reset():e._w2field=this,this.el=e,this.init()):console.log("ERROR: Cannot init w2field on empty subject")}init(){let t=this.options,e;if(["INPUT","TEXTAREA"].includes(this.el.tagName.toUpperCase())){switch(this.type){case"text":case"int":case"float":case"money":case"currency":case"percent":case"alphanumeric":case"bin":case"hex":e={min:null,max:null,step:1,autoFormat:!0,autoCorrect:!0,currencyPrefix:w2utils.settings.currencyPrefix,currencySuffix:w2utils.settings.currencySuffix,currencyPrecision:w2utils.settings.currencyPrecision,decimalSymbol:w2utils.settings.decimalSymbol,groupSymbol:w2utils.settings.groupSymbol,arrow:!1,keyboard:!0,precision:null,prefix:"",suffix:""},this.options=w2utils.extend({},e,t),(t=this.options).numberRE=new RegExp("["+t.groupSymbol+"]","g"),t.moneyRE=new RegExp("["+t.currencyPrefix+t.currencySuffix+t.groupSymbol+"]","g"),t.percentRE=new RegExp("["+t.groupSymbol+"%]","g"),["text","alphanumeric","hex","bin"].includes(this.type)&&(t.arrow=!1,t.keyboard=!1);break;case"color":e={prefix:"#",suffix:`<div style="width: ${parseInt(getComputedStyle(this.el)["font-size"])||12}px"> </div>`,arrow:!1,advanced:null,transparent:!0},this.options=w2utils.extend({},e,t),t=this.options;break;case"date":e={format:w2utils.settings.dateFormat,keyboard:!0,autoCorrect:!0,start:null,end:null,blockDates:[],blockWeekdays:[],colored:{},btnNow:!0},this.options=w2utils.extend({type:"date"},e,t),t=this.options,null==query(this.el).attr("placeholder")&&query(this.el).attr("placeholder",t.format);break;case"time":e={format:w2utils.settings.timeFormat,keyboard:!0,autoCorrect:!0,start:null,end:null,btnNow:!0,noMinutes:!1},this.options=w2utils.extend({type:"time"},e,t),t=this.options,null==query(this.el).attr("placeholder")&&query(this.el).attr("placeholder",t.format);break;case"datetime":e={format:w2utils.settings.dateFormat+"|"+w2utils.settings.timeFormat,keyboard:!0,autoCorrect:!0,start:null,end:null,startTime:null,endTime:null,blockDates:[],blockWeekdays:[],colored:{},btnNow:!0,noMinutes:!1},this.options=w2utils.extend({type:"datetime"},e,t),t=this.options,null==query(this.el).attr("placeholder")&&query(this.el).attr("placeholder",t.placeholder||t.format);break;case"list":case"combo":e={items:[],selected:{},url:null,recId:null,recText:null,method:null,debounce:250,postData:{},minLength:1,cacheMax:250,maxDropHeight:350,maxDropWidth:null,minDropWidth:null,match:"begins",icon:null,iconStyle:"",align:"both",altRows:!0,renderDrop:null,compare:null,filter:!0,hideSelected:!1,prefix:"",suffix:"",msgNoItems:"No matches",msgSearch:"Type to search...",openOnFocus:!1,markSearch:!1,onSearch:null,onRequest:null,onLoad:null,onError:null},"function"==typeof t.items&&(t._items_fun=t.items),t.items=w2utils.normMenu.call(this,t.items),"list"===this.type&&(query(this.el).addClass("w2ui-select"),!w2utils.isPlainObject(t.selected))&&Array.isArray(t.items)&&t.items.forEach(e=>{e&&e.id===t.selected&&(t.selected=w2utils.clone(e))}),t=w2utils.extend({},e,t),this.options=t,w2utils.isPlainObject(t.selected)||(t.selected={}),this.selected=t.selected,query(this.el).attr("autocapitalize","off").attr("autocomplete","off").attr("autocorrect","off").attr("spellcheck","false"),null!=t.selected.text&&query(this.el).val(t.selected.text);break;case"enum":e={items:[],selected:[],max:0,url:null,recId:null,recText:null,debounce:250,method:null,postData:{},minLength:1,cacheMax:250,maxItemWidth:250,maxDropHeight:350,maxDropWidth:null,match:"contains",align:"",altRows:!0,openOnFocus:!1,markSearch:!1,renderDrop:null,renderItem:null,compare:null,filter:!0,hideSelected:!0,style:"",msgNoItems:"No matches",msgSearch:"Type to search...",onSearch:null,onRequest:null,onLoad:null,onError:null,onClick:null,onAdd:null,onNew:null,onRemove:null,onMouseEnter:null,onMouseLeave:null,onScroll:null},"function"==typeof(t=w2utils.extend({},e,t,{suffix:""})).items&&(t._items_fun=t.items),t.items=w2utils.normMenu.call(this,t.items),t.selected=w2utils.normMenu.call(this,t.selected),this.options=t,Array.isArray(t.selected)||(t.selected=[]),this.selected=t.selected;break;case"file":e={selected:[],max:0,maxSize:0,maxFileSize:0,maxItemWidth:250,maxDropHeight:350,maxDropWidth:null,readContent:!0,silent:!0,align:"both",altRows:!0,renderItem:null,style:"",onClick:null,onAdd:null,onRemove:null,onMouseEnter:null,onMouseLeave:null},t=w2utils.extend({},e,t),this.options=t,Array.isArray(t.selected)||(t.selected=[]),this.selected=t.selected,null==query(this.el).attr("placeholder")&&query(this.el).attr("placeholder",w2utils.lang("Attach files by dragging and dropping or Click to Select"))}query(this.el).css("box-sizing","border-box").addClass("w2field w2ui-input").off(".w2field").on("change.w2field",e=>{this.change(e)}).on("click.w2field",e=>{this.click(e)}).on("focus.w2field",e=>{this.focus(e)}).on("blur.w2field",e=>{"list"!==this.type&&this.blur(e)}).on("keydown.w2field",e=>{this.keyDown(e)}).on("keyup.w2field",e=>{this.keyUp(e)}),this.addPrefix(),this.addSuffix(),this.addSearch(),this.addMultiSearch(),this.change(new Event("change"))}else console.log("ERROR: w2field could only be applied to INPUT or TEXTAREA.",this.el)}get(){let e;return e=-1!==["list","enum","file"].indexOf(this.type)?this.selected:query(this.el).val()}set(e,t){-1!==["list","enum","file"].indexOf(this.type)?("list"!==this.type&&t?(Array.isArray(this.selected)||(this.selected=[]),this.selected.push(e),(t=w2menu.get(this.el.id+"_menu"))&&(t.options.selected=this.selected)):(null==e&&(e=[]),t="enum"!==this.type||Array.isArray(e)?e:[e],this.selected=t),query(this.el).trigger("input").trigger("change"),this.refresh()):query(this.el).val(e)}setIndex(e,t){if(-1!==["list","enum"].indexOf(this.type)){var i=this.options.items;if(i&&i[e])return"list"==this.type&&(this.selected=i[e]),"enum"==this.type&&(t||(this.selected=[]),this.selected.push(i[e])),(t=w2menu.get(this.el.id+"_menu"))&&(t.options.selected=this.selected),query(this.el).trigger("input").trigger("change"),this.refresh(),!0}return!1}refresh(){let s=this.options;var e=Date.now(),t=getComputedStyle(this.el);if("list"==this.type){if(query(this.el).parent().css("white-space","nowrap"),this.helpers.prefix&&this.helpers.prefix.hide(),!this.helpers.search)return;null==this.selected&&s.icon?s.prefix=`
<span class="w2ui-icon ${s.icon} "style="cursor: pointer; font-size: 14px;
display: inline-block; margin-top: -1px; color: #7F98AD; ${s.iconStyle}">
</span>`:s.prefix="",this.addPrefix();let e=query(this.helpers.search_focus);var i=query(e[0].previousElementSibling);e.css({outline:"none"}),""===e.val()?(e.css("opacity",0),i.css("opacity",0),this.selected?.id?(n=this.selected.text,r=this.findItemIndex(s.items,this.selected.id),null!=n&&query(this.el).val(w2utils.lang(n)).data({selected:n,selectedIndex:r[0]})):(this.el.value="",query(this.el).removeData("selected selectedIndex"))):(e.css("opacity",1),i.css("opacity",1),query(this.el).val(""),setTimeout(()=>{this.helpers.prefix&&this.helpers.prefix.hide(),s.icon?(e.css("margin-left","17px"),query(this.helpers.search).find(".w2ui-icon-search").addClass("show-search")):(e.css("margin-left","0px"),query(this.helpers.search).find(".w2ui-icon-search").removeClass("show-search"))},1)),query(this.el).prop("readOnly")||query(this.el).prop("disabled")?setTimeout(()=>{this.helpers.prefix&&query(this.helpers.prefix).css("opacity","0.6"),this.helpers.suffix&&query(this.helpers.suffix).css("opacity","0.6")},1):setTimeout(()=>{this.helpers.prefix&&query(this.helpers.prefix).css("opacity","1"),this.helpers.suffix&&query(this.helpers.suffix).css("opacity","1")},1)}let l=this.helpers.multi;if(["enum","file"].includes(this.type)&&l){let i="";Array.isArray(this.selected)&&this.selected.forEach((e,t)=>{null!=e&&(i+=`
<div class="li-item" index="${t}" style="max-width: ${parseInt(s.maxItemWidth)}px; ${e.style||""}">
${"function"==typeof s.renderItem?s.renderItem(e,t,`<div class="w2ui-list-remove" index="${t}">  </div>`):`
${e.icon?`<span class="w2ui-icon ${e.icon}"></span>`:""}
<div class="w2ui-list-remove" index="${t}">  </div>
${("enum"===this.type?e.text:e.name)??e.id??e}
${e.size?`<span class="file-size"> - ${w2utils.formatSize(e.size)}</span>`:""}
`}
</div>`)});var r,n=l.find(".w2ui-multi-items");s.style&&l.attr("style",l.attr("style")+";"+s.style),query(this.el).css("z-index","-1"),query(this.el).prop("readOnly")||query(this.el).prop("disabled")?setTimeout(()=>{l[0].scrollTop=0,l.addClass("w2ui-readonly").find(".li-item").css("opacity","0.9").parent().find(".li-search").hide().find("input").prop("readOnly",!0).closest(".w2ui-multi-items").find(".w2ui-list-remove").hide()},1):setTimeout(()=>{l.removeClass("w2ui-readonly").find(".li-item").css("opacity","1").parent().find(".li-search").show().find("input").prop("readOnly",!1).closest(".w2ui-multi-items").find(".w2ui-list-remove").show()},1),0<this.selected?.length&&query(this.el).attr("placeholder",""),l.find(".w2ui-enum-placeholder").remove(),n.find(".li-item").remove(),""!==i?n.prepend(i):null!=query(this.el).attr("placeholder")&&""===l.find("input").val()&&(r=w2utils.stripSpaces(`
padding-top: ${t["padding-top"]};
padding-left: ${t["padding-left"]};
box-sizing: ${t["box-sizing"]};
line-height: ${t["line-height"]};
font-size: ${t["font-size"]};
font-family: ${t["font-family"]};
`),l.prepend(`<div class="w2ui-enum-placeholder" style="${r}">${query(this.el).attr("placeholder")}</div>`)),l.off(".w2item").on("scroll.w2item",e=>{e=this.trigger("scroll",{target:this.el,originalEvent:e});!0!==e.isCancelled&&(w2tooltip.hide(this.el.id+"_preview"),e.finish())}).find(".li-item").on("click.w2item",e=>{var i=query(e.target).closest(".li-item"),s=i.attr("index"),l=this.selected[s];if(!query(i).hasClass("li-search")){e.stopPropagation();let t;if(query(e.target).hasClass("w2ui-list-remove"))query(this.el).prop("readOnly")||query(this.el).prop("disabled")||!0!==(t=this.trigger("remove",{target:this.el,originalEvent:e,item:l})).isCancelled&&(this.selected.splice(s,1),query(this.el).trigger("input").trigger("change"),query(e.target).remove());else if(!0!==(t=this.trigger("click",{target:this.el,originalEvent:e.originalEvent,item:l})).isCancelled){let e=l.tooltip;if("file"===this.type&&(/image/i.test(l.type)&&(e=`
<div class="w2ui-file-preview">
<img src="${l.content?"data:"+l.type+";base64,"+l.content:""}"
style="max-width: 300px">
</div>`),e+=`
<div class="w2ui-file-info">
<div class="file-caption">${w2utils.lang("Name")}:</div>
<div class="file-value">${l.name}</div>
<div class="file-caption">${w2utils.lang("Size")}:</div>
<div class="file-value">${w2utils.formatSize(l.size)}</div>
<div class="file-caption">${w2utils.lang("Type")}:</div>
<div class="file-value file-type">${l.type}</div>
<div class="file-caption">${w2utils.lang("Modified")}:</div>
<div class="file-value">${w2utils.date(l.modified)}</div>
</div>`),e){let t=this.el.id+"_preview";w2tooltip.show({name:t,anchor:i.get(0),html:e,hideOn:["doc-click"],class:""}).show(e=>{query(`#w2overlay-${t} img`).on("load",function(e){var t=this.clientWidth,i=this.clientHeight;t<300&i<300||(i<=t&&300<t&&query(this).css("width","300px"),t<i&&300<i&&query(this).css("height","300px"))}).on("error",function(e){this.style.display="none"})})}t.finish()}}}).on("mouseenter.w2item",e=>{var t=query(e.target).closest(".li-item");query(t).hasClass("li-search")||(t=this.selected[query(e.target).attr("index")],!0!==(e=this.trigger("mouseEnter",{target:this.el,originalEvent:e,item:t})).isCancelled&&e.finish())}).on("mouseleave.w2item",e=>{var t=query(e.target).closest(".li-item");query(t).hasClass("li-search")||(t=this.selected[query(e.target).attr("index")],!0!==(e=this.trigger("mouseLeave",{target:this.el,originalEvent:e,item:t})).isCancelled&&e.finish())}),"enum"===this.type?this.helpers.multi.find("input").css({width:"15px"}):this.helpers.multi.find(".li-search").hide(),this.resize()}return Date.now()-e}resize(){var e=this.el.clientWidth,t=getComputedStyle(this.el),i=this.helpers.search,s=this.helpers.multi,l=this.helpers.suffix,r=this.helpers.prefix,i=(i&&query(i).css("width",e),s&&query(s).css("width",e-parseInt(t["margin-left"],10)-parseInt(t["margin-right"],10)),l&&this.addSuffix(),r&&this.addPrefix(),this.helpers.multi);if(["enum","file"].includes(this.type)&&i){query(this.el).css("height","auto");let e=query(i).find(":scope div.w2ui-multi-items").get(0).clientHeight+5;(e=(e=e<20?20:e)>this.tmp["max-height"]?this.tmp["max-height"]:e)<this.tmp["min-height"]&&(e=this.tmp["min-height"]);s=w2utils.getSize(this.el,"height")-2;s>e&&(e=s),query(i).css({height:e+"px",overflow:e==this.tmp["max-height"]?"auto":"hidden"}),query(i).css("height",e+"px"),query(this.el).css({height:e+"px"})}this.tmp.current_width=e}reset(){null!=this.tmp&&(query(this.el).css("height","auto"),Array("padding-left","padding-right","background-color","border-color").forEach(e=>{this.tmp&&null!=this.tmp["old-"+e]&&(query(this.el).css(e,this.tmp["old-"+e]),delete this.tmp["old-"+e])}),clearInterval(this.tmp.sizeTimer)),query(this.el).val(this.clean(query(this.el).val())).removeClass("w2field").removeData("selected selectedIndex").off(".w2field"),Object.keys(this.helpers).forEach(e=>{query(this.helpers[e]).remove()}),this.helpers={}}clean(e){var t;return e="number"!=typeof e&&(t=this.options,e=String(e).trim(),["int","float","money","currency","percent"].includes(this.type))?""!==(e="string"==typeof e?(e=t.autoFormat&&(["money","currency"].includes(this.type)&&(e=String(e).replace(t.moneyRE,"")),"percent"===this.type&&(e=String(e).replace(t.percentRE,"")),["int","float"].includes(this.type))?String(e).replace(t.numberRE,""):e).replace(/\s+/g,"").replace(new RegExp(t.groupSymbol,"g"),"").replace(t.decimalSymbol,"."):e)&&w2utils.isFloat(e)?Number(e):"":e}format(e){var t=this.options;if(t.autoFormat&&""!==e){switch(this.type){case"money":case"currency":""!==(e=w2utils.formatNumber(e,t.currencyPrecision,!0))&&(e=t.currencyPrefix+e+t.currencySuffix);break;case"percent":""!==(e=w2utils.formatNumber(e,t.precision,!0))&&(e+="%");break;case"float":e=w2utils.formatNumber(e,t.precision,!0);break;case"int":e=w2utils.formatNumber(e,0,!0)}var i=parseInt(1e3).toLocaleString(w2utils.settings.locale,{useGrouping:!0}).slice(1,2);i!==this.options.groupSymbol&&(e=e.replaceAll(i,this.options.groupSymbol))}return e}change(e){if(-1!==["int","float","money","currency","percent"].indexOf(this.type)){var t=query(this.el).val(),i=this.format(this.clean(query(this.el).val()));if(""!==t&&t!=i)return query(this.el).val(i),e.stopPropagation(),e.preventDefault(),!1}if("color"===this.type){let e=query(this.el).val();"rgb"!==e.substr(0,3).toLowerCase()&&(e="#"+e,8!==(t=query(this.el).val().length))&&6!==t&&3!==t&&(e="");i=query(this.el).get(0).nextElementSibling;query(i).find("div").css("background-color",e),query(this.el).hasClass("has-focus")&&this.updateOverlay()}if(-1!==["list","enum","file"].indexOf(this.type)&&this.refresh(),-1!==["date","time","datetime"].indexOf(this.type)){let e=parseInt(this.el.value);w2utils.isInt(this.el.value)&&3e3<e&&("time"===this.type&&(e=w2utils.formatTime(new Date(e),this.options.format)),"date"===this.type&&(e=w2utils.formatDate(new Date(e),this.options.format)),"datetime"===this.type&&(e=w2utils.formatDateTime(new Date(e),this.options.format)),query(this.el).val(e).trigger("input").trigger("change"))}}click(e){["list","combo","enum"].includes(this.type)&&(query(this.el).hasClass("has-focus")||this.focus(e),"combo"==this.type&&this.updateOverlay(),"list"==this.type)&&(this.updateOverlay(),e.stopPropagation()),["date","time","datetime","color"].includes(this.type)&&this.updateOverlay()}focus(e){if("list"==this.type&&document.activeElement==this.el)this.helpers.search_focus.focus();else{if(-1!==["color","date","time","datetime"].indexOf(this.type)){if(query(this.el).prop("readOnly")||query(this.el).prop("disabled"))return;this.updateOverlay()}if(-1!==["list","combo","enum"].indexOf(this.type)){if(query(this.el).prop("readOnly")||query(this.el).prop("disabled"))return void query(this.el).addClass("has-focus");"function"==typeof this.options._items_fun&&(this.options.items=w2utils.normMenu.call(this,this.options._items_fun)),this.helpers.search&&((t=this.helpers.search_focus).value="",t.select()),"enum"==this.type&&(t=query(this.el.previousElementSibling).find(".li-search input").get(0),document.activeElement!==t)&&t.focus(),this.resize(),!1===e.showMenu||!1===this.options.openOnFocus&&!query(this.el).hasClass("has-focus")||setTimeout(()=>{this.updateOverlay()},100)}var t;"file"==this.type&&(t=query(this.el).get(0).previousElementSibling,query(t).addClass("has-focus")),query(this.el).addClass("has-focus")}}blur(e){var i,s=query(this.el).val().trim();if(query(this.el).removeClass("has-focus"),["int","float","money","currency","percent"].includes(this.type)&&""!==s){let e=s,t="";this.isStrValid(s)?(i=this.clean(s),null!=this.options.min&&i<this.options.min&&(e=this.options.min,t="Should be >= "+this.options.min),null!=this.options.max&&i>this.options.max&&(e=this.options.max,t="Should be <= "+this.options.max)):e="",this.options.autoCorrect&&(query(this.el).val(e).trigger("input").trigger("change"),t)&&(w2tooltip.show({name:this.el.id+"_error",anchor:this.el,html:t}),setTimeout(()=>{w2tooltip.hide(this.el.id+"_error")},3e3))}["date","time","datetime"].includes(this.type)&&this.options.autoCorrect&&""!==s&&(i="date"==this.type?w2utils.isDate:"time"==this.type?w2utils.isTime:w2utils.isDateTime,w2date.inRange(this.el.value,this.options)&&i.bind(w2utils)(this.el.value,this.options.format)||query(this.el).val("").trigger("input").trigger("change")),"enum"===this.type&&query(this.helpers.multi).find("input").val("").css("width","15px"),"file"==this.type&&(s=this.el.previousElementSibling,query(s).removeClass("has-focus")),"list"===this.type&&(this.el.value=this.selected?.text??"")}keyDown(t,i){var e,s=this.options,i=t.keyCode||i&&i.keyCode;let l=!1,r,n,a,o,h,d;if(["int","float","money","currency","percent","hex","bin","color","alphanumeric"].includes(this.type)&&!(t.metaKey||t.ctrlKey||t.altKey||this.isStrValid(t.key??"1",!0)||[9,8,13,27,37,38,39,40,46].includes(t.keyCode)))return t.preventDefault(),t.stopPropagation?t.stopPropagation():t.cancelBubble=!0,!1;if(["int","float","money","currency","percent"].includes(this.type)){if(!s.keyboard||query(this.el).prop("readOnly")||query(this.el).prop("disabled"))return;switch(r=parseFloat(query(this.el).val().replace(s.moneyRE,""))||0,n=s.step,(t.ctrlKey||t.metaKey)&&(n=10*s.step),i){case 38:t.shiftKey||(h=r+n<=s.max||null==s.max?Number((r+n).toFixed(12)):s.max,query(this.el).val(h).trigger("input").trigger("change"),l=!0);break;case 40:t.shiftKey||(h=r-n>=s.min||null==s.min?Number((r-n).toFixed(12)):s.min,query(this.el).val(h).trigger("input").trigger("change"),l=!0)}l&&(t.preventDefault(),this.moveCaret2end())}if(["date","datetime"].includes(this.type)){if(!s.keyboard||query(this.el).prop("readOnly")||query(this.el).prop("disabled"))return;var u=("date"==this.type?w2utils.isDate:w2utils.isDateTime).bind(w2utils),c=("date"==this.type?w2utils.formatDate:w2utils.formatDateTime).bind(w2utils);switch(a=864e5,n=1,(t.ctrlKey||t.metaKey)&&(n=10),(o=u(query(this.el).val(),s.format,!0))||(o=new Date,a=0),i){case 38:t.shiftKey||(10==n?o.setMonth(o.getMonth()+1):o.setTime(o.getTime()+a),d=c(o.getTime(),s.format),query(this.el).val(d).trigger("input").trigger("change"),l=!0);break;case 40:t.shiftKey||(10==n?o.setMonth(o.getMonth()-1):o.setTime(o.getTime()-a),d=c(o.getTime(),s.format),query(this.el).val(d).trigger("input").trigger("change"),l=!0)}l&&(t.preventDefault(),this.moveCaret2end(),this.updateOverlay())}if("time"===this.type){if(!s.keyboard||query(this.el).prop("readOnly")||query(this.el).prop("disabled"))return;n=t.ctrlKey||t.metaKey?60:1,r=query(this.el).val();let e=w2date.str2min(r)||w2date.str2min((new Date).getHours()+":"+((new Date).getMinutes()-1));switch(i){case 38:t.shiftKey||(e+=n,l=!0);break;case 40:t.shiftKey||(e-=n,l=!0)}l&&(t.preventDefault(),query(this.el).val(w2date.min2str(e)).trigger("input").trigger("change"),this.moveCaret2end())}if(["list","enum"].includes(this.type))switch(i){case 8:case 46:"list"==this.type?""==query(this.helpers.search_focus).val()&&(this.selected=null,w2menu.hide(this.el.id+"_menu"),query(this.el).val("").trigger("input").trigger("change")):""==query(this.helpers.multi).find("input").val()&&(w2menu.hide(this.el.id+"_menu"),this.selected.pop(),(e=w2menu.get(this.el.id+"_menu"))&&(e.options.selected=this.selected),this.refresh());break;case 9:case 16:break;case 27:w2menu.hide(this.el.id+"_menu"),this.refresh()}}keyUp(t){if("list"==this.type){let e=query(this.helpers.search_focus);""!==e.val()?query(this.el).attr("placeholder",""):query(this.el).attr("placeholder",this.tmp.pholder),13==t.keyCode&&setTimeout(()=>{e.val(""),w2menu.hide(this.el.id+"_menu"),this.refresh()},1),[38,40].includes(t.keyCode)&&!this.tmp.overlay.overlay.displayed&&this.updateOverlay(),this.refresh()}var e,i;"combo"==this.type&&this.updateOverlay(),"enum"==this.type&&(e=this.helpers.multi.find("input"),i=getComputedStyle(e.get(0)),i=w2utils.getStrWidth(e.val(),`font-family: ${i["font-family"]}; font-size: ${i["font-size"]};`),e.css({width:i+15+"px"}),this.resize(),[38,40].includes(t.keyCode))&&!this.tmp.overlay?.overlay?.displayed&&this.updateOverlay()}findItemIndex(e,i,s){let l=[];var t;return s=s||[],["list","combo","enum"].includes(this.type)&&this.options.url&&(t=w2menu.get(this.el.id+"_menu"))&&(e=t.options.items,this.options.items=e),e.forEach((e,t)=>{e.id===i&&(l=s.concat([t]),this.options.index=[t]),0==l.length&&e.items&&0<e.items.length&&(s.push(t),l=this.findItemIndex(e.items,i,s),s.pop())}),l}updateOverlay(e){let l=this.options;if("color"===this.type){if(query(this.el).prop("readOnly")||query(this.el).prop("disabled"))return;w2color.show(w2utils.extend({name:this.el.id+"_color",anchor:this.el,transparent:l.transparent,advanced:l.advanced,color:this.el.value,liveUpdate:!0},this.options)).select(e=>{e=e.detail.color;query(this.el).val(e).trigger("input").trigger("change")}).liveUpdate(e=>{e=e.detail.color;query(this.helpers.suffix).find(":scope > div").css("background-color","#"+e)})}if(["list","combo","enum"].includes(this.type)){var t;this.el;let s=this.el;"enum"===this.type&&(t=this.helpers.multi.get(0),s=query(t).find("input").get(0)),"list"===this.type&&(t=this.selected,w2utils.isPlainObject(t)&&0<Object.keys(t).length&&0<(t=this.findItemIndex(l.items,t.id)).length&&(l.index=t),s=this.helpers.search_focus),!query(this.el).hasClass("has-focus")||this.el.readOnly||this.el.disabled||(t=w2utils.extend({},l,{name:this.el.id+"_menu",anchor:s,selected:this.selected,search:!1,render:l.renderDrop,anchorClass:"",offsetY:5,maxHeight:l.maxDropHeight,maxWidth:l.maxDropWidth,minWidth:l.minDropWidth}),this.tmp.overlay=w2menu.show(t).select(e=>{var t,i;["list","combo"].includes(this.type)?(this.selected=e.detail.item,query(s).val(""),query(this.el).val(this.selected.text).trigger("input").trigger("change"),this.focus({showMenu:!1})):(i=this.selected,(t=e.detail?.item)&&!0!==(e=this.trigger("add",{target:this.el,item:t,originalEvent:e})).isCancelled&&(i.length>=l.max&&0<l.max&&i.pop(),delete t.hidden,i.push(t),query(this.el).trigger("input").trigger("change"),query(this.helpers.multi).find("input").val(""),(i=w2menu.get(this.el.id+"_menu"))&&(i.options.selected=this.selected),e.finish()))}))}!["date","time","datetime"].includes(this.type)||query(this.el).prop("readOnly")||query(this.el).prop("disabled")||w2date.show(w2utils.extend({name:this.el.id+"_date",anchor:this.el,value:this.el.value},this.options)).select(e=>{e=e.detail.date;null!=e&&query(this.el).val(e).trigger("input").trigger("change")})}isStrValid(e,t){let i=!0;switch(this.type){case"int":i=!(!t||!["-",this.options.groupSymbol].includes(e))||w2utils.isInt(e.replace(this.options.numberRE,""));break;case"percent":e=e.replace(/%/g,"");case"float":i=!(!t||!["-","",this.options.decimalSymbol,this.options.groupSymbol].includes(e))||w2utils.isFloat(e.replace(this.options.numberRE,""));break;case"money":case"currency":i=!(!t||!["-",this.options.decimalSymbol,this.options.groupSymbol,this.options.currencyPrefix,this.options.currencySuffix].includes(e))||w2utils.isFloat(e.replace(this.options.moneyRE,""));break;case"bin":i=w2utils.isBin(e);break;case"color":case"hex":i=w2utils.isHex(e);break;case"alphanumeric":i=w2utils.isAlphaNumeric(e)}return i}addPrefix(){var e,t;this.options.prefix&&(t=getComputedStyle(this.el),null==this.tmp["old-padding-left"]&&(this.tmp["old-padding-left"]=t["padding-left"]),this.helpers.prefix&&query(this.helpers.prefix).remove(),query(this.el).before(`<div class="w2ui-field-helper">${this.options.prefix}</div>`),e=query(this.el).get(0).previousElementSibling,query(e).css({color:t.color,"font-family":t["font-family"],"font-size":t["font-size"],height:this.el.clientHeight+"px","padding-top":t["padding-top"],"padding-bottom":t["padding-bottom"],"padding-left":this.tmp["old-padding-left"],"padding-right":0,"margin-top":parseInt(t["margin-top"],10)+2+"px","margin-bottom":parseInt(t["margin-bottom"],10)+1+"px","margin-left":t["margin-left"],"margin-right":0,"z-index":1}),query(this.el).css("padding-left",e.clientWidth+"px !important"),this.helpers.prefix=e)}addSuffix(){if(this.options.suffix||this.options.arrow){let e,t=this;var i=getComputedStyle(this.el),s=(null==this.tmp["old-padding-right"]&&(this.tmp["old-padding-right"]=i["padding-right"]),parseInt(i["padding-right"]||0));this.options.arrow&&(this.helpers.arrow&&query(this.helpers.arrow).remove(),query(this.el).after('<div class="w2ui-field-helper" style="border: 1px solid transparent">  <div class="w2ui-field-up" type="up"> <div class="arrow-up" type="up"></div> </div> <div class="w2ui-field-down" type="down"> <div class="arrow-down" type="down"></div> </div></div>'),e=query(this.el).get(0).nextElementSibling,query(e).css({color:i.color,"font-family":i["font-family"],"font-size":i["font-size"],height:this.el.clientHeight+"px",padding:0,"margin-top":parseInt(i["margin-top"],10)+1+"px","margin-bottom":0,"border-left":"1px solid silver",width:"16px",transform:"translateX(-100%)"}).on("mousedown",function(e){query(e.target).hasClass("arrow-up")&&t.keyDown(e,{keyCode:38}),query(e.target).hasClass("arrow-down")&&t.keyDown(e,{keyCode:40})}),s+=e.clientWidth,query(this.el).css("padding-right",s+"px !important"),this.helpers.arrow=e),""!==this.options.suffix&&(this.helpers.suffix&&query(this.helpers.suffix).remove(),query(this.el).after(`<div class="w2ui-field-helper">${this.options.suffix}</div>`),e=query(this.el).get(0).nextElementSibling,query(e).css({color:i.color,"font-family":i["font-family"],"font-size":i["font-size"],height:this.el.clientHeight+"px","padding-top":i["padding-top"],"padding-bottom":i["padding-bottom"],"padding-left":0,"padding-right":i["padding-right"],"margin-top":parseInt(i["margin-top"],10)+2+"px","margin-bottom":parseInt(i["margin-bottom"],10)+1+"px",transform:"translateX(-100%)"}),query(this.el).css("padding-right",e.clientWidth+"px !important"),this.helpers.suffix=e)}}addSearch(){if("list"===this.type){this.helpers.search&&query(this.helpers.search).remove();let e=parseInt(query(this.el).attr("tabIndex")),t=(isNaN(e)||-1===e||(this.tmp["old-tabIndex"]=e),null!=(e=this.tmp["old-tabIndex"]?this.tmp["old-tabIndex"]:e)&&!isNaN(e)||(e=0),"");var i=`
<div class="w2ui-field-helper">
<span class="w2ui-icon w2ui-icon-search"></span>
<input ${t=null!=query(this.el).attr("id")?'id="'+query(this.el).attr("id")+'_search"':t} type="text" tabIndex="${e}" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"/>
</div>`,i=(query(this.el).attr("tabindex",-1).before(i),query(this.el).get(0).previousElementSibling),s=(this.helpers.search=i,this.helpers.search_focus=query(i).find("input").get(0),getComputedStyle(this.el));query(i).css({width:this.el.clientWidth+"px","margin-top":s["margin-top"],"margin-left":s["margin-left"],"margin-bottom":s["margin-bottom"],"margin-right":s["margin-right"]}).find("input").css({cursor:"default",width:"100%",opacity:1,padding:s.padding,margin:s.margin,border:"1px solid transparent","background-color":"transparent"}),query(i).find("input").off(".helper").on("focus.helper",e=>{query(e.target).val(""),this.tmp.pholder=query(this.el).attr("placeholder")??"",this.focus(e),e.stopPropagation()}).on("blur.helper",e=>{query(e.target).val(""),null!=this.tmp.pholder&&query(this.el).attr("placeholder",this.tmp.pholder),this.blur(e),e.stopPropagation()}).on("keydown.helper",e=>{this.keyDown(e)}).on("keyup.helper",e=>{this.keyUp(e)}),query(i).on("click",e=>{query(e.target).find("input").focus()})}}addMultiSearch(){if(["enum","file"].includes(this.type)){query(this.helpers.multi).remove();let e="";var l,r,n=getComputedStyle(this.el),a=w2utils.stripSpaces(`
margin-top: 0px;
margin-bottom: 0px;
margin-left: ${n["margin-left"]};
margin-right: ${n["margin-right"]};
width: ${w2utils.getSize(this.el,"width")-parseInt(n["margin-left"],10)-parseInt(n["margin-right"],10)}px;
`);null==this.tmp["min-height"]&&(l=this.tmp["min-height"]=parseInt(("none"!=n["min-height"]?n["min-height"]:0)||0),r=parseInt(n.height),this.tmp["min-height"]=Math.max(l,r)),null==this.tmp["max-height"]&&"none"!=n["max-height"]&&(this.tmp["max-height"]=parseInt(n["max-height"]));let t="",i=(null!=query(this.el).attr("id")&&(t=`id="${query(this.el).attr("id")}_search"`),parseInt(query(this.el).attr("tabIndex"))),s=(isNaN(i)||-1===i||(this.tmp["old-tabIndex"]=i),null!=(i=this.tmp["old-tabIndex"]?this.tmp["old-tabIndex"]:i)&&!isNaN(i)||(i=0),"enum"===this.type&&(e=`
<div class="w2ui-field-helper w2ui-list" style="${a}">
<div class="w2ui-multi-items">
<div class="li-search">
<input ${t} type="text" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"
tabindex="${i}"
${query(this.el).prop("readOnly")?"readonly":""}
${query(this.el).prop("disabled")?"disabled":""}>
</div>
</div>
</div>`),"file"===this.type&&(e=`
<div class="w2ui-field-helper w2ui-list" style="${a}">
<div class="w2ui-multi-file">
<input name="attachment" class="file-input" type="file" tabindex="-1"'
style="width: 100%; height: 100%; opacity: 0" title=""
${1!==this.options.max?"multiple":""}
${query(this.el).prop("readOnly")||query(this.el).prop("disabled")?"disabled":""}
${query(this.el).attr("accept")?' accept="'+query(this.el).attr("accept")+'"':""}>
</div>
<div class="w2ui-multi-items">
<div class="li-search" style="display: none">
<input ${t} type="text" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false"
tabindex="${i}"
${query(this.el).prop("readOnly")?"readonly":""}
${query(this.el).prop("disabled")?"disabled":""}>
</div>
</div>
</div>`),this.tmp["old-background-color"]=n["background-color"],this.tmp["old-border-color"]=n["border-color"],query(this.el).before(e).css({"border-color":"transparent","background-color":"transparent"}),query(this.el.previousElementSibling));this.helpers.multi=s,query(this.el).attr("tabindex",-1),s.on("click",e=>{this.focus(e)}),s.find("input:not(.file-input)").on("click",e=>{this.click(e)}).on("focus",e=>{this.focus(e)}).on("blur",e=>{this.blur(e)}).on("keydown",e=>{this.keyDown(e)}).on("keyup",e=>{this.keyUp(e)}),"file"===this.type&&s.find("input.file-input").off(".drag").on("click.drag",e=>{e.stopPropagation(),query(this.el).prop("readOnly")||query(this.el).prop("disabled")||this.focus(e)}).on("dragenter.drag",e=>{query(this.el).prop("readOnly")||query(this.el).prop("disabled")||s.addClass("w2ui-file-dragover")}).on("dragleave.drag",e=>{query(this.el).prop("readOnly")||query(this.el).prop("disabled")||s.removeClass("w2ui-file-dragover")}).on("drop.drag",e=>{query(this.el).prop("readOnly")||query(this.el).prop("disabled")||(s.removeClass("w2ui-file-dragover"),Array.from(e.dataTransfer.files).forEach(e=>{this.addFile(e)}),this.focus(e),e.preventDefault(),e.stopPropagation())}).on("dragover.drag",e=>{e.preventDefault(),e.stopPropagation()}).on("change.drag",e=>{void 0!==e.target.files&&Array.from(e.target.files).forEach(e=>{this.addFile(e)}),this.focus(e)}),this.refresh()}}addFile(t){var e=this.options,s=this.selected;let l={name:t.name,type:t.type,modified:t.lastModifiedDate,size:t.size,content:null,file:t},i=0,r=0,n=[],a=(Array.isArray(s)&&s.forEach(e=>{e.name==t.name&&e.size==t.size&&n.push(w2utils.lang('The file "${name}" (${size}) is already added.',{name:t.name,size:w2utils.formatSize(t.size)})),i+=e.size,r++}),0!==e.maxFileSize&&l.size>e.maxFileSize&&n.push(w2utils.lang("Maximum file size is ${size}",{size:w2utils.formatSize(e.maxFileSize)})),0!==e.maxSize&&i+l.size>e.maxSize&&n.push(w2utils.lang("Maximum total size is ${size}",{size:w2utils.formatSize(e.maxSize)})),0!==e.max&&r>=e.max&&n.push(w2utils.lang("Maximum number of files is ${count}",{count:e.max})),this.trigger("add",{target:this.el,file:l,total:r,totalSize:i,errors:n}));if(!0!==a.isCancelled)if(!0!==e.silent&&0<n.length)w2tooltip.show({anchor:this.el,html:"Errors: "+n.join("<br>")}),console.log("ERRORS (while adding files): ",n);else if(s.push(l),"undefined"!=typeof FileReader&&!0===e.readContent){s=new FileReader;let i=this;s.onload=function(e){var e=e.target.result,t=e.indexOf(",");l.content=e.substr(t+1),i.refresh(),query(i.el).trigger("input").trigger("change"),a.finish()},s.readAsDataURL(t)}else this.refresh(),query(this.el).trigger("input").trigger("change"),a.finish()}moveCaret2end(){setTimeout(()=>{this.el.setSelectionRange(this.el.value.length,this.el.value.length)},0)}}!function(r){function e(){var t,i;t=window,i={w2ui:w2ui,w2utils:w2utils,query:query,w2locale:w2locale,w2event:w2event,w2base:w2base,w2popup:w2popup,w2alert:w2alert,w2confirm:w2confirm,w2prompt:w2prompt,Dialog:Dialog,w2tooltip:w2tooltip,w2menu:w2menu,w2color:w2color,w2date:w2date,Tooltip:Tooltip,w2toolbar:w2toolbar,w2sidebar:w2sidebar,w2tabs:w2tabs,w2layout:w2layout,w2grid:w2grid,w2form:w2form,w2field:w2field},Object.keys(i).forEach(e=>{t[e]=i[e]})}var t=String(void 0).split("?")[1]||"";function i(t,i){var e;if(r.isPlainObject(t)){let e;return"w2form"==i&&(e=new w2form(t),0<this.find(".w2ui-field").length)&&(e.formHTML=this.html()),"w2grid"==i&&(e=new w2grid(t)),"w2layout"==i&&(e=new w2layout(t)),"w2sidebar"==i&&(e=new w2sidebar(t)),"w2tabs"==i&&(e=new w2tabs(t)),"w2toolbar"==i&&(e=new w2toolbar(t)),0!==r(this).length&&e.render(this[0]),e}return(e=w2ui[r(this).attr("name")])?0<arguments.length?(e[t]&&e[t].apply(e,Array.prototype.slice.call(arguments,1)),this):e:null}"globals"!=t&&"globals="!=t.substr(0,8)||e(),r&&(r.w2globals=e,r.fn.w2render=function(e){0<r(this).length&&("string"==typeof e&&w2ui[e]&&w2ui[e].render(r(this)[0]),"object"==typeof e)&&e.render(r(this)[0])},r.fn.w2destroy=function(e){"string"==typeof(e=!e&&0<this.length?this.attr("name"):e)&&w2ui[e]&&w2ui[e].destroy(),"object"==typeof e&&e.destroy()},r.fn.w2field=function(s,l){return 0===arguments.length?r(this).data("w2field"):this.each((e,t)=>{let i=r(t).data("w2field");return i,(i=new w2field(s,l)).render(t),i})},r.fn.w2form=function(e){return i.call(this,e,"w2form")},r.fn.w2grid=function(e){return i.call(this,e,"w2grid")},r.fn.w2layout=function(e){return i.call(this,e,"w2layout")},r.fn.w2sidebar=function(e){return i.call(this,e,"w2sidebar")},r.fn.w2tabs=function(e){return i.call(this,e,"w2tabs")},r.fn.w2toolbar=function(e){return i.call(this,e,"w2toolbar")},r.fn.w2popup=function(e){0<this.length?w2popup.template(this[0],null,e):e.url&&w2popup.load(e)},r.fn.w2marker=function(){let i=Array.from(arguments);return Array.isArray(i[0])&&(i=i[0]),r(this).each((e,t)=>{w2utils.marker(t,i)})},r.fn.w2tag=function(i,s){return this.each((e,t)=>{null==i&&null==s?w2tooltip.hide():("object"==typeof i?s=i:(s=s??{}).html=i,w2tooltip.show(t,s))})},r.fn.w2overlay=function(i,s){return this.each((e,t)=>{null==i&&null==s?w2tooltip.hide():("object"==typeof i?s=i:s.html=i,Object.assign(s,{class:"w2ui-white",hideOn:["doc-click"]}),w2tooltip.show(t,s))})},r.fn.w2menu=function(i,s){return this.each((e,t)=>{"object"==typeof i&&(s=i),"object"==typeof i?s=i:s.items=i,w2menu.show(t,s)})},r.fn.w2color=function(i,s){return this.each((e,t)=>{t=w2color.show(t,i);"function"==typeof s&&t.select(s)})})}(window.jQuery),function(t,i){if("function"==typeof define&&define.amd)return define(()=>i);if("undefined"!=typeof exports){if("undefined"!=typeof module&&module.exports)return exports=module.exports=i;t=exports}t&&Object.keys(i).forEach(e=>{t[e]=i[e]})}(self,{w2ui:w2ui,w2utils:w2utils,query:query,w2locale:w2locale,w2event:w2event,w2base:w2base,w2popup:w2popup,w2alert:w2alert,w2confirm:w2confirm,w2prompt:w2prompt,Dialog:Dialog,w2tooltip:w2tooltip,w2menu:w2menu,w2color:w2color,w2date:w2date,Tooltip:Tooltip,w2toolbar:w2toolbar,w2sidebar:w2sidebar,w2tabs:w2tabs,w2layout:w2layout,w2grid:w2grid,w2form:w2form,w2field:w2field});